project
string | commit_id
string | target
int64 | func
string | cwe
string | big_vul_idx
string | idx
int64 | hash
string | size
float64 | message
string | dataset
string |
|---|---|---|---|---|---|---|---|---|---|---|
linux
|
8700af2cc18c919b2a83e74e0479038fd113c15d
| 1
|
static void rtrs_clt_dev_release(struct device *dev)
{
struct rtrs_clt_sess *clt = container_of(dev, struct rtrs_clt_sess,
dev);
kfree(clt);
}
| null | null | 199,712
|
99949609061346084103219008254729298367
| 7
|
RDMA/rtrs-clt: Fix possible double free in error case
Callback function rtrs_clt_dev_release() for put_device() calls kfree(clt)
to free memory. We shouldn't call kfree(clt) again, and we can't use the
clt after kfree too.
Replace device_register() with device_initialize() and device_add() so that
dev_set_name can() be used appropriately.
Move mutex_destroy() to the release function so it can be called in
the alloc_clt err path.
Fixes: eab098246625 ("RDMA/rtrs-clt: Refactor the failure cases in alloc_clt")
Link: https://lore.kernel.org/r/[email protected]
Reported-by: Miaoqian Lin <[email protected]>
Signed-off-by: Md Haris Iqbal <[email protected]>
Reviewed-by: Jack Wang <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
|
other
|
jdk11u
|
132745902a4601dc64b2c8ca112ca30292feccb4
| 1
|
void LinkResolver::resolve_handle_call(CallInfo& result,
const LinkInfo& link_info,
TRAPS) {
// JSR 292: this must be an implicitly generated method MethodHandle.invokeExact(*...) or similar
Klass* resolved_klass = link_info.resolved_klass();
assert(resolved_klass == SystemDictionary::MethodHandle_klass() ||
resolved_klass == SystemDictionary::VarHandle_klass(), "");
assert(MethodHandles::is_signature_polymorphic_name(link_info.name()), "");
Handle resolved_appendix;
Handle resolved_method_type;
methodHandle resolved_method = lookup_polymorphic_method(link_info,
&resolved_appendix, &resolved_method_type, CHECK);
result.set_handle(resolved_klass, resolved_method, resolved_appendix, resolved_method_type, CHECK);
}
| null | null | 199,766
|
59171638359154183667239731490398433321
| 14
|
8281866: Enhance MethodHandle invocations
Reviewed-by: mbaesken
Backport-of: d974d9da365f787f67971d88c79371c8b0769f75
|
other
|
hexchat
|
4e061a43b3453a9856d34250c3913175c45afe9d
| 1
|
inbound_cap_ls (server *serv, char *nick, char *extensions_str,
const message_tags_data *tags_data)
{
char buffer[256]; /* buffer for requesting capabilities and emitting the signal */
guint32 want_cap; /* format the CAP REQ string based on previous capabilities being requested or not */
guint32 want_sasl; /* CAP END shouldn't be sent when SASL is requested, it needs further responses */
char **extensions;
int i;
EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPLIST, serv->server_session, nick,
extensions_str, NULL, NULL, 0, tags_data->timestamp);
want_cap = 0;
want_sasl = 0;
extensions = g_strsplit (extensions_str, " ", 0);
strcpy (buffer, "CAP REQ :");
for (i=0; extensions[i]; i++)
{
const char *extension = extensions[i];
if (!strcmp (extension, "identify-msg"))
{
strcat (buffer, "identify-msg ");
want_cap = 1;
}
if (!strcmp (extension, "multi-prefix"))
{
strcat (buffer, "multi-prefix ");
want_cap = 1;
}
if (!strcmp (extension, "away-notify"))
{
strcat (buffer, "away-notify ");
want_cap = 1;
}
if (!strcmp (extension, "account-notify"))
{
strcat (buffer, "account-notify ");
want_cap = 1;
}
if (!strcmp (extension, "extended-join"))
{
strcat (buffer, "extended-join ");
want_cap = 1;
}
if (!strcmp (extension, "userhost-in-names"))
{
strcat (buffer, "userhost-in-names ");
want_cap = 1;
}
/* bouncers can prefix a name space to the extension so we should use.
* znc <= 1.0 uses "znc.in/server-time" and newer use "znc.in/server-time-iso".
*/
if (!strcmp (extension, "znc.in/server-time-iso"))
{
strcat (buffer, "znc.in/server-time-iso ");
want_cap = 1;
}
if (!strcmp (extension, "znc.in/server-time"))
{
strcat (buffer, "znc.in/server-time ");
want_cap = 1;
}
if (prefs.hex_irc_cap_server_time
&& !strcmp (extension, "server-time"))
{
strcat (buffer, "server-time ");
want_cap = 1;
}
/* if the SASL password is set AND auth mode is set to SASL, request SASL auth */
if (!strcmp (extension, "sasl")
&& ((serv->loginmethod == LOGIN_SASL && strlen (serv->password) != 0)
|| (serv->loginmethod == LOGIN_SASLEXTERNAL && serv->have_cert)))
{
strcat (buffer, "sasl ");
want_cap = 1;
want_sasl = 1;
}
}
g_strfreev (extensions);
if (want_cap)
{
/* buffer + 9 = emit buffer without "CAP REQ :" */
EMIT_SIGNAL_TIMESTAMP (XP_TE_CAPREQ, serv->server_session,
buffer + 9, NULL, NULL, NULL, 0,
tags_data->timestamp);
tcp_sendf (serv, "%s\r\n", g_strchomp (buffer));
}
if (!want_sasl)
{
/* if we use SASL, CAP END is dealt via raw numerics */
serv->sent_capend = TRUE;
tcp_send_len (serv, "CAP END\r\n", 9);
}
}
| null | null | 199,767
|
12686496963225899782252465945305475091
| 101
|
Clean up handling CAP LS
|
other
|
puma
|
acdc3ae571dfae0e045cf09a295280127db65c7f
| 1
|
size_t puma_parser_execute(puma_parser *parser, const char *buffer, size_t len, size_t off) {
const char *p, *pe;
int cs = parser->cs;
assert(off <= len && "offset past end of buffer");
p = buffer+off;
pe = buffer+len;
/* assert(*pe == '\0' && "pointer does not end on NUL"); */
assert((size_t) (pe - p) == len - off && "pointers aren't same distance");
#line 87 "ext/puma_http11/http11_parser.c"
{
if ( p == pe )
goto _test_eof;
switch ( cs )
{
case 1:
switch( (*p) ) {
case 36: goto tr0;
case 95: goto tr0;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto tr0;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto tr0;
} else
goto tr0;
goto st0;
st0:
cs = 0;
goto _out;
tr0:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st2;
st2:
if ( ++p == pe )
goto _test_eof2;
case 2:
#line 118 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st27;
case 95: goto st27;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st27;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st27;
} else
goto st27;
goto st0;
tr2:
#line 50 "ext/puma_http11/http11_parser.rl"
{
parser->request_method(parser, PTR_TO(mark), LEN(mark, p));
}
goto st3;
st3:
if ( ++p == pe )
goto _test_eof3;
case 3:
#line 143 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 42: goto tr4;
case 43: goto tr5;
case 47: goto tr6;
case 58: goto tr7;
}
if ( (*p) < 65 ) {
if ( 45 <= (*p) && (*p) <= 57 )
goto tr5;
} else if ( (*p) > 90 ) {
if ( 97 <= (*p) && (*p) <= 122 )
goto tr5;
} else
goto tr5;
goto st0;
tr4:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st4;
st4:
if ( ++p == pe )
goto _test_eof4;
case 4:
#line 167 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr8;
case 35: goto tr9;
}
goto st0;
tr8:
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st5;
tr31:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
#line 56 "ext/puma_http11/http11_parser.rl"
{
parser->fragment(parser, PTR_TO(mark), LEN(mark, p));
}
goto st5;
tr33:
#line 56 "ext/puma_http11/http11_parser.rl"
{
parser->fragment(parser, PTR_TO(mark), LEN(mark, p));
}
goto st5;
tr37:
#line 69 "ext/puma_http11/http11_parser.rl"
{
parser->request_path(parser, PTR_TO(mark), LEN(mark,p));
}
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st5;
tr41:
#line 60 "ext/puma_http11/http11_parser.rl"
{ MARK(query_start, p); }
#line 61 "ext/puma_http11/http11_parser.rl"
{
parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));
}
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st5;
tr44:
#line 61 "ext/puma_http11/http11_parser.rl"
{
parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));
}
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st5;
st5:
if ( ++p == pe )
goto _test_eof5;
case 5:
#line 229 "ext/puma_http11/http11_parser.c"
if ( (*p) == 72 )
goto tr10;
goto st0;
tr10:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st6;
st6:
if ( ++p == pe )
goto _test_eof6;
case 6:
#line 241 "ext/puma_http11/http11_parser.c"
if ( (*p) == 84 )
goto st7;
goto st0;
st7:
if ( ++p == pe )
goto _test_eof7;
case 7:
if ( (*p) == 84 )
goto st8;
goto st0;
st8:
if ( ++p == pe )
goto _test_eof8;
case 8:
if ( (*p) == 80 )
goto st9;
goto st0;
st9:
if ( ++p == pe )
goto _test_eof9;
case 9:
if ( (*p) == 47 )
goto st10;
goto st0;
st10:
if ( ++p == pe )
goto _test_eof10;
case 10:
if ( 48 <= (*p) && (*p) <= 57 )
goto st11;
goto st0;
st11:
if ( ++p == pe )
goto _test_eof11;
case 11:
if ( (*p) == 46 )
goto st12;
if ( 48 <= (*p) && (*p) <= 57 )
goto st11;
goto st0;
st12:
if ( ++p == pe )
goto _test_eof12;
case 12:
if ( 48 <= (*p) && (*p) <= 57 )
goto st13;
goto st0;
st13:
if ( ++p == pe )
goto _test_eof13;
case 13:
if ( (*p) == 13 )
goto tr18;
if ( 48 <= (*p) && (*p) <= 57 )
goto st13;
goto st0;
tr18:
#line 65 "ext/puma_http11/http11_parser.rl"
{
parser->http_version(parser, PTR_TO(mark), LEN(mark, p));
}
goto st14;
tr26:
#line 46 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
#line 47 "ext/puma_http11/http11_parser.rl"
{
parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p));
}
goto st14;
tr29:
#line 47 "ext/puma_http11/http11_parser.rl"
{
parser->http_field(parser, PTR_TO(field_start), parser->field_len, PTR_TO(mark), LEN(mark, p));
}
goto st14;
st14:
if ( ++p == pe )
goto _test_eof14;
case 14:
#line 322 "ext/puma_http11/http11_parser.c"
if ( (*p) == 10 )
goto st15;
goto st0;
st15:
if ( ++p == pe )
goto _test_eof15;
case 15:
switch( (*p) ) {
case 13: goto st16;
case 33: goto tr21;
case 124: goto tr21;
case 126: goto tr21;
}
if ( (*p) < 45 ) {
if ( (*p) > 39 ) {
if ( 42 <= (*p) && (*p) <= 43 )
goto tr21;
} else if ( (*p) >= 35 )
goto tr21;
} else if ( (*p) > 46 ) {
if ( (*p) < 65 ) {
if ( 48 <= (*p) && (*p) <= 57 )
goto tr21;
} else if ( (*p) > 90 ) {
if ( 94 <= (*p) && (*p) <= 122 )
goto tr21;
} else
goto tr21;
} else
goto tr21;
goto st0;
st16:
if ( ++p == pe )
goto _test_eof16;
case 16:
if ( (*p) == 10 )
goto tr22;
goto st0;
tr22:
#line 73 "ext/puma_http11/http11_parser.rl"
{
parser->body_start = p - buffer + 1;
parser->header_done(parser, p + 1, pe - p - 1);
{p++; cs = 46; goto _out;}
}
goto st46;
st46:
if ( ++p == pe )
goto _test_eof46;
case 46:
#line 373 "ext/puma_http11/http11_parser.c"
goto st0;
tr21:
#line 40 "ext/puma_http11/http11_parser.rl"
{ MARK(field_start, p); }
#line 41 "ext/puma_http11/http11_parser.rl"
{ snake_upcase_char((char *)p); }
goto st17;
tr23:
#line 41 "ext/puma_http11/http11_parser.rl"
{ snake_upcase_char((char *)p); }
goto st17;
st17:
if ( ++p == pe )
goto _test_eof17;
case 17:
#line 389 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 33: goto tr23;
case 58: goto tr24;
case 124: goto tr23;
case 126: goto tr23;
}
if ( (*p) < 45 ) {
if ( (*p) > 39 ) {
if ( 42 <= (*p) && (*p) <= 43 )
goto tr23;
} else if ( (*p) >= 35 )
goto tr23;
} else if ( (*p) > 46 ) {
if ( (*p) < 65 ) {
if ( 48 <= (*p) && (*p) <= 57 )
goto tr23;
} else if ( (*p) > 90 ) {
if ( 94 <= (*p) && (*p) <= 122 )
goto tr23;
} else
goto tr23;
} else
goto tr23;
goto st0;
tr24:
#line 42 "ext/puma_http11/http11_parser.rl"
{
parser->field_len = LEN(field_start, p);
}
goto st18;
tr27:
#line 46 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st18;
st18:
if ( ++p == pe )
goto _test_eof18;
case 18:
#line 428 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 13: goto tr26;
case 32: goto tr27;
}
goto tr25;
tr25:
#line 46 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st19;
st19:
if ( ++p == pe )
goto _test_eof19;
case 19:
#line 442 "ext/puma_http11/http11_parser.c"
if ( (*p) == 13 )
goto tr29;
goto st19;
tr9:
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st20;
tr38:
#line 69 "ext/puma_http11/http11_parser.rl"
{
parser->request_path(parser, PTR_TO(mark), LEN(mark,p));
}
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st20;
tr42:
#line 60 "ext/puma_http11/http11_parser.rl"
{ MARK(query_start, p); }
#line 61 "ext/puma_http11/http11_parser.rl"
{
parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));
}
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st20;
tr45:
#line 61 "ext/puma_http11/http11_parser.rl"
{
parser->query_string(parser, PTR_TO(query_start), LEN(query_start, p));
}
#line 53 "ext/puma_http11/http11_parser.rl"
{
parser->request_uri(parser, PTR_TO(mark), LEN(mark, p));
}
goto st20;
st20:
if ( ++p == pe )
goto _test_eof20;
case 20:
#line 488 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr31;
case 60: goto st0;
case 62: goto st0;
case 127: goto st0;
}
if ( (*p) > 31 ) {
if ( 34 <= (*p) && (*p) <= 35 )
goto st0;
} else if ( (*p) >= 0 )
goto st0;
goto tr30;
tr30:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st21;
st21:
if ( ++p == pe )
goto _test_eof21;
case 21:
#line 509 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr33;
case 60: goto st0;
case 62: goto st0;
case 127: goto st0;
}
if ( (*p) > 31 ) {
if ( 34 <= (*p) && (*p) <= 35 )
goto st0;
} else if ( (*p) >= 0 )
goto st0;
goto st21;
tr5:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st22;
st22:
if ( ++p == pe )
goto _test_eof22;
case 22:
#line 530 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 43: goto st22;
case 58: goto st23;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st22;
} else if ( (*p) > 57 ) {
if ( (*p) > 90 ) {
if ( 97 <= (*p) && (*p) <= 122 )
goto st22;
} else if ( (*p) >= 65 )
goto st22;
} else
goto st22;
goto st0;
tr7:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st23;
st23:
if ( ++p == pe )
goto _test_eof23;
case 23:
#line 555 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr8;
case 34: goto st0;
case 35: goto tr9;
case 60: goto st0;
case 62: goto st0;
case 127: goto st0;
}
if ( 0 <= (*p) && (*p) <= 31 )
goto st0;
goto st23;
tr6:
#line 37 "ext/puma_http11/http11_parser.rl"
{ MARK(mark, p); }
goto st24;
st24:
if ( ++p == pe )
goto _test_eof24;
case 24:
#line 575 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr37;
case 34: goto st0;
case 35: goto tr38;
case 60: goto st0;
case 62: goto st0;
case 63: goto tr39;
case 127: goto st0;
}
if ( 0 <= (*p) && (*p) <= 31 )
goto st0;
goto st24;
tr39:
#line 69 "ext/puma_http11/http11_parser.rl"
{
parser->request_path(parser, PTR_TO(mark), LEN(mark,p));
}
goto st25;
st25:
if ( ++p == pe )
goto _test_eof25;
case 25:
#line 598 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr41;
case 34: goto st0;
case 35: goto tr42;
case 60: goto st0;
case 62: goto st0;
case 127: goto st0;
}
if ( 0 <= (*p) && (*p) <= 31 )
goto st0;
goto tr40;
tr40:
#line 60 "ext/puma_http11/http11_parser.rl"
{ MARK(query_start, p); }
goto st26;
st26:
if ( ++p == pe )
goto _test_eof26;
case 26:
#line 618 "ext/puma_http11/http11_parser.c"
switch( (*p) ) {
case 32: goto tr44;
case 34: goto st0;
case 35: goto tr45;
case 60: goto st0;
case 62: goto st0;
case 127: goto st0;
}
if ( 0 <= (*p) && (*p) <= 31 )
goto st0;
goto st26;
st27:
if ( ++p == pe )
goto _test_eof27;
case 27:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st28;
case 95: goto st28;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st28;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st28;
} else
goto st28;
goto st0;
st28:
if ( ++p == pe )
goto _test_eof28;
case 28:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st29;
case 95: goto st29;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st29;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st29;
} else
goto st29;
goto st0;
st29:
if ( ++p == pe )
goto _test_eof29;
case 29:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st30;
case 95: goto st30;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st30;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st30;
} else
goto st30;
goto st0;
st30:
if ( ++p == pe )
goto _test_eof30;
case 30:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st31;
case 95: goto st31;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st31;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st31;
} else
goto st31;
goto st0;
st31:
if ( ++p == pe )
goto _test_eof31;
case 31:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st32;
case 95: goto st32;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st32;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st32;
} else
goto st32;
goto st0;
st32:
if ( ++p == pe )
goto _test_eof32;
case 32:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st33;
case 95: goto st33;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st33;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st33;
} else
goto st33;
goto st0;
st33:
if ( ++p == pe )
goto _test_eof33;
case 33:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st34;
case 95: goto st34;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st34;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st34;
} else
goto st34;
goto st0;
st34:
if ( ++p == pe )
goto _test_eof34;
case 34:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st35;
case 95: goto st35;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st35;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st35;
} else
goto st35;
goto st0;
st35:
if ( ++p == pe )
goto _test_eof35;
case 35:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st36;
case 95: goto st36;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st36;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st36;
} else
goto st36;
goto st0;
st36:
if ( ++p == pe )
goto _test_eof36;
case 36:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st37;
case 95: goto st37;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st37;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st37;
} else
goto st37;
goto st0;
st37:
if ( ++p == pe )
goto _test_eof37;
case 37:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st38;
case 95: goto st38;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st38;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st38;
} else
goto st38;
goto st0;
st38:
if ( ++p == pe )
goto _test_eof38;
case 38:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st39;
case 95: goto st39;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st39;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st39;
} else
goto st39;
goto st0;
st39:
if ( ++p == pe )
goto _test_eof39;
case 39:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st40;
case 95: goto st40;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st40;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st40;
} else
goto st40;
goto st0;
st40:
if ( ++p == pe )
goto _test_eof40;
case 40:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st41;
case 95: goto st41;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st41;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st41;
} else
goto st41;
goto st0;
st41:
if ( ++p == pe )
goto _test_eof41;
case 41:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st42;
case 95: goto st42;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st42;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st42;
} else
goto st42;
goto st0;
st42:
if ( ++p == pe )
goto _test_eof42;
case 42:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st43;
case 95: goto st43;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st43;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st43;
} else
goto st43;
goto st0;
st43:
if ( ++p == pe )
goto _test_eof43;
case 43:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st44;
case 95: goto st44;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st44;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st44;
} else
goto st44;
goto st0;
st44:
if ( ++p == pe )
goto _test_eof44;
case 44:
switch( (*p) ) {
case 32: goto tr2;
case 36: goto st45;
case 95: goto st45;
}
if ( (*p) < 48 ) {
if ( 45 <= (*p) && (*p) <= 46 )
goto st45;
} else if ( (*p) > 57 ) {
if ( 65 <= (*p) && (*p) <= 90 )
goto st45;
} else
goto st45;
goto st0;
st45:
if ( ++p == pe )
goto _test_eof45;
case 45:
if ( (*p) == 32 )
goto tr2;
goto st0;
}
_test_eof2: cs = 2; goto _test_eof;
_test_eof3: cs = 3; goto _test_eof;
_test_eof4: cs = 4; goto _test_eof;
_test_eof5: cs = 5; goto _test_eof;
_test_eof6: cs = 6; goto _test_eof;
_test_eof7: cs = 7; goto _test_eof;
_test_eof8: cs = 8; goto _test_eof;
_test_eof9: cs = 9; goto _test_eof;
_test_eof10: cs = 10; goto _test_eof;
_test_eof11: cs = 11; goto _test_eof;
_test_eof12: cs = 12; goto _test_eof;
_test_eof13: cs = 13; goto _test_eof;
_test_eof14: cs = 14; goto _test_eof;
_test_eof15: cs = 15; goto _test_eof;
_test_eof16: cs = 16; goto _test_eof;
_test_eof46: cs = 46; goto _test_eof;
_test_eof17: cs = 17; goto _test_eof;
_test_eof18: cs = 18; goto _test_eof;
_test_eof19: cs = 19; goto _test_eof;
_test_eof20: cs = 20; goto _test_eof;
_test_eof21: cs = 21; goto _test_eof;
_test_eof22: cs = 22; goto _test_eof;
_test_eof23: cs = 23; goto _test_eof;
_test_eof24: cs = 24; goto _test_eof;
_test_eof25: cs = 25; goto _test_eof;
_test_eof26: cs = 26; goto _test_eof;
_test_eof27: cs = 27; goto _test_eof;
_test_eof28: cs = 28; goto _test_eof;
_test_eof29: cs = 29; goto _test_eof;
_test_eof30: cs = 30; goto _test_eof;
_test_eof31: cs = 31; goto _test_eof;
_test_eof32: cs = 32; goto _test_eof;
_test_eof33: cs = 33; goto _test_eof;
_test_eof34: cs = 34; goto _test_eof;
_test_eof35: cs = 35; goto _test_eof;
_test_eof36: cs = 36; goto _test_eof;
_test_eof37: cs = 37; goto _test_eof;
_test_eof38: cs = 38; goto _test_eof;
_test_eof39: cs = 39; goto _test_eof;
_test_eof40: cs = 40; goto _test_eof;
_test_eof41: cs = 41; goto _test_eof;
_test_eof42: cs = 42; goto _test_eof;
_test_eof43: cs = 43; goto _test_eof;
_test_eof44: cs = 44; goto _test_eof;
_test_eof45: cs = 45; goto _test_eof;
_test_eof: {}
_out: {}
}
#line 117 "ext/puma_http11/http11_parser.rl"
if (!puma_parser_has_error(parser))
parser->cs = cs;
parser->nread += p - (buffer + off);
assert(p <= pe && "buffer overflow after parsing execute");
assert(parser->nread <= len && "nread longer than length");
assert(parser->body_start <= len && "body starts after buffer end");
assert(parser->mark < len && "mark is after buffer end");
assert(parser->field_len <= len && "field has length longer than whole buffer");
assert(parser->field_start < len && "field starts after buffer end");
return(parser->nread);
}
| null | null | 199,778
|
59711458713735015738030075198637316540
| 953
|
Merge pull request from GHSA-48w2-rm65-62xx
* Fix HTTP request smuggling vulnerability
See GHSA-48w2-rm65-62xx or CVE-2021-41136 for more info.
* 4.3.9 release note
* 5.5.1 release note
* 5.5.1
|
other
|
chafa
|
e4b777c7b7c144cd16a0ea96108267b1004fe6c9
| 1
|
gif_internal_decode_frame(gif_animation *gif,
unsigned int frame,
bool clear_image)
{
unsigned int index = 0;
const unsigned char *gif_data, *gif_end;
ssize_t gif_bytes;
unsigned int width, height, offset_x, offset_y;
unsigned int flags, colour_table_size, interlace;
unsigned int *colour_table;
unsigned int *frame_data = 0; // Set to 0 for no warnings
unsigned int *frame_scanline;
ssize_t save_buffer_position;
unsigned int return_value = 0;
unsigned int x, y, decode_y, burst_bytes;
register unsigned char colour;
/* Ensure this frame is supposed to be decoded */
if (gif->frames[frame].display == false) {
return GIF_OK;
}
/* Ensure the frame is in range to decode */
if (frame > gif->frame_count_partial) {
return GIF_INSUFFICIENT_DATA;
}
/* done if frame is already decoded */
if ((!clear_image) &&
((int)frame == gif->decoded_frame)) {
return GIF_OK;
}
/* Get the start of our frame data and the end of the GIF data */
gif_data = gif->gif_data + gif->frames[frame].frame_pointer;
gif_end = gif->gif_data + gif->buffer_size;
gif_bytes = (gif_end - gif_data);
/*
* Ensure there is a minimal amount of data to proceed. The shortest
* block of data is a 10-byte image descriptor + 1-byte gif trailer
*/
if (gif_bytes < 12) {
return GIF_INSUFFICIENT_FRAME_DATA;
}
/* Save the buffer position */
save_buffer_position = gif->buffer_position;
gif->buffer_position = gif_data - gif->gif_data;
/* Skip any extensions because they have allready been processed */
if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK) {
goto gif_decode_frame_exit;
}
gif_data = (gif->gif_data + gif->buffer_position);
gif_bytes = (gif_end - gif_data);
/* Ensure we have enough data for the 10-byte image descriptor + 1-byte
* gif trailer
*/
if (gif_bytes < 12) {
return_value = GIF_INSUFFICIENT_FRAME_DATA;
goto gif_decode_frame_exit;
}
/* 10-byte Image Descriptor is:
*
* +0 CHAR Image Separator (0x2c)
* +1 SHORT Image Left Position
* +3 SHORT Image Top Position
* +5 SHORT Width
* +7 SHORT Height
* +9 CHAR __Packed Fields__
* 1BIT Local Colour Table Flag
* 1BIT Interlace Flag
* 1BIT Sort Flag
* 2BITS Reserved
* 3BITS Size of Local Colour Table
*/
if (gif_data[0] != GIF_IMAGE_SEPARATOR) {
return_value = GIF_DATA_ERROR;
goto gif_decode_frame_exit;
}
offset_x = gif_data[1] | (gif_data[2] << 8);
offset_y = gif_data[3] | (gif_data[4] << 8);
width = gif_data[5] | (gif_data[6] << 8);
height = gif_data[7] | (gif_data[8] << 8);
/* Boundary checking - shouldn't ever happen except unless the data has
* been modified since initialisation.
*/
if ((offset_x + width > gif->width) ||
(offset_y + height > gif->height)) {
return_value = GIF_DATA_ERROR;
goto gif_decode_frame_exit;
}
/* Decode the flags */
flags = gif_data[9];
colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
interlace = flags & GIF_INTERLACE_MASK;
/* Advance data pointer to next block either colour table or image
* data.
*/
gif_data += 10;
gif_bytes = (gif_end - gif_data);
/* Set up the colour table */
if (flags & GIF_COLOUR_TABLE_MASK) {
if (gif_bytes < (int)(3 * colour_table_size)) {
return_value = GIF_INSUFFICIENT_FRAME_DATA;
goto gif_decode_frame_exit;
}
colour_table = gif->local_colour_table;
if (!clear_image) {
for (index = 0; index < colour_table_size; index++) {
/* Gif colour map contents are r,g,b.
*
* We want to pack them bytewise into the
* colour table, such that the red component
* is in byte 0 and the alpha component is in
* byte 3.
*/
unsigned char *entry =
(unsigned char *) &colour_table[index];
entry[0] = gif_data[0]; /* r */
entry[1] = gif_data[1]; /* g */
entry[2] = gif_data[2]; /* b */
entry[3] = 0xff; /* a */
gif_data += 3;
}
} else {
gif_data += 3 * colour_table_size;
}
gif_bytes = (gif_end - gif_data);
} else {
colour_table = gif->global_colour_table;
}
/* Ensure sufficient data remains */
if (gif_bytes < 1) {
return_value = GIF_INSUFFICIENT_FRAME_DATA;
goto gif_decode_frame_exit;
}
/* check for an end marker */
if (gif_data[0] == GIF_TRAILER) {
return_value = GIF_OK;
goto gif_decode_frame_exit;
}
/* Get the frame data */
assert(gif->bitmap_callbacks.bitmap_get_buffer);
frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
if (!frame_data) {
return GIF_INSUFFICIENT_MEMORY;
}
/* If we are clearing the image we just clear, if not decode */
if (!clear_image) {
lzw_result res;
const uint8_t *stack_base;
const uint8_t *stack_pos;
/* Ensure we have enough data for a 1-byte LZW code size +
* 1-byte gif trailer
*/
if (gif_bytes < 2) {
return_value = GIF_INSUFFICIENT_FRAME_DATA;
goto gif_decode_frame_exit;
}
/* If we only have a 1-byte LZW code size + 1-byte gif trailer,
* we're finished
*/
if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {
return_value = GIF_OK;
goto gif_decode_frame_exit;
}
/* If the previous frame's disposal method requires we restore
* the background colour or this is the first frame, clear
* the frame data
*/
if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {
memset((char*)frame_data,
GIF_TRANSPARENT_COLOUR,
gif->width * gif->height * sizeof(int));
gif->decoded_frame = frame;
/* The line below would fill the image with its
* background color, but because GIFs support
* transparency we likely wouldn't want to do that. */
/* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */
} else if ((frame != 0) &&
(gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {
return_value = gif_internal_decode_frame(gif,
(frame - 1),
true);
if (return_value != GIF_OK) {
goto gif_decode_frame_exit;
}
} else if ((frame != 0) &&
(gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {
/*
* If the previous frame's disposal method requires we
* restore the previous image, find the last image set
* to "do not dispose" and get that frame data
*/
int last_undisposed_frame = frame - 2;
while ((last_undisposed_frame >= 0) &&
(gif->frames[last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE)) {
last_undisposed_frame--;
}
/* If we don't find one, clear the frame data */
if (last_undisposed_frame == -1) {
/* see notes above on transparency
* vs. background color
*/
memset((char*)frame_data,
GIF_TRANSPARENT_COLOUR,
gif->width * gif->height * sizeof(int));
} else {
return_value = gif_internal_decode_frame(gif, last_undisposed_frame, false);
if (return_value != GIF_OK) {
goto gif_decode_frame_exit;
}
/* Get this frame's data */
assert(gif->bitmap_callbacks.bitmap_get_buffer);
frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
if (!frame_data) {
return GIF_INSUFFICIENT_MEMORY;
}
}
}
gif->decoded_frame = frame;
gif->buffer_position = (gif_data - gif->gif_data) + 1;
/* Initialise the LZW decoding */
res = lzw_decode_init(gif->lzw_ctx, gif->gif_data,
gif->buffer_size, gif->buffer_position,
gif_data[0], &stack_base, &stack_pos);
if (res != LZW_OK) {
return gif_error_from_lzw(res);
}
/* Decompress the data */
for (y = 0; y < height; y++) {
if (interlace) {
decode_y = gif_interlaced_line(height, y) + offset_y;
} else {
decode_y = y + offset_y;
}
frame_scanline = frame_data + offset_x + (decode_y * gif->width);
/* Rather than decoding pixel by pixel, we try to burst
* out streams of data to remove the need for end-of
* data checks every pixel.
*/
x = width;
while (x > 0) {
burst_bytes = (stack_pos - stack_base);
if (burst_bytes > 0) {
if (burst_bytes > x) {
burst_bytes = x;
}
x -= burst_bytes;
while (burst_bytes-- > 0) {
colour = *--stack_pos;
if (((gif->frames[frame].transparency) &&
(colour != gif->frames[frame].transparency_index)) ||
(!gif->frames[frame].transparency)) {
*frame_scanline = colour_table[colour];
}
frame_scanline++;
}
} else {
res = lzw_decode(gif->lzw_ctx, &stack_pos);
if (res != LZW_OK) {
/* Unexpected end of frame, try to recover */
if (res == LZW_OK_EOD) {
return_value = GIF_OK;
} else {
return_value = gif_error_from_lzw(res);
}
goto gif_decode_frame_exit;
}
}
}
}
} else {
/* Clear our frame */
if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {
for (y = 0; y < height; y++) {
frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);
if (gif->frames[frame].transparency) {
memset(frame_scanline,
GIF_TRANSPARENT_COLOUR,
width * 4);
} else {
memset(frame_scanline,
colour_table[gif->background_index],
width * 4);
}
}
}
}
gif_decode_frame_exit:
/* Check if we should test for optimisation */
if (gif->frames[frame].virgin) {
if (gif->bitmap_callbacks.bitmap_test_opaque) {
gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);
} else {
gif->frames[frame].opaque = false;
}
gif->frames[frame].virgin = false;
}
if (gif->bitmap_callbacks.bitmap_set_opaque) {
gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);
}
if (gif->bitmap_callbacks.bitmap_modified) {
gif->bitmap_callbacks.bitmap_modified(gif->frame_image);
}
/* Restore the buffer position */
gif->buffer_position = save_buffer_position;
return return_value;
}
| null | null | 199,833
|
21944791382892949851366795906609751797
| 336
|
libnsgif: Fix null pointer deref on frameless GIF input
A crafted GIF file with no frame data could cause a null pointer
dereference leading to denial of service (crash). Reported by
@JieyongMa via huntr.dev.
|
other
|
vim
|
f12129f1714f7d2301935bb21d896609bdac221c
| 1
|
ins_compl_stop(int c, int prev_mode, int retval)
{
char_u *ptr;
int want_cindent;
// Get here when we have finished typing a sequence of ^N and
// ^P or other completion characters in CTRL-X mode. Free up
// memory that was used, and make sure we can redo the insert.
if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
{
// If any of the original typed text has been changed, eg when
// ignorecase is set, we must add back-spaces to the redo
// buffer. We add as few as necessary to delete just the part
// of the original text that has changed.
// When using the longest match, edited the match or used
// CTRL-E then don't use the current match.
if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
ptr = compl_curr_match->cp_str;
else
ptr = NULL;
ins_compl_fixRedoBufForLeader(ptr);
}
want_cindent = (get_can_cindent() && cindent_on());
// When completing whole lines: fix indent for 'cindent'.
// Otherwise, break line if it's too long.
if (compl_cont_mode == CTRL_X_WHOLE_LINE)
{
// re-indent the current line
if (want_cindent)
{
do_c_expr_indent();
want_cindent = FALSE; // don't do it again
}
}
else
{
int prev_col = curwin->w_cursor.col;
// put the cursor on the last char, for 'tw' formatting
if (prev_col > 0)
dec_cursor();
// only format when something was inserted
if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
insertchar(NUL, 0, -1);
if (prev_col > 0
&& ml_get_curline()[curwin->w_cursor.col] != NUL)
inc_cursor();
}
// If the popup menu is displayed pressing CTRL-Y means accepting
// the selection without inserting anything. When
// compl_enter_selects is set the Enter key does the same.
if ((c == Ctrl_Y || (compl_enter_selects
&& (c == CAR || c == K_KENTER || c == NL)))
&& pum_visible())
retval = TRUE;
// CTRL-E means completion is Ended, go back to the typed text.
// but only do this, if the Popup is still visible
if (c == Ctrl_E)
{
ins_compl_delete();
if (compl_leader != NULL)
ins_bytes(compl_leader + get_compl_len());
else if (compl_first_match != NULL)
ins_bytes(compl_orig_text + get_compl_len());
retval = TRUE;
}
auto_format(FALSE, TRUE);
// Trigger the CompleteDonePre event to give scripts a chance to
// act upon the completion before clearing the info, and restore
// ctrl_x_mode, so that complete_info() can be used.
ctrl_x_mode = prev_mode;
ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
ins_compl_free();
compl_started = FALSE;
compl_matches = 0;
if (!shortmess(SHM_COMPLETIONMENU))
msg_clr_cmdline(); // necessary for "noshowmode"
ctrl_x_mode = CTRL_X_NORMAL;
compl_enter_selects = FALSE;
if (edit_submode != NULL)
{
edit_submode = NULL;
showmode();
}
#ifdef FEAT_CMDWIN
if (c == Ctrl_C && cmdwin_type != 0)
// Avoid the popup menu remains displayed when leaving the
// command line window.
update_screen(0);
#endif
// Indent now if a key was typed that is in 'cinkeys'.
if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
do_c_expr_indent();
// Trigger the CompleteDone event to give scripts a chance to act
// upon the end of completion.
ins_apply_autocmds(EVENT_COMPLETEDONE);
return retval;
}
| null | null | 199,834
|
12307773136404750699697042007089989431
| 107
|
patch 9.0.0020: with some completion reading past end of string
Problem: With some completion reading past end of string.
Solution: Check the length of the string.
|
other
|
pjproject
|
077b465c33f0aec05a49cd2ca456f9a1b112e896
| 1
|
PJ_DEF(int) pj_scan_get_char( pj_scanner *scanner )
{
int chr = *scanner->curptr;
if (!chr) {
pj_scan_syntax_err(scanner);
return 0;
}
++scanner->curptr;
if (PJ_SCAN_IS_PROBABLY_SPACE(*scanner->curptr) && scanner->skip_ws) {
pj_scan_skip_whitespace(scanner);
}
return chr;
}
| null | null | 199,836
|
250257059547301458667731790844822819454
| 16
|
Merge pull request from GHSA-7fw8-54cv-r7pm
|
other
|
radare2
|
feaa4e7f7399c51ee6f52deb84dc3f795b4035d6
| 1
|
static bool load_buffer(RBinFile *bf, void **bin_obj, RBuffer *buf, ut64 loadaddr, Sdb *sdb) {
RBuffer *fbuf = r_buf_ref (buf);
struct MACH0_(opts_t) opts;
MACH0_(opts_set_default) (&opts, bf);
struct MACH0_(obj_t) *main_mach0 = MACH0_(new_buf) (fbuf, &opts);
if (!main_mach0) {
return false;
}
RRebaseInfo *rebase_info = r_rebase_info_new_from_mach0 (fbuf, main_mach0);
RKernelCacheObj *obj = NULL;
RPrelinkRange *prelink_range = get_prelink_info_range_from_mach0 (main_mach0);
if (!prelink_range) {
goto beach;
}
obj = R_NEW0 (RKernelCacheObj);
if (!obj) {
R_FREE (prelink_range);
goto beach;
}
RCFValueDict *prelink_info = NULL;
if (main_mach0->hdr.filetype != MH_FILESET && prelink_range->range.size) {
prelink_info = r_cf_value_dict_parse (fbuf, prelink_range->range.offset,
prelink_range->range.size, R_CF_OPTION_SKIP_NSDATA);
if (!prelink_info) {
R_FREE (prelink_range);
R_FREE (obj);
goto beach;
}
}
if (!pending_bin_files) {
pending_bin_files = r_list_new ();
if (!pending_bin_files) {
R_FREE (prelink_range);
R_FREE (obj);
R_FREE (prelink_info);
goto beach;
}
}
obj->mach0 = main_mach0;
obj->rebase_info = rebase_info;
obj->prelink_info = prelink_info;
obj->cache_buf = fbuf;
obj->pa2va_exec = prelink_range->pa2va_exec;
obj->pa2va_data = prelink_range->pa2va_data;
R_FREE (prelink_range);
*bin_obj = obj;
r_list_push (pending_bin_files, bf);
if (rebase_info || main_mach0->chained_starts) {
RIO *io = bf->rbin->iob.io;
swizzle_io_read (obj, io);
}
return true;
beach:
r_buf_free (fbuf);
obj->cache_buf = NULL;
MACH0_(mach0_free) (main_mach0);
return false;
}
| null | null | 199,841
|
163929521667987283200588349888403367573
| 70
|
Fix null deref in xnu.kernelcache ##crash
* Reported by @xshad3 via huntr.dev
|
other
|
vim
|
6e28703a8e41f775f64e442c5d11ce1ff599aa3f
| 1
|
ex_retab(exarg_T *eap)
{
linenr_T lnum;
int got_tab = FALSE;
long num_spaces = 0;
long num_tabs;
long len;
long col;
long vcol;
long start_col = 0; // For start of white-space string
long start_vcol = 0; // For start of white-space string
long old_len;
char_u *ptr;
char_u *new_line = (char_u *)1; // init to non-NULL
int did_undo; // called u_save for current line
#ifdef FEAT_VARTABS
int *new_vts_array = NULL;
char_u *new_ts_str; // string value of tab argument
#else
int temp;
int new_ts;
#endif
int save_list;
linenr_T first_line = 0; // first changed line
linenr_T last_line = 0; // last changed line
save_list = curwin->w_p_list;
curwin->w_p_list = 0; // don't want list mode here
#ifdef FEAT_VARTABS
new_ts_str = eap->arg;
if (tabstop_set(eap->arg, &new_vts_array) == FAIL)
return;
while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')
++(eap->arg);
// This ensures that either new_vts_array and new_ts_str are freshly
// allocated, or new_vts_array points to an existing array and new_ts_str
// is null.
if (new_vts_array == NULL)
{
new_vts_array = curbuf->b_p_vts_array;
new_ts_str = NULL;
}
else
new_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str);
#else
ptr = eap->arg;
new_ts = getdigits(&ptr);
if (new_ts < 0 && *eap->arg == '-')
{
emsg(_(e_argument_must_be_positive));
return;
}
if (new_ts < 0 || new_ts > TABSTOP_MAX)
{
semsg(_(e_invalid_argument_str), eap->arg);
return;
}
if (new_ts == 0)
new_ts = curbuf->b_p_ts;
#endif
for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)
{
ptr = ml_get(lnum);
col = 0;
vcol = 0;
did_undo = FALSE;
for (;;)
{
if (VIM_ISWHITE(ptr[col]))
{
if (!got_tab && num_spaces == 0)
{
// First consecutive white-space
start_vcol = vcol;
start_col = col;
}
if (ptr[col] == ' ')
num_spaces++;
else
got_tab = TRUE;
}
else
{
if (got_tab || (eap->forceit && num_spaces > 1))
{
// Retabulate this string of white-space
// len is virtual length of white string
len = num_spaces = vcol - start_vcol;
num_tabs = 0;
if (!curbuf->b_p_et)
{
#ifdef FEAT_VARTABS
int t, s;
tabstop_fromto(start_vcol, vcol,
curbuf->b_p_ts, new_vts_array, &t, &s);
num_tabs = t;
num_spaces = s;
#else
temp = new_ts - (start_vcol % new_ts);
if (num_spaces >= temp)
{
num_spaces -= temp;
num_tabs++;
}
num_tabs += num_spaces / new_ts;
num_spaces -= (num_spaces / new_ts) * new_ts;
#endif
}
if (curbuf->b_p_et || got_tab ||
(num_spaces + num_tabs < len))
{
if (did_undo == FALSE)
{
did_undo = TRUE;
if (u_save((linenr_T)(lnum - 1),
(linenr_T)(lnum + 1)) == FAIL)
{
new_line = NULL; // flag out-of-memory
break;
}
}
// len is actual number of white characters used
len = num_spaces + num_tabs;
old_len = (long)STRLEN(ptr);
new_line = alloc(old_len - col + start_col + len + 1);
if (new_line == NULL)
break;
if (start_col > 0)
mch_memmove(new_line, ptr, (size_t)start_col);
mch_memmove(new_line + start_col + len,
ptr + col, (size_t)(old_len - col + 1));
ptr = new_line + start_col;
for (col = 0; col < len; col++)
ptr[col] = (col < num_tabs) ? '\t' : ' ';
if (ml_replace(lnum, new_line, FALSE) == OK)
// "new_line" may have been copied
new_line = curbuf->b_ml.ml_line_ptr;
if (first_line == 0)
first_line = lnum;
last_line = lnum;
ptr = new_line;
col = start_col + len;
}
}
got_tab = FALSE;
num_spaces = 0;
}
if (ptr[col] == NUL)
break;
vcol += chartabsize(ptr + col, (colnr_T)vcol);
if (has_mbyte)
col += (*mb_ptr2len)(ptr + col);
else
++col;
}
if (new_line == NULL) // out of memory
break;
line_breakcheck();
}
if (got_int)
emsg(_(e_interrupted));
#ifdef FEAT_VARTABS
// If a single value was given then it can be considered equal to
// either the value of 'tabstop' or the value of 'vartabstop'.
if (tabstop_count(curbuf->b_p_vts_array) == 0
&& tabstop_count(new_vts_array) == 1
&& curbuf->b_p_ts == tabstop_first(new_vts_array))
; // not changed
else if (tabstop_count(curbuf->b_p_vts_array) > 0
&& tabstop_eq(curbuf->b_p_vts_array, new_vts_array))
; // not changed
else
redraw_curbuf_later(NOT_VALID);
#else
if (curbuf->b_p_ts != new_ts)
redraw_curbuf_later(NOT_VALID);
#endif
if (first_line != 0)
changed_lines(first_line, 0, last_line + 1, 0L);
curwin->w_p_list = save_list; // restore 'list'
#ifdef FEAT_VARTABS
if (new_ts_str != NULL) // set the new tabstop
{
// If 'vartabstop' is in use or if the value given to retab has more
// than one tabstop then update 'vartabstop'.
int *old_vts_ary = curbuf->b_p_vts_array;
if (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1)
{
set_string_option_direct((char_u *)"vts", -1, new_ts_str,
OPT_FREE|OPT_LOCAL, 0);
curbuf->b_p_vts_array = new_vts_array;
vim_free(old_vts_ary);
}
else
{
// 'vartabstop' wasn't in use and a single value was given to
// retab then update 'tabstop'.
curbuf->b_p_ts = tabstop_first(new_vts_array);
vim_free(new_vts_array);
}
vim_free(new_ts_str);
}
#else
curbuf->b_p_ts = new_ts;
#endif
coladvance(curwin->w_curswant);
u_clearline();
}
| null | null | 199,851
|
234964729879976016048982685024514611474
| 218
|
patch 8.2.4359: crash when repeatedly using :retab
Problem: crash when repeatedly using :retab.
Solution: Bail out when the line is getting too long.
|
other
|
date
|
8f2d7a0c7e52cea8333824bd527822e5449ed83d
| 1
|
check_limit(VALUE str, VALUE opt)
{
StringValue(str);
size_t slen = RSTRING_LEN(str);
size_t limit = get_limit(opt);
if (slen > limit) {
rb_raise(rb_eArgError,
"string length (%"PRI_SIZE_PREFIX"u) exceeds the limit %"PRI_SIZE_PREFIX"u", slen, limit);
}
}
| null | null | 199,885
|
197335199202788740114040264486120590708
| 10
|
`Date._<format>(nil)` should return an empty Hash
Fix: https://github.com/ruby/date/issues/39
This is how versions previous to 3.2.1 behaved and Active Support
currently rely on this behavior.
https://github.com/rails/rails/blob/90357af08048ef5076730505f6e7b14a81f33d0c/activesupport/lib/active_support/values/time_zone.rb#L383-L384
Any Rails application upgrading to date `3.2.1` might run into unexpected errors.
|
other
|
vim
|
2813f38e021c6e6581c0c88fcf107e41788bc835
| 1
|
spell_move_to(
win_T *wp,
int dir, // FORWARD or BACKWARD
int allwords, // TRUE for "[s"/"]s", FALSE for "[S"/"]S"
int curline,
hlf_T *attrp) // return: attributes of bad word or NULL
// (only when "dir" is FORWARD)
{
linenr_T lnum;
pos_T found_pos;
int found_len = 0;
char_u *line;
char_u *p;
char_u *endp;
hlf_T attr;
int len;
#ifdef FEAT_SYN_HL
int has_syntax = syntax_present(wp);
#endif
int col;
int can_spell;
char_u *buf = NULL;
int buflen = 0;
int skip = 0;
int capcol = -1;
int found_one = FALSE;
int wrapped = FALSE;
if (no_spell_checking(wp))
return 0;
/*
* Start looking for bad word at the start of the line, because we can't
* start halfway a word, we don't know where it starts or ends.
*
* When searching backwards, we continue in the line to find the last
* bad word (in the cursor line: before the cursor).
*
* We concatenate the start of the next line, so that wrapped words work
* (e.g. "et<line-break>cetera"). Doesn't work when searching backwards
* though...
*/
lnum = wp->w_cursor.lnum;
CLEAR_POS(&found_pos);
while (!got_int)
{
line = ml_get_buf(wp->w_buffer, lnum, FALSE);
len = (int)STRLEN(line);
if (buflen < len + MAXWLEN + 2)
{
vim_free(buf);
buflen = len + MAXWLEN + 2;
buf = alloc(buflen);
if (buf == NULL)
break;
}
// In first line check first word for Capital.
if (lnum == 1)
capcol = 0;
// For checking first word with a capital skip white space.
if (capcol == 0)
capcol = getwhitecols(line);
else if (curline && wp == curwin)
{
// For spellbadword(): check if first word needs a capital.
col = getwhitecols(line);
if (check_need_cap(lnum, col))
capcol = col;
// Need to get the line again, may have looked at the previous
// one.
line = ml_get_buf(wp->w_buffer, lnum, FALSE);
}
// Copy the line into "buf" and append the start of the next line if
// possible.
STRCPY(buf, line);
if (lnum < wp->w_buffer->b_ml.ml_line_count)
spell_cat_line(buf + STRLEN(buf),
ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN);
p = buf + skip;
endp = buf + len;
while (p < endp)
{
// When searching backward don't search after the cursor. Unless
// we wrapped around the end of the buffer.
if (dir == BACKWARD
&& lnum == wp->w_cursor.lnum
&& !wrapped
&& (colnr_T)(p - buf) >= wp->w_cursor.col)
break;
// start of word
attr = HLF_COUNT;
len = spell_check(wp, p, &attr, &capcol, FALSE);
if (attr != HLF_COUNT)
{
// We found a bad word. Check the attribute.
if (allwords || attr == HLF_SPB)
{
// When searching forward only accept a bad word after
// the cursor.
if (dir == BACKWARD
|| lnum != wp->w_cursor.lnum
|| (wrapped
|| (colnr_T)(curline ? p - buf + len
: p - buf)
> wp->w_cursor.col))
{
#ifdef FEAT_SYN_HL
if (has_syntax)
{
col = (int)(p - buf);
(void)syn_get_id(wp, lnum, (colnr_T)col,
FALSE, &can_spell, FALSE);
if (!can_spell)
attr = HLF_COUNT;
}
else
#endif
can_spell = TRUE;
if (can_spell)
{
found_one = TRUE;
found_pos.lnum = lnum;
found_pos.col = (int)(p - buf);
found_pos.coladd = 0;
if (dir == FORWARD)
{
// No need to search further.
wp->w_cursor = found_pos;
vim_free(buf);
if (attrp != NULL)
*attrp = attr;
return len;
}
else if (curline)
// Insert mode completion: put cursor after
// the bad word.
found_pos.col += len;
found_len = len;
}
}
else
found_one = TRUE;
}
}
// advance to character after the word
p += len;
capcol -= len;
}
if (dir == BACKWARD && found_pos.lnum != 0)
{
// Use the last match in the line (before the cursor).
wp->w_cursor = found_pos;
vim_free(buf);
return found_len;
}
if (curline)
break; // only check cursor line
// If we are back at the starting line and searched it again there
// is no match, give up.
if (lnum == wp->w_cursor.lnum && wrapped)
break;
// Advance to next line.
if (dir == BACKWARD)
{
if (lnum > 1)
--lnum;
else if (!p_ws)
break; // at first line and 'nowrapscan'
else
{
// Wrap around to the end of the buffer. May search the
// starting line again and accept the last match.
lnum = wp->w_buffer->b_ml.ml_line_count;
wrapped = TRUE;
if (!shortmess(SHM_SEARCH))
give_warning((char_u *)_(top_bot_msg), TRUE);
}
capcol = -1;
}
else
{
if (lnum < wp->w_buffer->b_ml.ml_line_count)
++lnum;
else if (!p_ws)
break; // at first line and 'nowrapscan'
else
{
// Wrap around to the start of the buffer. May search the
// starting line again and accept the first match.
lnum = 1;
wrapped = TRUE;
if (!shortmess(SHM_SEARCH))
give_warning((char_u *)_(bot_top_msg), TRUE);
}
// If we are back at the starting line and there is no match then
// give up.
if (lnum == wp->w_cursor.lnum && !found_one)
break;
// Skip the characters at the start of the next line that were
// included in a match crossing line boundaries.
if (attr == HLF_COUNT)
skip = (int)(p - endp);
else
skip = 0;
// Capcol skips over the inserted space.
--capcol;
// But after empty line check first word in next line
if (*skipwhite(line) == NUL)
capcol = 0;
}
line_breakcheck();
}
vim_free(buf);
return 0;
}
| null | null | 199,918
|
24431311156552293265437974373971430432
| 236
|
patch 8.2.5072: using uninitialized value and freed memory in spell command
Problem: Using uninitialized value and freed memory in spell command.
Solution: Initialize "attr". Check for empty line early.
|
other
|
MilkyTracker
|
3a5474f9102cbdc10fbd9e7b1b2c8d3f3f45d91b
| 1
|
mp_sint32 LoaderXM::load(XMFileBase& f, XModule* module)
{
mp_ubyte insData[230];
mp_sint32 smpReloc[MP_MAXINSSAMPS];
mp_ubyte nbu[MP_MAXINSSAMPS];
mp_uint32 fileSize = 0;
module->cleanUp();
// this will make code much easier to read
TXMHeader* header = &module->header;
TXMInstrument* instr = module->instr;
TXMSample* smp = module->smp;
TXMPattern* phead = module->phead;
// we're already out of memory here
if (!phead || !instr || !smp)
return MP_OUT_OF_MEMORY;
fileSize = f.sizeWithBaseOffset();
f.read(&header->sig,1,17);
f.read(&header->name,1,20);
f.read(&header->whythis1a,1,1);
header->whythis1a=0;
f.read(&header->tracker,1,20);
f.readWords(&header->ver,1);
if (header->ver != 0x102 &&
header->ver != 0x103 && // untested
header->ver != 0x104)
return MP_LOADER_FAILED;
f.readDwords(&header->hdrsize,1);
header->hdrsize-=4;
mp_uint32 hdrSize = 0x110;
if (header->hdrsize > hdrSize)
hdrSize = header->hdrsize;
mp_ubyte* hdrBuff = new mp_ubyte[hdrSize];
memset(hdrBuff, 0, hdrSize);
f.read(hdrBuff, 1, header->hdrsize);
header->ordnum = LittleEndian::GET_WORD(hdrBuff);
header->restart = LittleEndian::GET_WORD(hdrBuff+2);
header->channum = LittleEndian::GET_WORD(hdrBuff+4);
header->patnum = LittleEndian::GET_WORD(hdrBuff+6);
header->insnum = LittleEndian::GET_WORD(hdrBuff+8);
header->freqtab = LittleEndian::GET_WORD(hdrBuff+10);
header->tempo = LittleEndian::GET_WORD(hdrBuff+12);
header->speed = LittleEndian::GET_WORD(hdrBuff+14);
memcpy(header->ord, hdrBuff+16, 256);
if(header->ordnum > MP_MAXORDERS)
header->ordnum = MP_MAXORDERS;
if(header->insnum > MP_MAXINS)
return MP_LOADER_FAILED;
delete[] hdrBuff;
header->mainvol=255;
header->flags = XModule::MODULE_XMNOTECLIPPING |
XModule::MODULE_XMARPEGGIO |
XModule::MODULE_XMPORTANOTEBUFFER |
XModule::MODULE_XMVOLCOLUMNVIBRATO;
header->uppernotebound = 119;
mp_sint32 i,y,sc;
for (i=0;i<32;i++) header->pan[i]=0x80;
// old version?
if (header->ver == 0x102 || header->ver == 0x103)
{
mp_sint32 s = 0;
mp_sint32 e = 0;
for (y=0;y<header->insnum;y++) {
f.readDwords(&instr[y].size,1);
f.read(&instr[y].name,1,22);
f.read(&instr[y].type,1,1);
mp_uword numSamples = 0;
f.readWords(&numSamples,1);
if(numSamples > MP_MAXINSSAMPS)
return MP_LOADER_FAILED;
instr[y].samp = numSamples;
if (instr[y].size == 29)
{
#ifdef MILKYTRACKER
s+=16;
#endif
for (mp_sint32 i = 0; i < 120; i++)
instr[y].snum[i] = -1;
continue;
}
f.readDwords(&instr[y].shsize,1);
memset(insData, 0, 230);
if (instr[y].size - 33 > 230)
return MP_OUT_OF_MEMORY;
f.read(insData, 1, instr[y].size - 33);
if (instr[y].samp) {
mp_ubyte* insDataPtr = insData;
memcpy(nbu, insDataPtr, MP_MAXINSSAMPS);
insDataPtr+=MP_MAXINSSAMPS;
TEnvelope venv;
TEnvelope penv;
memset(&venv,0,sizeof(venv));
memset(&penv,0,sizeof(penv));
mp_sint32 k;
for (k = 0; k < XM_ENVELOPENUMPOINTS; k++)
{
venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);
venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);
insDataPtr+=4;
}
for (k = 0; k < XM_ENVELOPENUMPOINTS; k++)
{
penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);
penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);
insDataPtr+=4;
}
venv.num = *insDataPtr++;
if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS;
penv.num = *insDataPtr++;
if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS;
venv.sustain = *insDataPtr++;
venv.loops = *insDataPtr++;
venv.loope = *insDataPtr++;
penv.sustain = *insDataPtr++;
penv.loops = *insDataPtr++;
penv.loope = *insDataPtr++;
venv.type = *insDataPtr++;
penv.type = *insDataPtr++;
mp_ubyte vibtype, vibsweep, vibdepth, vibrate;
mp_uword volfade;
vibtype = *insDataPtr++;
vibsweep = *insDataPtr++;
vibdepth = *insDataPtr++;
vibrate = *insDataPtr++;
vibdepth<<=1;
volfade = LittleEndian::GET_WORD(insDataPtr);
insDataPtr+=2;
volfade<<=1;
//instr[y].res = LittleEndian::GET_WORD(insDataPtr);
insDataPtr+=2;
for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) {
venv.env[l][1]<<=2;
penv.env[l][1]<<=2;
}
if (!module->addVolumeEnvelope(venv))
return MP_OUT_OF_MEMORY;
if (!module->addPanningEnvelope(penv))
return MP_OUT_OF_MEMORY;
mp_sint32 g=0, sc;
for (sc=0;sc<instr[y].samp;sc++) {
smp[g+s].flags=3;
smp[g+s].venvnum=e+1;
smp[g+s].penvnum=e+1;
smp[g+s].vibtype=vibtype;
smp[g+s].vibsweep=vibsweep;
smp[g+s].vibdepth=vibdepth;
smp[g+s].vibrate=vibrate;
smp[g+s].volfade=volfade;
// not sure why I did that, actually doesn't make sense
//if (!(venv.type&1)) smp[g+s].volfade=0;
f.readDwords(&smp[g+s].samplen,1);
f.readDwords(&smp[g+s].loopstart,1);
f.readDwords(&smp[g+s].looplen,1);
smp[g+s].vol=XModule::vol64to255(f.readByte());
//f.read(&smp[g+s].vol,1,1);
f.read(&smp[g+s].finetune,1,1);
f.read(&smp[g+s].type,1,1);
#ifdef VERBOSE
printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16));
#endif
f.read(&smp[g+s].pan,1,1);
f.read(&smp[g+s].relnote,1,1);
f.read(&smp[g+s].res,1,1);
f.read(&smp[g+s].name,1,22);
char line[30];
memset(line, 0, sizeof(line));
XModule::convertStr(line, smp[g+s].name, 23, false);
if (line[0])
module->addSongMessageLine(line);
// ignore empty samples
#ifndef MILKYTRACKER
// ignore empty samples when not being a tracker
if (smp[g+s].samplen) {
smpReloc[sc] = g;
g++;
}
else
smpReloc[sc] = -1;
#else
smpReloc[sc] = g;
g++;
#endif
}
instr[y].samp = g;
for (sc = 0; sc < MP_MAXINSSAMPS; sc++) {
if (smpReloc[nbu[sc]] == -1)
instr[y].snum[sc] = -1;
else
instr[y].snum[sc] = smpReloc[nbu[sc]]+s;
}
e++;
}
else
{
for (mp_sint32 i = 0; i < 120; i++)
instr[y].snum[i] = -1;
}
#ifdef MILKYTRACKER
s+=16;
#else
s+=instr[y].samp;
#endif
}
header->smpnum=s;
header->volenvnum=e;
header->panenvnum=e;
}
for (y=0;y<header->patnum;y++) {
if (header->ver == 0x104 || header->ver == 0x103)
{
f.readDwords(&phead[y].len,1);
f.read(&phead[y].ptype,1,1);
f.readWords(&phead[y].rows,1);
f.readWords(&phead[y].patdata,1);
}
else
{
f.readDwords(&phead[y].len,1);
f.read(&phead[y].ptype,1,1);
phead[y].rows = (mp_uword)f.readByte()+1;
f.readWords(&phead[y].patdata,1);
}
phead[y].effnum=2;
phead[y].channum=(mp_ubyte)header->channum;
phead[y].patternData = new mp_ubyte[phead[y].rows*header->channum*6];
// out of memory?
if (phead[y].patternData == NULL)
{
return MP_OUT_OF_MEMORY;
}
memset(phead[y].patternData,0,phead[y].rows*header->channum*6);
if (phead[y].patdata) {
mp_ubyte *buffer = new mp_ubyte[phead[y].patdata];
// out of memory?
if (buffer == NULL)
{
return MP_OUT_OF_MEMORY;
}
f.read(buffer,1,phead[y].patdata);
//printf("%i\n", phead[y].patdata);
mp_sint32 pc = 0, bc = 0;
for (mp_sint32 r=0;r<phead[y].rows;r++) {
for (mp_sint32 c=0;c<header->channum;c++) {
mp_ubyte slot[5];
memset(slot,0,5);
if ((buffer[pc]&128)) {
mp_ubyte pb = buffer[pc];
pc++;
if ((pb&1)) {
//phead[y].patternData[bc]=buffer[pc];
slot[0]=buffer[pc];
pc++;
}
if ((pb&2)) {
//phead[y].patternData[bc+1]=buffer[pc];
slot[1]=buffer[pc];
pc++;
}
if ((pb&4)) {
//phead[y].patternData[bc+2]=buffer[pc];
slot[2]=buffer[pc];
pc++;
}
if ((pb&8)) {
//phead[y].patternData[bc+3]=buffer[pc];
slot[3]=buffer[pc];
pc++;
}
if ((pb&16)) {
//phead[y].patternData[bc+4]=buffer[pc];
slot[4]=buffer[pc];
pc++;
}
}
else {
//memcpy(phead[y].patternData+bc,buffer+pc,5);
memcpy(slot,buffer+pc,5);
pc+=5;
}
char gl=0;
for (mp_sint32 i=0;i<XModule::numValidXMEffects;i++)
if (slot[3]==XModule::validXMEffects[i]) gl=1;
if (!gl) slot[3]=slot[4]=0;
if ((slot[3]==0xC)||(slot[3]==0x10)) {
slot[4] = XModule::vol64to255(slot[4]);
/*mp_sint32 bl = slot[4];
if (bl>64) bl=64;
slot[4]=(bl*261120)>>16;*/
}
if ((!slot[3])&&(slot[4])) slot[3]=0x20;
if (slot[3]==0xE) {
slot[3]=(slot[4]>>4)+0x30;
slot[4]=slot[4]&0xf;
}
if (slot[3]==0x21) {
slot[3]=(slot[4]>>4)+0x40;
slot[4]=slot[4]&0xf;
}
if (slot[0]==97) slot[0]=XModule::NOTE_OFF;
phead[y].patternData[bc]=slot[0];
phead[y].patternData[bc+1]=slot[1];
XModule::convertXMVolumeEffects(slot[2], phead[y].patternData[bc+2], phead[y].patternData[bc+3]);
phead[y].patternData[bc+4]=slot[3];
phead[y].patternData[bc+5]=slot[4];
/*if ((y==3)&&(c==2)) {
for (mp_sint32 bl=0;bl<6;bl++) cprintf("%x ",phead[y].patternData[bc+bl]);
cprintf("\r\n");
getch();
};*/
/*printf("Note : %i\r\n",phead[y].patternData[bc]);
printf("Ins : %i\r\n",phead[y].patternData[bc+1]);
printf("Vol : %i\r\n",phead[y].patternData[bc+2]);
printf("Eff : %i\r\n",phead[y].patternData[bc+3]);
printf("Effop: %i\r\n",phead[y].patternData[bc+4]);
getch();*/
bc+=6;
} // for c
} // for r
delete[] buffer;
}
}
if (header->ver == 0x104)
{
mp_sint32 s = 0;
mp_sint32 e = 0;
for (y=0;y<header->insnum;y++) {
// fixes MOOH.XM loading problems
// seems to store more instruments in the header than in the actual file
if (f.posWithBaseOffset() >= fileSize)
break;
//TXMInstrument* ins = &instr[y];
f.readDwords(&instr[y].size,1);
if (instr[y].size < 29)
{
mp_ubyte buffer[29];
memset(buffer, 0, sizeof(buffer));
f.read(buffer, 1, instr[y].size - 4);
memcpy(instr[y].name, buffer, 22);
instr[y].type = buffer[22];
instr[y].samp = LittleEndian::GET_WORD(buffer + 23);
}
else
{
f.read(&instr[y].name,1,22);
f.read(&instr[y].type,1,1);
f.readWords(&instr[y].samp,1);
}
if (instr[y].samp > MP_MAXINSSAMPS)
return MP_LOADER_FAILED;
//printf("%i, %i\n", instr[y].size, instr[y].samp);
if (instr[y].size <= 29)
{
#ifdef MILKYTRACKER
s+=16;
#endif
for (mp_sint32 i = 0; i < 120; i++)
instr[y].snum[i] = -1;
continue;
}
f.readDwords(&instr[y].shsize,1);
#ifdef VERBOSE
printf("%i/%i: %i, %i, %i, %s\n",y,header->insnum-1,instr[y].size,instr[y].shsize,instr[y].samp,instr[y].name);
#endif
memset(insData, 0, 230);
if (instr[y].size - 33 > 230)
{
//return -7;
break;
}
f.read(insData, 1, instr[y].size - 33);
/*printf("%i\r\n",instr[y].size);
printf("%s\r\n",instr[y].name);
printf("%i\r\n",instr[y].type);
printf("%i\r\n",instr[y].samp);
printf("%i\r\n",instr[y].shsize);*/
//getch();
memset(smpReloc, 0, sizeof(smpReloc));
if (instr[y].samp) {
mp_ubyte* insDataPtr = insData;
//f.read(&nbu,1,96);
memcpy(nbu, insDataPtr, MP_MAXINSSAMPS);
insDataPtr+=MP_MAXINSSAMPS;
TEnvelope venv;
TEnvelope penv;
memset(&venv,0,sizeof(venv));
memset(&penv,0,sizeof(penv));
mp_sint32 k;
for (k = 0; k < XM_ENVELOPENUMPOINTS; k++)
{
venv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);
venv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);
insDataPtr+=4;
}
for (k = 0; k < XM_ENVELOPENUMPOINTS; k++)
{
penv.env[k][0] = LittleEndian::GET_WORD(insDataPtr);
penv.env[k][1] = LittleEndian::GET_WORD(insDataPtr+2);
insDataPtr+=4;
}
venv.num = *insDataPtr++;
if (venv.num > XM_ENVELOPENUMPOINTS) venv.num = XM_ENVELOPENUMPOINTS;
penv.num = *insDataPtr++;
if (penv.num > XM_ENVELOPENUMPOINTS) penv.num = XM_ENVELOPENUMPOINTS;
venv.sustain = *insDataPtr++;
venv.loops = *insDataPtr++;
venv.loope = *insDataPtr++;
penv.sustain = *insDataPtr++;
penv.loops = *insDataPtr++;
penv.loope = *insDataPtr++;
venv.type = *insDataPtr++;
penv.type = *insDataPtr++;
mp_ubyte vibtype, vibsweep, vibdepth, vibrate;
mp_uword volfade;
vibtype = *insDataPtr++;
vibsweep = *insDataPtr++;
vibdepth = *insDataPtr++;
vibrate = *insDataPtr++;
vibdepth<<=1;
//f.readWords(&volfade,1);
volfade = LittleEndian::GET_WORD(insDataPtr);
insDataPtr+=2;
volfade<<=1;
//instr[y].res = LittleEndian::GET_WORD(insDataPtr);
insDataPtr+=2;
for (mp_sint32 l=0;l<XM_ENVELOPENUMPOINTS;l++) {
venv.env[l][1]<<=2;
penv.env[l][1]<<=2;
}
if (!module->addVolumeEnvelope(venv))
return MP_OUT_OF_MEMORY;
if (!module->addPanningEnvelope(penv))
return MP_OUT_OF_MEMORY;
mp_sint32 g=0, sc;
for (sc=0;sc<instr[y].samp;sc++) {
//TXMSample* smpl = &smp[g+s];
smp[g+s].flags=3;
smp[g+s].venvnum=e+1;
smp[g+s].penvnum=e+1;
smp[g+s].vibtype=vibtype;
smp[g+s].vibsweep=vibsweep;
smp[g+s].vibdepth=vibdepth;
smp[g+s].vibrate=vibrate;
smp[g+s].volfade=volfade;
// not sure why I did that, actually doesn't make sense
//if (!(venv.type&1)) smp[g+s].volfade=0;
f.readDwords(&smp[g+s].samplen,1);
f.readDwords(&smp[g+s].loopstart,1);
f.readDwords(&smp[g+s].looplen,1);
smp[g+s].vol=XModule::vol64to255(f.readByte());
//f.read(&smp[g+s].vol,1,1);
f.read(&smp[g+s].finetune,1,1);
f.read(&smp[g+s].type,1,1);
#ifdef VERBOSE
printf("Before: %i, After: %i\n", smp[g+s].type, smp[g+s].type & (3+16));
#endif
f.read(&smp[g+s].pan,1,1);
f.read(&smp[g+s].relnote,1,1);
f.read(&smp[g+s].res,1,1);
f.read(&smp[g+s].name,1,22);
char line[30];
memset(line, 0, sizeof(line));
XModule::convertStr(line, smp[g+s].name, 23, false);
if (line[0])
module->addSongMessageLine(line);
#ifndef MILKYTRACKER
// ignore empty samples when not being a tracker
if (smp[g+s].samplen) {
smpReloc[sc] = g;
g++;
}
else
smpReloc[sc] = -1;
#else
smpReloc[sc] = g;
g++;
#endif
}
instr[y].samp = g;
for (sc = 0; sc < MP_MAXINSSAMPS; sc++) {
if (smpReloc[nbu[sc]] == -1)
instr[y].snum[sc] = -1;
else
instr[y].snum[sc] = smpReloc[nbu[sc]]+s;
}
for (sc=0;sc<instr[y].samp;sc++) {
if (smp[s].samplen)
{
bool adpcm = (smp[s].res == 0xAD);
mp_uint32 oldSize = smp[s].samplen;
if (smp[s].type&16)
{
smp[s].samplen>>=1;
smp[s].loopstart>>=1;
smp[s].looplen>>=1;
}
mp_sint32 result = module->loadModuleSample(f, s,
adpcm ? XModule::ST_PACKING_ADPCM : XModule::ST_DELTA,
adpcm ? (XModule::ST_PACKING_ADPCM | XModule::ST_16BIT) : (XModule::ST_DELTA | XModule::ST_16BIT),
oldSize);
if (result != MP_OK)
return result;
if (adpcm)
smp[s].res = 0;
}
s++;
if (s>=MP_MAXSAMPLES)
return MP_OUT_OF_MEMORY;
}
e++;
}
else
{
for (mp_sint32 i = 0; i < 120; i++)
instr[y].snum[i] = -1;
}
#ifdef MILKYTRACKER
s+=16 - instr[y].samp;
#endif
}
header->smpnum=s;
header->volenvnum=e;
header->panenvnum=e;
}
else
{
mp_sint32 s = 0;
for (y=0;y<header->insnum;y++) {
for (sc=0;sc<instr[y].samp;sc++) {
if (smp[s].samplen)
{
mp_uint32 oldSize = smp[s].samplen;
if (smp[s].type&16)
{
smp[s].samplen>>=1;
smp[s].loopstart>>=1;
smp[s].looplen>>=1;
}
mp_sint32 result = module->loadModuleSample(f, s, XModule::ST_DELTA, XModule::ST_DELTA | XModule::ST_16BIT, oldSize);
if (result != MP_OK)
return result;
}
s++;
if (s>=MP_MAXSAMPLES)
return MP_OUT_OF_MEMORY;
}
#ifdef MILKYTRACKER
s+=16 - instr[y].samp;
#endif
}
}
// convert modplug stereo samples
for (mp_sint32 s = 0; s < header->smpnum; s++)
{
if (smp[s].type & 32)
{
// that's what's allowed, stupid modplug tracker
smp[s].type &= 3+16;
if (smp[s].sample == NULL)
continue;
if (!(smp[s].type&16)) {
smp[s].samplen>>=1;
smp[s].loopstart>>=1;
smp[s].looplen>>=1;
mp_sbyte* sample = (mp_sbyte*)smp[s].sample;
mp_sint32 samplen = smp[s].samplen;
for (mp_sint32 i = 0; i < samplen; i++)
{
mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1;
if (s < -128) s = -128;
if (s > 127) s = 127;
sample[i] = (mp_sbyte)s;
}
}
else
{
smp[s].samplen>>=1;
smp[s].loopstart>>=1;
smp[s].looplen>>=1;
mp_sword* sample = (mp_sword*)smp[s].sample;
mp_sint32 samplen = smp[s].samplen;
for (mp_sint32 i = 0; i < samplen; i++)
{
mp_sint32 s = ((mp_sint32)sample[i] + (mp_sint32)sample[i + samplen]) >> 1;
if (s < -32768) s = -32768;
if (s > 32767) s = 32767;
sample[i] = (mp_sword)s;
}
}
}
// correct loop type 0x03 (undefined)
// will become ping pong loop
// note that FT2 will refuse to load XM files with such a loop type
if ((smp[s].type & 0x3) == 0x3)
smp[s].type&=~1;
}
// correct number of patterns if necessary, otherwise the post processing will remove
// the "invalid" patterns from the order list
bool addPatterns = false;
for (i = 0; i < header->ordnum; i++)
if (header->ord[i]+1 > header->patnum)
{
header->patnum = header->ord[i]+1;
addPatterns = true;
}
// if the pattern number has been adjusted, add some empty patterns
if (addPatterns)
{
for (i = 0; i < header->patnum; i++)
if (phead[i].patternData == NULL)
{
phead[i].rows = 64;
phead[i].effnum = 2;
phead[i].channum = (mp_ubyte)header->channum;
phead[i].patternData = new mp_ubyte[phead[i].rows*header->channum*6];
// out of memory?
if (phead[i].patternData == NULL)
{
return MP_OUT_OF_MEMORY;
}
memset(phead[i].patternData,0,phead[i].rows*header->channum*6);
}
}
// check for MODPLUG extensions
if (f.posWithBaseOffset() + 8 <= fileSize)
{
char buffer[4];
f.read(buffer, 1, 4);
if (memcmp(buffer, "text", 4) == 0)
{
mp_uint32 len = f.readDword();
module->allocateSongMessage(len+1);
memset(module->message, 0, len+1);
f.read(module->message, 1, len);
}
}
module->postProcessSamples();
return MP_OK;
}
| null | null | 199,952
|
83192180280574834367842323186237365521
| 790
|
Fix possible stack corruption with XM instrument headers claiming a size of less than 4
Closes #275
|
other
|
vim
|
37f47958b8a2a44abc60614271d9537e7f14e51a
| 1
|
ex_substitute(exarg_T *eap)
{
linenr_T lnum;
long i = 0;
regmmatch_T regmatch;
static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE,
FALSE, FALSE, 0};
#ifdef FEAT_EVAL
subflags_T subflags_save;
#endif
int save_do_all; // remember user specified 'g' flag
int save_do_ask; // remember user specified 'c' flag
char_u *pat = NULL, *sub = NULL; // init for GCC
int delimiter;
int sublen;
int got_quit = FALSE;
int got_match = FALSE;
int temp;
int which_pat;
char_u *cmd;
int save_State;
linenr_T first_line = 0; // first changed line
linenr_T last_line= 0; // below last changed line AFTER the
// change
linenr_T old_line_count = curbuf->b_ml.ml_line_count;
linenr_T line2;
long nmatch; // number of lines in match
char_u *sub_firstline; // allocated copy of first sub line
int endcolumn = FALSE; // cursor in last column when done
pos_T old_cursor = curwin->w_cursor;
int start_nsubs;
#ifdef FEAT_EVAL
int save_ma = 0;
#endif
cmd = eap->arg;
if (!global_busy)
{
sub_nsubs = 0;
sub_nlines = 0;
}
start_nsubs = sub_nsubs;
if (eap->cmdidx == CMD_tilde)
which_pat = RE_LAST; // use last used regexp
else
which_pat = RE_SUBST; // use last substitute regexp
// new pattern and substitution
if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd)
&& vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL)
{
// don't accept alphanumeric for separator
if (check_regexp_delim(*cmd) == FAIL)
return;
#ifdef FEAT_EVAL
if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg)
== FAIL)
return;
#endif
/*
* undocumented vi feature:
* "\/sub/" and "\?sub?" use last used search pattern (almost like
* //sub/r). "\&sub&" use last substitute pattern (like //sub/).
*/
if (*cmd == '\\')
{
++cmd;
if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
{
emsg(_(e_backslash_should_be_followed_by));
return;
}
if (*cmd != '&')
which_pat = RE_SEARCH; // use last '/' pattern
pat = (char_u *)""; // empty search pattern
delimiter = *cmd++; // remember delimiter character
}
else // find the end of the regexp
{
which_pat = RE_LAST; // use last used regexp
delimiter = *cmd++; // remember delimiter character
pat = cmd; // remember start of search pat
cmd = skip_regexp_ex(cmd, delimiter, magic_isset(),
&eap->arg, NULL, NULL);
if (cmd[0] == delimiter) // end delimiter found
*cmd++ = NUL; // replace it with a NUL
}
/*
* Small incompatibility: vi sees '\n' as end of the command, but in
* Vim we want to use '\n' to find/substitute a NUL.
*/
sub = cmd; // remember the start of the substitution
cmd = skip_substitute(cmd, delimiter);
if (!eap->skip)
{
// In POSIX vi ":s/pat/%/" uses the previous subst. string.
if (STRCMP(sub, "%") == 0
&& vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
{
if (old_sub == NULL) // there is no previous command
{
emsg(_(e_no_previous_substitute_regular_expression));
return;
}
sub = old_sub;
}
else
{
vim_free(old_sub);
old_sub = vim_strsave(sub);
}
}
}
else if (!eap->skip) // use previous pattern and substitution
{
if (old_sub == NULL) // there is no previous command
{
emsg(_(e_no_previous_substitute_regular_expression));
return;
}
pat = NULL; // search_regcomp() will use previous pattern
sub = old_sub;
// Vi compatibility quirk: repeating with ":s" keeps the cursor in the
// last column after using "$".
endcolumn = (curwin->w_curswant == MAXCOL);
}
// Recognize ":%s/\n//" and turn it into a join command, which is much
// more efficient.
// TODO: find a generic solution to make line-joining operations more
// efficient, avoid allocating a string that grows in size.
if (pat != NULL && STRCMP(pat, "\\n") == 0
&& *sub == NUL
&& (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l'
|| *cmd == 'p' || *cmd == '#'))))
{
linenr_T joined_lines_count;
if (eap->skip)
return;
curwin->w_cursor.lnum = eap->line1;
if (*cmd == 'l')
eap->flags = EXFLAG_LIST;
else if (*cmd == '#')
eap->flags = EXFLAG_NR;
else if (*cmd == 'p')
eap->flags = EXFLAG_PRINT;
// The number of lines joined is the number of lines in the range plus
// one. One less when the last line is included.
joined_lines_count = eap->line2 - eap->line1 + 1;
if (eap->line2 < curbuf->b_ml.ml_line_count)
++joined_lines_count;
if (joined_lines_count > 1)
{
(void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE);
sub_nsubs = joined_lines_count - 1;
sub_nlines = 1;
(void)do_sub_msg(FALSE);
ex_may_print(eap);
}
if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)
save_re_pat(RE_SUBST, pat, magic_isset());
// put pattern in history
add_to_history(HIST_SEARCH, pat, TRUE, NUL);
return;
}
/*
* Find trailing options. When '&' is used, keep old options.
*/
if (*cmd == '&')
++cmd;
else
{
#ifdef FEAT_EVAL
if (in_vim9script())
{
// ignore 'gdefault' and 'edcompatible'
subflags.do_all = FALSE;
subflags.do_ask = FALSE;
}
else
#endif
if (!p_ed)
{
if (p_gd) // default is global on
subflags.do_all = TRUE;
else
subflags.do_all = FALSE;
subflags.do_ask = FALSE;
}
subflags.do_error = TRUE;
subflags.do_print = FALSE;
subflags.do_list = FALSE;
subflags.do_count = FALSE;
subflags.do_number = FALSE;
subflags.do_ic = 0;
}
while (*cmd)
{
/*
* Note that 'g' and 'c' are always inverted, also when p_ed is off.
* 'r' is never inverted.
*/
if (*cmd == 'g')
subflags.do_all = !subflags.do_all;
else if (*cmd == 'c')
subflags.do_ask = !subflags.do_ask;
else if (*cmd == 'n')
subflags.do_count = TRUE;
else if (*cmd == 'e')
subflags.do_error = !subflags.do_error;
else if (*cmd == 'r') // use last used regexp
which_pat = RE_LAST;
else if (*cmd == 'p')
subflags.do_print = TRUE;
else if (*cmd == '#')
{
subflags.do_print = TRUE;
subflags.do_number = TRUE;
}
else if (*cmd == 'l')
{
subflags.do_print = TRUE;
subflags.do_list = TRUE;
}
else if (*cmd == 'i') // ignore case
subflags.do_ic = 'i';
else if (*cmd == 'I') // don't ignore case
subflags.do_ic = 'I';
else
break;
++cmd;
}
if (subflags.do_count)
subflags.do_ask = FALSE;
save_do_all = subflags.do_all;
save_do_ask = subflags.do_ask;
/*
* check for a trailing count
*/
cmd = skipwhite(cmd);
if (VIM_ISDIGIT(*cmd))
{
i = getdigits(&cmd);
if (i <= 0 && !eap->skip && subflags.do_error)
{
emsg(_(e_positive_count_required));
return;
}
eap->line1 = eap->line2;
eap->line2 += i - 1;
if (eap->line2 > curbuf->b_ml.ml_line_count)
eap->line2 = curbuf->b_ml.ml_line_count;
}
/*
* check for trailing command or garbage
*/
cmd = skipwhite(cmd);
if (*cmd && *cmd != '"') // if not end-of-line or comment
{
set_nextcmd(eap, cmd);
if (eap->nextcmd == NULL)
{
semsg(_(e_trailing_characters_str), cmd);
return;
}
}
if (eap->skip) // not executing commands, only parsing
return;
if (!subflags.do_count && !curbuf->b_p_ma)
{
// Substitution is not allowed in non-'modifiable' buffer
emsg(_(e_cannot_make_changes_modifiable_is_off));
return;
}
if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, ®match) == FAIL)
{
if (subflags.do_error)
emsg(_(e_invalid_command));
return;
}
// the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'
if (subflags.do_ic == 'i')
regmatch.rmm_ic = TRUE;
else if (subflags.do_ic == 'I')
regmatch.rmm_ic = FALSE;
sub_firstline = NULL;
/*
* ~ in the substitute pattern is replaced with the old pattern.
* We do it here once to avoid it to be replaced over and over again.
* But don't do it when it starts with "\=", then it's an expression.
*/
if (!(sub[0] == '\\' && sub[1] == '='))
sub = regtilde(sub, magic_isset());
/*
* Check for a match on each line.
*/
line2 = eap->line2;
for (lnum = eap->line1; lnum <= line2 && !(got_quit
#if defined(FEAT_EVAL)
|| aborting()
#endif
); ++lnum)
{
nmatch = vim_regexec_multi(®match, curwin, curbuf, lnum,
(colnr_T)0, NULL, NULL);
if (nmatch)
{
colnr_T copycol;
colnr_T matchcol;
colnr_T prev_matchcol = MAXCOL;
char_u *new_end, *new_start = NULL;
unsigned new_start_len = 0;
char_u *p1;
int did_sub = FALSE;
int lastone;
int len, copy_len, needed_len;
long nmatch_tl = 0; // nr of lines matched below lnum
int do_again; // do it again after joining lines
int skip_match = FALSE;
linenr_T sub_firstlnum; // nr of first sub line
#ifdef FEAT_PROP_POPUP
int apc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE;
colnr_T total_added = 0;
#endif
/*
* The new text is build up step by step, to avoid too much
* copying. There are these pieces:
* sub_firstline The old text, unmodified.
* copycol Column in the old text where we started
* looking for a match; from here old text still
* needs to be copied to the new text.
* matchcol Column number of the old text where to look
* for the next match. It's just after the
* previous match or one further.
* prev_matchcol Column just after the previous match (if any).
* Mostly equal to matchcol, except for the first
* match and after skipping an empty match.
* regmatch.*pos Where the pattern matched in the old text.
* new_start The new text, all that has been produced so
* far.
* new_end The new text, where to append new text.
*
* lnum The line number where we found the start of
* the match. Can be below the line we searched
* when there is a \n before a \zs in the
* pattern.
* sub_firstlnum The line number in the buffer where to look
* for a match. Can be different from "lnum"
* when the pattern or substitute string contains
* line breaks.
*
* Special situations:
* - When the substitute string contains a line break, the part up
* to the line break is inserted in the text, but the copy of
* the original line is kept. "sub_firstlnum" is adjusted for
* the inserted lines.
* - When the matched pattern contains a line break, the old line
* is taken from the line at the end of the pattern. The lines
* in the match are deleted later, "sub_firstlnum" is adjusted
* accordingly.
*
* The new text is built up in new_start[]. It has some extra
* room to avoid using alloc()/free() too often. new_start_len is
* the length of the allocated memory at new_start.
*
* Make a copy of the old line, so it won't be taken away when
* updating the screen or handling a multi-line match. The "old_"
* pointers point into this copy.
*/
sub_firstlnum = lnum;
copycol = 0;
matchcol = 0;
// At first match, remember current cursor position.
if (!got_match)
{
setpcmark();
got_match = TRUE;
}
/*
* Loop until nothing more to replace in this line.
* 1. Handle match with empty string.
* 2. If do_ask is set, ask for confirmation.
* 3. substitute the string.
* 4. if do_all is set, find next match
* 5. break if there isn't another match in this line
*/
for (;;)
{
// Advance "lnum" to the line where the match starts. The
// match does not start in the first line when there is a line
// break before \zs.
if (regmatch.startpos[0].lnum > 0)
{
lnum += regmatch.startpos[0].lnum;
sub_firstlnum += regmatch.startpos[0].lnum;
nmatch -= regmatch.startpos[0].lnum;
VIM_CLEAR(sub_firstline);
}
// Match might be after the last line for "\n\zs" matching at
// the end of the last line.
if (lnum > curbuf->b_ml.ml_line_count)
break;
if (sub_firstline == NULL)
{
sub_firstline = vim_strsave(ml_get(sub_firstlnum));
if (sub_firstline == NULL)
{
vim_free(new_start);
goto outofmem;
}
}
// Save the line number of the last change for the final
// cursor position (just like Vi).
curwin->w_cursor.lnum = lnum;
do_again = FALSE;
/*
* 1. Match empty string does not count, except for first
* match. This reproduces the strange vi behaviour.
* This also catches endless loops.
*/
if (matchcol == prev_matchcol
&& regmatch.endpos[0].lnum == 0
&& matchcol == regmatch.endpos[0].col)
{
if (sub_firstline[matchcol] == NUL)
// We already were at the end of the line. Don't look
// for a match in this line again.
skip_match = TRUE;
else
{
// search for a match at next column
if (has_mbyte)
matchcol += mb_ptr2len(sub_firstline + matchcol);
else
++matchcol;
}
goto skip;
}
// Normally we continue searching for a match just after the
// previous match.
matchcol = regmatch.endpos[0].col;
prev_matchcol = matchcol;
/*
* 2. If do_count is set only increase the counter.
* If do_ask is set, ask for confirmation.
*/
if (subflags.do_count)
{
// For a multi-line match, put matchcol at the NUL at
// the end of the line and set nmatch to one, so that
// we continue looking for a match on the next line.
// Avoids that ":s/\nB\@=//gc" get stuck.
if (nmatch > 1)
{
matchcol = (colnr_T)STRLEN(sub_firstline);
nmatch = 1;
skip_match = TRUE;
}
sub_nsubs++;
did_sub = TRUE;
#ifdef FEAT_EVAL
// Skip the substitution, unless an expression is used,
// then it is evaluated in the sandbox.
if (!(sub[0] == '\\' && sub[1] == '='))
#endif
goto skip;
}
if (subflags.do_ask)
{
int typed = 0;
// change State to CONFIRM, so that the mouse works
// properly
save_State = State;
State = CONFIRM;
setmouse(); // disable mouse in xterm
curwin->w_cursor.col = regmatch.startpos[0].col;
if (curwin->w_p_crb)
do_check_cursorbind();
// When 'cpoptions' contains "u" don't sync undo when
// asking for confirmation.
if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
++no_u_sync;
/*
* Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
*/
while (subflags.do_ask)
{
if (exmode_active)
{
char_u *resp;
colnr_T sc, ec;
print_line_no_prefix(lnum,
subflags.do_number, subflags.do_list);
getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
curwin->w_cursor.col = regmatch.endpos[0].col - 1;
if (curwin->w_cursor.col < 0)
curwin->w_cursor.col = 0;
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
curwin->w_cursor.col = regmatch.startpos[0].col;
if (subflags.do_number || curwin->w_p_nu)
{
int numw = number_width(curwin) + 1;
sc += numw;
ec += numw;
}
msg_start();
for (i = 0; i < (long)sc; ++i)
msg_putchar(' ');
for ( ; i <= (long)ec; ++i)
msg_putchar('^');
resp = getexmodeline('?', NULL, 0, TRUE);
if (resp != NULL)
{
typed = *resp;
vim_free(resp);
}
}
else
{
char_u *orig_line = NULL;
int len_change = 0;
int save_p_lz = p_lz;
#ifdef FEAT_FOLDING
int save_p_fen = curwin->w_p_fen;
curwin->w_p_fen = FALSE;
#endif
// Invert the matched string.
// Remove the inversion afterwards.
temp = RedrawingDisabled;
RedrawingDisabled = 0;
// avoid calling update_screen() in vgetorpeek()
p_lz = FALSE;
if (new_start != NULL)
{
// There already was a substitution, we would
// like to show this to the user. We cannot
// really update the line, it would change
// what matches. Temporarily replace the line
// and change it back afterwards.
orig_line = vim_strsave(ml_get(lnum));
if (orig_line != NULL)
{
char_u *new_line = concat_str(new_start,
sub_firstline + copycol);
if (new_line == NULL)
VIM_CLEAR(orig_line);
else
{
// Position the cursor relative to the
// end of the line, the previous
// substitute may have inserted or
// deleted characters before the
// cursor.
len_change = (int)STRLEN(new_line)
- (int)STRLEN(orig_line);
curwin->w_cursor.col += len_change;
ml_replace(lnum, new_line, FALSE);
}
}
}
search_match_lines = regmatch.endpos[0].lnum
- regmatch.startpos[0].lnum;
search_match_endcol = regmatch.endpos[0].col
+ len_change;
highlight_match = TRUE;
update_topline();
validate_cursor();
update_screen(SOME_VALID);
highlight_match = FALSE;
redraw_later(SOME_VALID);
#ifdef FEAT_FOLDING
curwin->w_p_fen = save_p_fen;
#endif
if (msg_row == Rows - 1)
msg_didout = FALSE; // avoid a scroll-up
msg_starthere();
i = msg_scroll;
msg_scroll = 0; // truncate msg when
// needed
msg_no_more = TRUE;
// write message same highlighting as for
// wait_return
smsg_attr(HL_ATTR(HLF_R),
_("replace with %s (y/n/a/q/l/^E/^Y)?"), sub);
msg_no_more = FALSE;
msg_scroll = i;
showruler(TRUE);
windgoto(msg_row, msg_col);
RedrawingDisabled = temp;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = FALSE; // allow scrolling here
#endif
++no_mapping; // don't map this key
++allow_keys; // allow special keys
typed = plain_vgetc();
--allow_keys;
--no_mapping;
// clear the question
msg_didout = FALSE; // don't scroll up
msg_col = 0;
gotocmdline(TRUE);
p_lz = save_p_lz;
// restore the line
if (orig_line != NULL)
ml_replace(lnum, orig_line, FALSE);
}
need_wait_return = FALSE; // no hit-return prompt
if (typed == 'q' || typed == ESC || typed == Ctrl_C
#ifdef UNIX
|| typed == intr_char
#endif
)
{
got_quit = TRUE;
break;
}
if (typed == 'n')
break;
if (typed == 'y')
break;
if (typed == 'l')
{
// last: replace and then stop
subflags.do_all = FALSE;
line2 = lnum;
break;
}
if (typed == 'a')
{
subflags.do_ask = FALSE;
break;
}
if (typed == Ctrl_E)
scrollup_clamp();
else if (typed == Ctrl_Y)
scrolldown_clamp();
}
State = save_State;
setmouse();
if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
--no_u_sync;
if (typed == 'n')
{
// For a multi-line match, put matchcol at the NUL at
// the end of the line and set nmatch to one, so that
// we continue looking for a match on the next line.
// Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc"
// get stuck when pressing 'n'.
if (nmatch > 1)
{
matchcol = (colnr_T)STRLEN(sub_firstline);
skip_match = TRUE;
}
goto skip;
}
if (got_quit)
goto skip;
}
// Move the cursor to the start of the match, so that we can
// use "\=col(".").
curwin->w_cursor.col = regmatch.startpos[0].col;
/*
* 3. substitute the string.
*/
#ifdef FEAT_EVAL
save_ma = curbuf->b_p_ma;
if (subflags.do_count)
{
// prevent accidentally changing the buffer by a function
curbuf->b_p_ma = FALSE;
sandbox++;
}
// Save flags for recursion. They can change for e.g.
// :s/^/\=execute("s#^##gn")
subflags_save = subflags;
#endif
// get length of substitution part
sublen = vim_regsub_multi(®match,
sub_firstlnum - regmatch.startpos[0].lnum,
sub, sub_firstline, FALSE, magic_isset(), TRUE);
#ifdef FEAT_EVAL
// If getting the substitute string caused an error, don't do
// the replacement.
// Don't keep flags set by a recursive call.
subflags = subflags_save;
if (aborting() || subflags.do_count)
{
curbuf->b_p_ma = save_ma;
if (sandbox > 0)
sandbox--;
goto skip;
}
#endif
// When the match included the "$" of the last line it may
// go beyond the last line of the buffer.
if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)
{
nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;
skip_match = TRUE;
}
// Need room for:
// - result so far in new_start (not for first sub in line)
// - original text up to match
// - length of substituted part
// - original text after match
// Adjust text properties here, since we have all information
// needed.
if (nmatch == 1)
{
p1 = sub_firstline;
#ifdef FEAT_PROP_POPUP
if (curbuf->b_has_textprop)
{
int bytes_added = sublen - 1 - (regmatch.endpos[0].col
- regmatch.startpos[0].col);
// When text properties are changed, need to save for
// undo first, unless done already.
if (adjust_prop_columns(lnum,
total_added + regmatch.startpos[0].col,
bytes_added, apc_flags))
apc_flags &= ~APC_SAVE_FOR_UNDO;
// Offset for column byte number of the text property
// in the resulting buffer afterwards.
total_added += bytes_added;
}
#endif
}
else
{
p1 = ml_get(sub_firstlnum + nmatch - 1);
nmatch_tl += nmatch - 1;
}
copy_len = regmatch.startpos[0].col - copycol;
needed_len = copy_len + ((unsigned)STRLEN(p1)
- regmatch.endpos[0].col) + sublen + 1;
if (new_start == NULL)
{
/*
* Get some space for a temporary buffer to do the
* substitution into (and some extra space to avoid
* too many calls to alloc()/free()).
*/
new_start_len = needed_len + 50;
if ((new_start = alloc(new_start_len)) == NULL)
goto outofmem;
*new_start = NUL;
new_end = new_start;
}
else
{
/*
* Check if the temporary buffer is long enough to do the
* substitution into. If not, make it larger (with a bit
* extra to avoid too many calls to alloc()/free()).
*/
len = (unsigned)STRLEN(new_start);
needed_len += len;
if (needed_len > (int)new_start_len)
{
new_start_len = needed_len + 50;
if ((p1 = alloc(new_start_len)) == NULL)
{
vim_free(new_start);
goto outofmem;
}
mch_memmove(p1, new_start, (size_t)(len + 1));
vim_free(new_start);
new_start = p1;
}
new_end = new_start + len;
}
/*
* copy the text up to the part that matched
*/
mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);
new_end += copy_len;
(void)vim_regsub_multi(®match,
sub_firstlnum - regmatch.startpos[0].lnum,
sub, new_end, TRUE, magic_isset(), TRUE);
sub_nsubs++;
did_sub = TRUE;
// Move the cursor to the start of the line, to avoid that it
// is beyond the end of the line after the substitution.
curwin->w_cursor.col = 0;
// For a multi-line match, make a copy of the last matched
// line and continue in that one.
if (nmatch > 1)
{
sub_firstlnum += nmatch - 1;
vim_free(sub_firstline);
sub_firstline = vim_strsave(ml_get(sub_firstlnum));
// When going beyond the last line, stop substituting.
if (sub_firstlnum <= line2)
do_again = TRUE;
else
subflags.do_all = FALSE;
}
// Remember next character to be copied.
copycol = regmatch.endpos[0].col;
if (skip_match)
{
// Already hit end of the buffer, sub_firstlnum is one
// less than what it ought to be.
vim_free(sub_firstline);
sub_firstline = vim_strsave((char_u *)"");
copycol = 0;
}
/*
* Now the trick is to replace CTRL-M chars with a real line
* break. This would make it impossible to insert a CTRL-M in
* the text. The line break can be avoided by preceding the
* CTRL-M with a backslash. To be able to insert a backslash,
* they must be doubled in the string and are halved here.
* That is Vi compatible.
*/
for (p1 = new_end; *p1; ++p1)
{
if (p1[0] == '\\' && p1[1] != NUL) // remove backslash
{
STRMOVE(p1, p1 + 1);
#ifdef FEAT_PROP_POPUP
if (curbuf->b_has_textprop)
{
// When text properties are changed, need to save
// for undo first, unless done already.
if (adjust_prop_columns(lnum,
(colnr_T)(p1 - new_start), -1,
apc_flags))
apc_flags &= ~APC_SAVE_FOR_UNDO;
}
#endif
}
else if (*p1 == CAR)
{
if (u_inssub(lnum) == OK) // prepare for undo
{
colnr_T plen = (colnr_T)(p1 - new_start + 1);
*p1 = NUL; // truncate up to the CR
ml_append(lnum - 1, new_start, plen, FALSE);
mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
if (subflags.do_ask)
appended_lines(lnum - 1, 1L);
else
{
if (first_line == 0)
first_line = lnum;
last_line = lnum + 1;
}
#ifdef FEAT_PROP_POPUP
adjust_props_for_split(lnum + 1, lnum, plen, 1);
#endif
// all line numbers increase
++sub_firstlnum;
++lnum;
++line2;
// move the cursor to the new line, like Vi
++curwin->w_cursor.lnum;
// copy the rest
STRMOVE(new_start, p1 + 1);
p1 = new_start - 1;
}
}
else if (has_mbyte)
p1 += (*mb_ptr2len)(p1) - 1;
}
/*
* 4. If do_all is set, find next match.
* Prevent endless loop with patterns that match empty
* strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
* But ":s/\n/#/" is OK.
*/
skip:
// We already know that we did the last subst when we are at
// the end of the line, except that a pattern like
// "bar\|\nfoo" may match at the NUL. "lnum" can be below
// "line2" when there is a \zs in the pattern after a line
// break.
lastone = (skip_match
|| got_int
|| got_quit
|| lnum > line2
|| !(subflags.do_all || do_again)
|| (sub_firstline[matchcol] == NUL && nmatch <= 1
&& !re_multiline(regmatch.regprog)));
nmatch = -1;
/*
* Replace the line in the buffer when needed. This is
* skipped when there are more matches.
* The check for nmatch_tl is needed for when multi-line
* matching must replace the lines before trying to do another
* match, otherwise "\@<=" won't work.
* When the match starts below where we start searching also
* need to replace the line first (using \zs after \n).
*/
if (lastone
|| nmatch_tl > 0
|| (nmatch = vim_regexec_multi(®match, curwin,
curbuf, sub_firstlnum,
matchcol, NULL, NULL)) == 0
|| regmatch.startpos[0].lnum > 0)
{
if (new_start != NULL)
{
/*
* Copy the rest of the line, that didn't match.
* "matchcol" has to be adjusted, we use the end of
* the line as reference, because the substitute may
* have changed the number of characters. Same for
* "prev_matchcol".
*/
STRCAT(new_start, sub_firstline + copycol);
matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
prev_matchcol = (colnr_T)STRLEN(sub_firstline)
- prev_matchcol;
if (u_savesub(lnum) != OK)
break;
ml_replace(lnum, new_start, TRUE);
if (nmatch_tl > 0)
{
/*
* Matched lines have now been substituted and are
* useless, delete them. The part after the match
* has been appended to new_start, we don't need
* it in the buffer.
*/
++lnum;
if (u_savedel(lnum, nmatch_tl) != OK)
break;
for (i = 0; i < nmatch_tl; ++i)
ml_delete(lnum);
mark_adjust(lnum, lnum + nmatch_tl - 1,
(long)MAXLNUM, -nmatch_tl);
if (subflags.do_ask)
deleted_lines(lnum, nmatch_tl);
--lnum;
line2 -= nmatch_tl; // nr of lines decreases
nmatch_tl = 0;
}
// When asking, undo is saved each time, must also set
// changed flag each time.
if (subflags.do_ask)
changed_bytes(lnum, 0);
else
{
if (first_line == 0)
first_line = lnum;
last_line = lnum + 1;
}
sub_firstlnum = lnum;
vim_free(sub_firstline); // free the temp buffer
sub_firstline = new_start;
new_start = NULL;
matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
prev_matchcol = (colnr_T)STRLEN(sub_firstline)
- prev_matchcol;
copycol = 0;
}
if (nmatch == -1 && !lastone)
nmatch = vim_regexec_multi(®match, curwin, curbuf,
sub_firstlnum, matchcol, NULL, NULL);
/*
* 5. break if there isn't another match in this line
*/
if (nmatch <= 0)
{
// If the match found didn't start where we were
// searching, do the next search in the line where we
// found the match.
if (nmatch == -1)
lnum -= regmatch.startpos[0].lnum;
break;
}
}
line_breakcheck();
}
if (did_sub)
++sub_nlines;
vim_free(new_start); // for when substitute was cancelled
VIM_CLEAR(sub_firstline); // free the copy of the original line
}
line_breakcheck();
}
if (first_line != 0)
{
// Need to subtract the number of added lines from "last_line" to get
// the line number before the change (same as adding the number of
// deleted lines).
i = curbuf->b_ml.ml_line_count - old_line_count;
changed_lines(first_line, 0, last_line - i, i);
}
outofmem:
vim_free(sub_firstline); // may have to free allocated copy of the line
// ":s/pat//n" doesn't move the cursor
if (subflags.do_count)
curwin->w_cursor = old_cursor;
if (sub_nsubs > start_nsubs)
{
if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
{
// Set the '[ and '] marks.
curbuf->b_op_start.lnum = eap->line1;
curbuf->b_op_end.lnum = line2;
curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
}
if (!global_busy)
{
// when interactive leave cursor on the match
if (!subflags.do_ask)
{
if (endcolumn)
coladvance((colnr_T)MAXCOL);
else
beginline(BL_WHITE | BL_FIX);
}
if (!do_sub_msg(subflags.do_count) && subflags.do_ask)
msg("");
}
else
global_need_beginline = TRUE;
if (subflags.do_print)
print_line(curwin->w_cursor.lnum,
subflags.do_number, subflags.do_list);
}
else if (!global_busy)
{
if (got_int) // interrupted
emsg(_(e_interrupted));
else if (got_match) // did find something but nothing substituted
msg("");
else if (subflags.do_error) // nothing found
semsg(_(e_pattern_not_found_str), get_search_pat());
}
#ifdef FEAT_FOLDING
if (subflags.do_ask && hasAnyFolding(curwin))
// Cursor position may require updating
changed_window_setting();
#endif
vim_regfree(regmatch.regprog);
// Restore the flag values, they can be used for ":&&".
subflags.do_all = save_do_all;
subflags.do_ask = save_do_ask;
}
| null | null | 199,984
|
260216811169709745358018434345046580146
| 1,121
|
patch 8.2.4253: using freed memory when substitute with function call
Problem: Using freed memory when substitute uses a recursive function call.
Solution: Make a copy of the substitute text.
|
other
|
php-src
|
64043cb9e5d8bc5af719678893e38ee0290e0c0a
| 1
|
static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table TSRMLS_DC)
{
size_t length;
int tag, format, components;
char *value_ptr, tagname[64], cbuf[32], *outside=NULL;
size_t byte_count, offset_val, fpos, fgot;
int64_t byte_count_signed;
xp_field_type *tmp_xp;
#ifdef EXIF_DEBUG
char *dump_data;
int dump_free;
#endif /* EXIF_DEBUG */
/* Protect against corrupt headers */
if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "corrupt EXIF header: maximum directory nesting level reached");
return FALSE;
}
ImageInfo->ifd_nesting_level++;
tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel);
format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel);
components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel);
if (!format || format > NUM_FORMATS) {
/* (-1) catches illegal zero case as unsigned underflows to positive large. */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal format code 0x%04X, suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), format);
format = TAG_FMT_BYTE;
/*return TRUE;*/
}
if (components < 0) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal components(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), components);
return FALSE;
}
byte_count_signed = (int64_t)components * php_tiff_bytes_per_format[format];
if (byte_count_signed < 0 || (byte_count_signed > INT32_MAX)) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal byte_count", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC));
return FALSE;
}
byte_count = (size_t)byte_count_signed;
if (byte_count > 4) {
offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel);
/* If its bigger than 4 bytes, the dir entry contains an offset. */
value_ptr = offset_base+offset_val;
/*
dir_entry is ImageInfo->file.list[sn].data+2+i*12
offset_base is ImageInfo->file.list[sn].data-dir_offset
dir_entry - offset_base is dir_offset+2+i*12
*/
if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) {
/* It is important to check for IMAGE_FILETYPE_TIFF
* JPEG does not use absolute pointers instead its pointers are
* relative to the start of the TIFF header in APP1 section. */
if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) {
if (value_ptr < dir_entry) {
/* we can read this if offset_val > 0 */
/* some files have their values in other parts of the file */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X < x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, dir_entry);
} else {
/* this is for sure not allowed */
/* exception are IFD pointers */
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Process tag(x%04X=%s): Illegal pointer offset(x%04X + x%04X = x%04X > x%04X)", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val, byte_count, offset_val+byte_count, IFDlength);
}
return FALSE;
}
if (byte_count>sizeof(cbuf)) {
/* mark as outside range and get buffer */
value_ptr = safe_emalloc(byte_count, 1, 0);
outside = value_ptr;
} else {
/* In most cases we only access a small range so
* it is faster to use a static buffer there
* BUT it offers also the possibility to have
* pointers read without the need to free them
* explicitley before returning. */
memset(&cbuf, 0, sizeof(cbuf));
value_ptr = cbuf;
}
fpos = php_stream_tell(ImageInfo->infile);
php_stream_seek(ImageInfo->infile, offset_val, SEEK_SET);
fgot = php_stream_tell(ImageInfo->infile);
if (fgot!=offset_val) {
EFREE_IF(outside);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Wrong file pointer: 0x%08X != 0x%08X", fgot, offset_val);
return FALSE;
}
fgot = php_stream_read(ImageInfo->infile, value_ptr, byte_count);
php_stream_seek(ImageInfo->infile, fpos, SEEK_SET);
if (fgot<byte_count) {
EFREE_IF(outside);
EXIF_ERRLOG_FILEEOF(ImageInfo)
return FALSE;
}
}
} else {
/* 4 bytes or less and value is in the dir entry itself */
value_ptr = dir_entry+8;
offset_val= value_ptr-offset_base;
}
ImageInfo->sections_found |= FOUND_ANY_TAG;
#ifdef EXIF_DEBUG
dump_data = exif_dump_data(&dump_free, format, components, length, ImageInfo->motorola_intel, value_ptr TSRMLS_CC);
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process tag(x%04X=%s,@x%04X + x%04X(=%d)): %s%s %s", tag, exif_get_tagname(tag, tagname, -12, tag_table TSRMLS_CC), offset_val+displacement, byte_count, byte_count, (components>1)&&format!=TAG_FMT_UNDEFINED&&format!=TAG_FMT_STRING?"ARRAY OF ":"", exif_get_tagformat(format), dump_data);
if (dump_free) {
efree(dump_data);
}
#endif
if (section_index==SECTION_THUMBNAIL) {
if (!ImageInfo->Thumbnail.data) {
switch(tag) {
case TAG_IMAGEWIDTH:
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_IMAGEHEIGHT:
case TAG_COMP_IMAGE_HEIGHT:
ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_OFFSETS:
case TAG_JPEG_INTERCHANGE_FORMAT:
/* accept both formats */
ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_STRIP_BYTE_COUNTS:
if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) {
ImageInfo->Thumbnail.filetype = ImageInfo->FileType;
} else {
/* motorola is easier to read */
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM;
}
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_JPEG_INTERCHANGE_FORMAT_LEN:
if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) {
ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG;
ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
}
break;
}
}
} else {
if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF)
switch(tag) {
case TAG_COPYRIGHT:
/* check for "<photographer> NUL <editor> NUL" */
if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) {
if (length<byte_count-1) {
/* When there are any characters after the first NUL */
ImageInfo->CopyrightPhotographer = estrdup(value_ptr);
ImageInfo->CopyrightEditor = estrdup(value_ptr+length+1);
spprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, value_ptr+length+1);
/* format = TAG_FMT_UNDEFINED; this musn't be ASCII */
/* but we are not supposed to change this */
/* keep in mind that image_info does not store editor value */
} else {
ImageInfo->Copyright = estrdup(value_ptr);
}
}
break;
case TAG_USERCOMMENT:
ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count TSRMLS_CC);
break;
case TAG_XP_TITLE:
case TAG_XP_COMMENTS:
case TAG_XP_AUTHOR:
case TAG_XP_KEYWORDS:
case TAG_XP_SUBJECT:
tmp_xp = (xp_field_type*)safe_erealloc(ImageInfo->xp_fields.list, (ImageInfo->xp_fields.count+1), sizeof(xp_field_type), 0);
ImageInfo->sections_found |= FOUND_WINXP;
ImageInfo->xp_fields.list = tmp_xp;
ImageInfo->xp_fields.count++;
exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count TSRMLS_CC);
break;
case TAG_FNUMBER:
/* Simplest way of expressing aperture, so I trust it the most.
(overwrite previously computed value if there is one) */
ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_APERTURE:
case TAG_MAX_APERTURE:
/* More relevant info always comes earlier, so only use this field if we don't
have appropriate aperture information yet. */
if (ImageInfo->ApertureFNumber == 0) {
ImageInfo->ApertureFNumber
= (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)*0.5);
}
break;
case TAG_SHUTTERSPEED:
/* More complicated way of expressing exposure time, so only use
this value if we don't already have it from somewhere else.
SHUTTERSPEED comes after EXPOSURE TIME
*/
if (ImageInfo->ExposureTime == 0) {
ImageInfo->ExposureTime
= (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)*log(2)));
}
break;
case TAG_EXPOSURETIME:
ImageInfo->ExposureTime = -1;
break;
case TAG_COMP_IMAGE_WIDTH:
ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_X_RES:
ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_SUBJECT_DISTANCE:
/* Inidcates the distacne the autofocus camera is focused to.
Tends to be less accurate as distance increases. */
ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC);
break;
case TAG_FOCALPLANE_RESOLUTION_UNIT:
switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel TSRMLS_CC)) {
case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */
case 2:
/* According to the information I was using, 2 measn meters.
But looking at the Cannon powershot's files, inches is the only
sensible value. */
ImageInfo->FocalplaneUnits = 25.4;
break;
case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */
case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */
case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */
}
break;
case TAG_SUB_IFD:
if (format==TAG_FMT_IFD) {
/* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */
/* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */
/* JPEG do we have the data area and what to do with it */
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Skip SUB IFD");
}
break;
case TAG_MAKE:
ImageInfo->make = estrdup(value_ptr);
break;
case TAG_MODEL:
ImageInfo->model = estrdup(value_ptr);
break;
case TAG_MAKER_NOTE:
exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement TSRMLS_CC);
break;
case TAG_EXIF_IFD_POINTER:
case TAG_GPS_IFD_POINTER:
case TAG_INTEROP_IFD_POINTER:
if (ReadNextIFD) {
char *Subdir_start;
int sub_section_index = 0;
switch(tag) {
case TAG_EXIF_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found EXIF");
#endif
ImageInfo->sections_found |= FOUND_EXIF;
sub_section_index = SECTION_EXIF;
break;
case TAG_GPS_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found GPS");
#endif
ImageInfo->sections_found |= FOUND_GPS;
sub_section_index = SECTION_GPS;
break;
case TAG_INTEROP_IFD_POINTER:
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Found INTEROPERABILITY");
#endif
ImageInfo->sections_found |= FOUND_INTEROP;
sub_section_index = SECTION_INTEROP;
break;
}
Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel);
if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) {
exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD Pointer");
return FALSE;
}
if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, IFDlength, displacement, sub_section_index TSRMLS_CC)) {
return FALSE;
}
#ifdef EXIF_DEBUG
exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(sub_section_index));
#endif
}
}
}
exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table TSRMLS_CC), tag, format, components, value_ptr TSRMLS_CC);
EFREE_IF(outside);
return TRUE;
}
| null | null | 200,032
|
110126115483762895567445864042748786778
| 315
|
Fix bug #70385 (Buffer over-read in exif_read_data with TIFF IFD tag byte value of 32 bytes)
|
other
|
ImageMagick
|
389ecc365a7c61404ba078a72c3fa5a3cf1b4101
| 1
|
static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
typedef struct {
unsigned char Type[4];
unsigned int nRows;
unsigned int nCols;
unsigned int imagf;
unsigned int nameLen;
} MAT4_HDR;
long
ldblk;
EndianType
endian;
Image
*rotated_image;
MagickBooleanType
status;
MAT4_HDR
HDR;
QuantumInfo
*quantum_info;
QuantumFormatType
format_type;
register ssize_t
i;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned int
depth;
quantum_info=(QuantumInfo *) NULL;
(void) SeekBlob(image,0,SEEK_SET);
while (EOFBlob(image) == MagickFalse)
{
/*
Object parser loop.
*/
ldblk=ReadBlobLSBLong(image);
if ((ldblk > 9999) || (ldblk < 0))
break;
HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */
HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */
HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */
HDR.Type[0]=ldblk; /* M digit */
if (HDR.Type[3] != 0)
break; /* Data format */
if (HDR.Type[2] != 0)
break; /* Always 0 */
if (HDR.Type[0] == 0)
{
HDR.nRows=ReadBlobLSBLong(image);
HDR.nCols=ReadBlobLSBLong(image);
HDR.imagf=ReadBlobLSBLong(image);
HDR.nameLen=ReadBlobLSBLong(image);
endian=LSBEndian;
}
else
{
HDR.nRows=ReadBlobMSBLong(image);
HDR.nCols=ReadBlobMSBLong(image);
HDR.imagf=ReadBlobMSBLong(image);
HDR.nameLen=ReadBlobMSBLong(image);
endian=MSBEndian;
}
if ((HDR.imagf != 0) && (HDR.imagf != 1))
break;
if (HDR.nameLen > 0xFFFF)
return(DestroyImageList(image));
for (i=0; i < (ssize_t) HDR.nameLen; i++)
{
int
byte;
/*
Skip matrix name.
*/
byte=ReadBlobByte(image);
if (byte == EOF)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
image->columns=(size_t) HDR.nRows;
image->rows=(size_t) HDR.nCols;
if ((image->columns == 0) || (image->rows == 0))
return(DestroyImageList(image));
if (image_info->ping != MagickFalse)
{
Swap(image->columns,image->rows);
if(HDR.imagf==1) ldblk *= 2;
SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);
if ((image->columns == 0) || (image->rows == 0))
return(image->previous == (Image *) NULL ? DestroyImageList(image)
: image);
goto skip_reading_current;
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(DestroyImageList(image));
switch(HDR.Type[1])
{
case 0:
format_type=FloatingPointQuantumFormat;
depth=64;
break;
case 1:
format_type=FloatingPointQuantumFormat;
depth=32;
break;
case 2:
format_type=UnsignedQuantumFormat;
depth=16;
break;
case 3:
format_type=SignedQuantumFormat;
depth=16;
break;
case 4:
format_type=UnsignedQuantumFormat;
depth=8;
break;
default:
format_type=UnsignedQuantumFormat;
depth=8;
break;
}
image->depth=depth;
if (HDR.Type[0] != 0)
SetQuantumEndian(image,quantum_info,MSBEndian);
status=SetQuantumFormat(image,quantum_info,format_type);
status=SetQuantumDepth(image,quantum_info,depth);
status=SetQuantumEndian(image,quantum_info,endian);
SetQuantumScale(quantum_info,1.0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
if (count == -1)
break;
q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))
FixSignedValues(image,q,(int) image->columns);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (HDR.imagf == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
/*
Read complex pixels.
*/
count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
if (count == -1)
break;
if (HDR.Type[1] == 0)
InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);
else
InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
rotated_image=RotateImage(image,90.0,exception);
if (rotated_image != (Image *) NULL)
{
rotated_image->page.x=0;
rotated_image->page.y=0;
rotated_image->colors = image->colors;
DestroyBlob(rotated_image);
rotated_image->blob=ReferenceBlob(image->blob);
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Allocate next image structure.
*/
skip_reading_current:
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
| null | null | 200,113
|
138685852020641925694268423284225156115
| 243
|
https://github.com/ImageMagick/ImageMagick/issues/1221
|
other
|
exim
|
e2f5dc151e2e79058e93924e6d35510557f0535d
| 1
|
readconf_main(void)
{
int sep = 0;
struct stat statbuf;
uschar *s, *filename;
uschar *list = config_main_filelist;
/* Loop through the possible file names */
while((filename = string_nextinlist(&list, &sep, big_buffer, big_buffer_size))
!= NULL)
{
/* Cut out all the fancy processing unless specifically wanted */
#if defined(CONFIGURE_FILE_USE_NODE) || defined(CONFIGURE_FILE_USE_EUID)
uschar *suffix = filename + Ustrlen(filename);
/* Try for the node-specific file if a node name exists */
#ifdef CONFIGURE_FILE_USE_NODE
struct utsname uts;
if (uname(&uts) >= 0)
{
#ifdef CONFIGURE_FILE_USE_EUID
sprintf(CS suffix, ".%ld.%.256s", (long int)original_euid, uts.nodename);
config_file = Ufopen(filename, "rb");
if (config_file == NULL)
#endif /* CONFIGURE_FILE_USE_EUID */
{
sprintf(CS suffix, ".%.256s", uts.nodename);
config_file = Ufopen(filename, "rb");
}
}
#endif /* CONFIGURE_FILE_USE_NODE */
/* Otherwise, try the generic name, possibly with the euid added */
#ifdef CONFIGURE_FILE_USE_EUID
if (config_file == NULL)
{
sprintf(CS suffix, ".%ld", (long int)original_euid);
config_file = Ufopen(filename, "rb");
}
#endif /* CONFIGURE_FILE_USE_EUID */
/* Finally, try the unadorned name */
if (config_file == NULL)
{
*suffix = 0;
config_file = Ufopen(filename, "rb");
}
#else /* if neither defined */
/* This is the common case when the fancy processing is not included. */
config_file = Ufopen(filename, "rb");
#endif
/* If the file does not exist, continue to try any others. For any other
error, break out (and die). */
if (config_file != NULL || errno != ENOENT) break;
}
/* On success, save the name for verification; config_filename is used when
logging configuration errors (it changes for .included files) whereas
config_main_filename is the name shown by -bP. Failure to open a configuration
file is a serious disaster. */
if (config_file != NULL)
{
config_filename = config_main_filename = string_copy(filename);
}
else
{
if (filename == NULL)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "non-existent configuration file(s): "
"%s", config_main_filelist);
else
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "%s", string_open_failed(errno,
"configuration file %s", filename));
}
/* Check the status of the file we have opened, unless it was specified on
the command line, in which case privilege was given away at the start. */
if (!config_changed)
{
if (fstat(fileno(config_file), &statbuf) != 0)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to stat configuration file %s",
big_buffer);
if ((statbuf.st_uid != root_uid /* owner not root */
#ifdef CONFIGURE_OWNER
&& statbuf.st_uid != config_uid /* owner not the special one */
#endif
) || /* or */
(statbuf.st_gid != root_gid /* group not root & */
#ifdef CONFIGURE_GROUP
&& statbuf.st_gid != config_gid /* group not the special one */
#endif
&& (statbuf.st_mode & 020) != 0) || /* group writeable */
/* or */
((statbuf.st_mode & 2) != 0)) /* world writeable */
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Exim configuration file %s has the "
"wrong owner, group, or mode", big_buffer);
}
/* Process the main configuration settings. They all begin with a lower case
letter. If we see something starting with an upper case letter, it is taken as
a macro definition. */
while ((s = get_config_line()) != NULL)
{
if (isupper(s[0])) read_macro_assignment(s);
else if (Ustrncmp(s, "domainlist", 10) == 0)
read_named_list(&domainlist_anchor, &domainlist_count,
MAX_NAMED_LIST, s+10, US"domain list");
else if (Ustrncmp(s, "hostlist", 8) == 0)
read_named_list(&hostlist_anchor, &hostlist_count,
MAX_NAMED_LIST, s+8, US"host list");
else if (Ustrncmp(s, US"addresslist", 11) == 0)
read_named_list(&addresslist_anchor, &addresslist_count,
MAX_NAMED_LIST, s+11, US"address list");
else if (Ustrncmp(s, US"localpartlist", 13) == 0)
read_named_list(&localpartlist_anchor, &localpartlist_count,
MAX_NAMED_LIST, s+13, US"local part list");
else
(void) readconf_handle_option(s, optionlist_config, optionlist_config_size,
NULL, US"main option \"%s\" unknown");
}
/* If local_sender_retain is set, local_from_check must be unset. */
if (local_sender_retain && local_from_check)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "both local_from_check and "
"local_sender_retain are set; this combination is not allowed");
/* If the timezone string is empty, set it to NULL, implying no TZ variable
wanted. */
if (timezone_string != NULL && *timezone_string == 0) timezone_string = NULL;
/* The max retry interval must not be greater than 24 hours. */
if (retry_interval_max > 24*60*60) retry_interval_max = 24*60*60;
/* remote_max_parallel must be > 0 */
if (remote_max_parallel <= 0) remote_max_parallel = 1;
/* Save the configured setting of freeze_tell, so we can re-instate it at the
start of a new SMTP message. */
freeze_tell_config = freeze_tell;
/* The primary host name may be required for expansion of spool_directory
and log_file_path, so make sure it is set asap. It is obtained from uname(),
but if that yields an unqualified value, make a FQDN by using gethostbyname to
canonize it. Some people like upper case letters in their host names, so we
don't force the case. */
if (primary_hostname == NULL)
{
uschar *hostname;
struct utsname uts;
if (uname(&uts) < 0)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "uname() failed to yield host name");
hostname = US uts.nodename;
if (Ustrchr(hostname, '.') == NULL)
{
int af = AF_INET;
struct hostent *hostdata;
#if HAVE_IPV6
if (!disable_ipv6 && (dns_ipv4_lookup == NULL ||
match_isinlist(hostname, &dns_ipv4_lookup, 0, NULL, NULL, MCL_DOMAIN,
TRUE, NULL) != OK))
af = AF_INET6;
#else
af = AF_INET;
#endif
for (;;)
{
#if HAVE_IPV6
#if HAVE_GETIPNODEBYNAME
int error_num;
hostdata = getipnodebyname(CS hostname, af, 0, &error_num);
#else
hostdata = gethostbyname2(CS hostname, af);
#endif
#else
hostdata = gethostbyname(CS hostname);
#endif
if (hostdata != NULL)
{
hostname = US hostdata->h_name;
break;
}
if (af == AF_INET) break;
af = AF_INET;
}
}
primary_hostname = string_copy(hostname);
}
/* Set up default value for smtp_active_hostname */
smtp_active_hostname = primary_hostname;
/* If spool_directory wasn't set in the build-time configuration, it must have
got set above. Of course, writing to the log may not work if log_file_path is
not set, but it will at least get to syslog or somewhere, with any luck. */
if (*spool_directory == 0)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "spool_directory undefined: cannot "
"proceed");
/* Expand the spool directory name; it may, for example, contain the primary
host name. Same comment about failure. */
s = expand_string(spool_directory);
if (s == NULL)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand spool_directory "
"\"%s\": %s", spool_directory, expand_string_message);
spool_directory = s;
/* Expand log_file_path, which must contain "%s" in any component that isn't
the null string or "syslog". It is also allowed to contain one instance of %D.
However, it must NOT contain % followed by anything else. */
if (*log_file_path != 0)
{
uschar *ss, *sss;
int sep = ':'; /* Fixed for log file path */
s = expand_string(log_file_path);
if (s == NULL)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand log_file_path "
"\"%s\": %s", log_file_path, expand_string_message);
ss = s;
while ((sss = string_nextinlist(&ss,&sep,big_buffer,big_buffer_size)) != NULL)
{
uschar *t;
if (sss[0] == 0 || Ustrcmp(sss, "syslog") == 0) continue;
t = Ustrstr(sss, "%s");
if (t == NULL)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" does not "
"contain \"%%s\"", sss);
*t = 'X';
t = Ustrchr(sss, '%');
if (t != NULL)
{
if (t[1] != 'D' || Ustrchr(t+2, '%') != NULL)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "log_file_path \"%s\" contains "
"unexpected \"%%\" character", s);
}
}
log_file_path = s;
}
/* Interpret syslog_facility into an integer argument for 'ident' param to
openlog(). Default is LOG_MAIL set in globals.c. Allow the user to omit the
leading "log_". */
if (syslog_facility_str != NULL)
{
int i;
uschar *s = syslog_facility_str;
if ((Ustrlen(syslog_facility_str) >= 4) &&
(strncmpic(syslog_facility_str, US"log_", 4) == 0))
s += 4;
for (i = 0; i < syslog_list_size; i++)
{
if (strcmpic(s, syslog_list[i].name) == 0)
{
syslog_facility = syslog_list[i].value;
break;
}
}
if (i >= syslog_list_size)
{
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"failed to interpret syslog_facility \"%s\"", syslog_facility_str);
}
}
/* Expand pid_file_path */
if (*pid_file_path != 0)
{
s = expand_string(pid_file_path);
if (s == NULL)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "failed to expand pid_file_path "
"\"%s\": %s", pid_file_path, expand_string_message);
pid_file_path = s;
}
/* Compile the regex for matching a UUCP-style "From_" line in an incoming
message. */
regex_From = regex_must_compile(uucp_from_pattern, FALSE, TRUE);
/* Unpick the SMTP rate limiting options, if set */
if (smtp_ratelimit_mail != NULL)
{
unpick_ratelimit(smtp_ratelimit_mail, &smtp_rlm_threshold,
&smtp_rlm_base, &smtp_rlm_factor, &smtp_rlm_limit);
}
if (smtp_ratelimit_rcpt != NULL)
{
unpick_ratelimit(smtp_ratelimit_rcpt, &smtp_rlr_threshold,
&smtp_rlr_base, &smtp_rlr_factor, &smtp_rlr_limit);
}
/* The qualify domains default to the primary host name */
if (qualify_domain_sender == NULL)
qualify_domain_sender = primary_hostname;
if (qualify_domain_recipient == NULL)
qualify_domain_recipient = qualify_domain_sender;
/* Setting system_filter_user in the configuration sets the gid as well if a
name is given, but a numerical value does not. */
if (system_filter_uid_set && !system_filter_gid_set)
{
struct passwd *pw = getpwuid(system_filter_uid);
if (pw == NULL)
log_write(0, LOG_MAIN|LOG_PANIC_DIE, "Failed to look up uid %ld",
(long int)system_filter_uid);
system_filter_gid = pw->pw_gid;
system_filter_gid_set = TRUE;
}
/* If the errors_reply_to field is set, check that it is syntactically valid
and ensure it contains a domain. */
if (errors_reply_to != NULL)
{
uschar *errmess;
int start, end, domain;
uschar *recipient = parse_extract_address(errors_reply_to, &errmess,
&start, &end, &domain, FALSE);
if (recipient == NULL)
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"error in errors_reply_to (%s): %s", errors_reply_to, errmess);
if (domain == 0)
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"errors_reply_to (%s) does not contain a domain", errors_reply_to);
}
/* If smtp_accept_queue or smtp_accept_max_per_host is set, then
smtp_accept_max must also be set. */
if (smtp_accept_max == 0 &&
(smtp_accept_queue > 0 || smtp_accept_max_per_host != NULL))
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"smtp_accept_max must be set if smtp_accept_queue or "
"smtp_accept_max_per_host is set");
/* Set up the host number if anything is specified. It is an expanded string
so that it can be computed from the host name, for example. We do this last
so as to ensure that everything else is set up before the expansion. */
if (host_number_string != NULL)
{
uschar *end;
uschar *s = expand_string(host_number_string);
long int n = Ustrtol(s, &end, 0);
while (isspace(*end)) end++;
if (*end != 0)
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"localhost_number value is not a number: %s", s);
if (n > LOCALHOST_MAX)
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"localhost_number is greater than the maximum allowed value (%d)",
LOCALHOST_MAX);
host_number = n;
}
#ifdef SUPPORT_TLS
/* If tls_verify_hosts is set, tls_verify_certificates must also be set */
if ((tls_verify_hosts != NULL || tls_try_verify_hosts != NULL) &&
tls_verify_certificates == NULL)
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"tls_%sverify_hosts is set, but tls_verify_certificates is not set",
(tls_verify_hosts != NULL)? "" : "try_");
/* If openssl_options is set, validate it */
if (openssl_options != NULL)
{
# ifdef USE_GNUTLS
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"openssl_options is set but we're using GnuTLS");
# else
long dummy;
if (!(tls_openssl_options_parse(openssl_options, &dummy)))
log_write(0, LOG_PANIC_DIE|LOG_CONFIG,
"openssl_options parse error: %s", openssl_options);
# endif
}
#endif
}
| null | null | 200,157
|
27874412724630776189410611026623848083
| 426
|
Check configure file permissions even for non-default files if still privileged
(Bug 1044, CVE-2010-4345)
|
other
|
linux
|
817b8b9c5396d2b2d92311b46719aad5d3339dbe
| 1
|
static int elo_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
struct elo_priv *priv;
int ret;
struct usb_device *udev;
if (!hid_is_usb(hdev))
return -EINVAL;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
INIT_DELAYED_WORK(&priv->work, elo_work);
udev = interface_to_usbdev(to_usb_interface(hdev->dev.parent));
priv->usbdev = usb_get_dev(udev);
hid_set_drvdata(hdev, priv);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
goto err_free;
}
ret = hid_hw_start(hdev, HID_CONNECT_DEFAULT);
if (ret) {
hid_err(hdev, "hw start failed\n");
goto err_free;
}
if (elo_broken_firmware(priv->usbdev)) {
hid_info(hdev, "broken firmware found, installing workaround\n");
queue_delayed_work(wq, &priv->work, ELO_PERIODIC_READ_INTERVAL);
}
return 0;
err_free:
kfree(priv);
return ret;
}
| null | null | 200,163
|
47515603588365829983297433294206664196
| 41
|
HID: elo: fix memory leak in elo_probe
When hid_parse() in elo_probe() fails, it forgets to call usb_put_dev to
decrease the refcount.
Fix this by adding usb_put_dev() in the error handling code of elo_probe().
Fixes: fbf42729d0e9 ("HID: elo: update the reference count of the usb device structure")
Reported-by: syzkaller <[email protected]>
Signed-off-by: Dongliang Mu <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
|
other
|
linux
|
d6d86830705f173fca6087a3e67ceaf68db80523
| 1
|
static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct tipc_sock *tsk = tipc_sk(sk);
struct tipc_uaddr *ua = (struct tipc_uaddr *)m->msg_name;
long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
struct list_head *clinks = &tsk->cong_links;
bool syn = !tipc_sk_type_connectionless(sk);
struct tipc_group *grp = tsk->group;
struct tipc_msg *hdr = &tsk->phdr;
struct tipc_socket_addr skaddr;
struct sk_buff_head pkts;
int atype, mtu, rc;
if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))
return -EMSGSIZE;
if (ua) {
if (!tipc_uaddr_valid(ua, m->msg_namelen))
return -EINVAL;
atype = ua->addrtype;
}
/* If socket belongs to a communication group follow other paths */
if (grp) {
if (!ua)
return tipc_send_group_bcast(sock, m, dlen, timeout);
if (atype == TIPC_SERVICE_ADDR)
return tipc_send_group_anycast(sock, m, dlen, timeout);
if (atype == TIPC_SOCKET_ADDR)
return tipc_send_group_unicast(sock, m, dlen, timeout);
if (atype == TIPC_SERVICE_RANGE)
return tipc_send_group_mcast(sock, m, dlen, timeout);
return -EINVAL;
}
if (!ua) {
ua = (struct tipc_uaddr *)&tsk->peer;
if (!syn && ua->family != AF_TIPC)
return -EDESTADDRREQ;
atype = ua->addrtype;
}
if (unlikely(syn)) {
if (sk->sk_state == TIPC_LISTEN)
return -EPIPE;
if (sk->sk_state != TIPC_OPEN)
return -EISCONN;
if (tsk->published)
return -EOPNOTSUPP;
if (atype == TIPC_SERVICE_ADDR)
tsk->conn_addrtype = atype;
msg_set_syn(hdr, 1);
}
/* Determine destination */
if (atype == TIPC_SERVICE_RANGE) {
return tipc_sendmcast(sock, ua, m, dlen, timeout);
} else if (atype == TIPC_SERVICE_ADDR) {
skaddr.node = ua->lookup_node;
ua->scope = tipc_node2scope(skaddr.node);
if (!tipc_nametbl_lookup_anycast(net, ua, &skaddr))
return -EHOSTUNREACH;
} else if (atype == TIPC_SOCKET_ADDR) {
skaddr = ua->sk;
} else {
return -EINVAL;
}
/* Block or return if destination link is congested */
rc = tipc_wait_for_cond(sock, &timeout,
!tipc_dest_find(clinks, skaddr.node, 0));
if (unlikely(rc))
return rc;
/* Finally build message header */
msg_set_destnode(hdr, skaddr.node);
msg_set_destport(hdr, skaddr.ref);
if (atype == TIPC_SERVICE_ADDR) {
msg_set_type(hdr, TIPC_NAMED_MSG);
msg_set_hdr_sz(hdr, NAMED_H_SIZE);
msg_set_nametype(hdr, ua->sa.type);
msg_set_nameinst(hdr, ua->sa.instance);
msg_set_lookup_scope(hdr, ua->scope);
} else { /* TIPC_SOCKET_ADDR */
msg_set_type(hdr, TIPC_DIRECT_MSG);
msg_set_lookup_scope(hdr, 0);
msg_set_hdr_sz(hdr, BASIC_H_SIZE);
}
/* Add message body */
__skb_queue_head_init(&pkts);
mtu = tipc_node_get_mtu(net, skaddr.node, tsk->portid, true);
rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
if (unlikely(rc != dlen))
return rc;
if (unlikely(syn && !tipc_msg_skb_clone(&pkts, &sk->sk_write_queue))) {
__skb_queue_purge(&pkts);
return -ENOMEM;
}
/* Send message */
trace_tipc_sk_sendmsg(sk, skb_peek(&pkts), TIPC_DUMP_SK_SNDQ, " ");
rc = tipc_node_xmit(net, &pkts, skaddr.node, tsk->portid);
if (unlikely(rc == -ELINKCONG)) {
tipc_dest_push(clinks, skaddr.node, 0);
tsk->cong_link_cnt++;
rc = 0;
}
if (unlikely(syn && !rc)) {
tipc_set_sk_state(sk, TIPC_CONNECTING);
if (dlen && timeout) {
timeout = msecs_to_jiffies(timeout);
tipc_wait_for_connect(sock, &timeout);
}
}
return rc ? rc : dlen;
}
| null | null | 200,287
|
311647954081435231040346755089215787774
| 121
|
net ticp:fix a kernel-infoleak in __tipc_sendmsg()
struct tipc_socket_addr.ref has a 4-byte hole,and __tipc_getname() currently
copying it to user space,causing kernel-infoleak.
BUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline]
BUG: KMSAN: kernel-infoleak in instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33
BUG: KMSAN: kernel-infoleak in _copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33
instrument_copy_to_user include/linux/instrumented.h:121 [inline]
instrument_copy_to_user include/linux/instrumented.h:121 [inline] lib/usercopy.c:33
_copy_to_user+0x1c9/0x270 lib/usercopy.c:33 lib/usercopy.c:33
copy_to_user include/linux/uaccess.h:209 [inline]
copy_to_user include/linux/uaccess.h:209 [inline] net/socket.c:287
move_addr_to_user+0x3f6/0x600 net/socket.c:287 net/socket.c:287
__sys_getpeername+0x470/0x6b0 net/socket.c:1987 net/socket.c:1987
__do_sys_getpeername net/socket.c:1997 [inline]
__se_sys_getpeername net/socket.c:1994 [inline]
__do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994
__se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994
__x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994
do_syscall_x64 arch/x86/entry/common.c:51 [inline]
do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82
do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82
entry_SYSCALL_64_after_hwframe+0x44/0xae
Uninit was stored to memory at:
tipc_getname+0x575/0x5e0 net/tipc/socket.c:757 net/tipc/socket.c:757
__sys_getpeername+0x3b3/0x6b0 net/socket.c:1984 net/socket.c:1984
__do_sys_getpeername net/socket.c:1997 [inline]
__se_sys_getpeername net/socket.c:1994 [inline]
__do_sys_getpeername net/socket.c:1997 [inline] net/socket.c:1994
__se_sys_getpeername net/socket.c:1994 [inline] net/socket.c:1994
__x64_sys_getpeername+0xda/0x120 net/socket.c:1994 net/socket.c:1994
do_syscall_x64 arch/x86/entry/common.c:51 [inline]
do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82
do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82
entry_SYSCALL_64_after_hwframe+0x44/0xae
Uninit was stored to memory at:
msg_set_word net/tipc/msg.h:212 [inline]
msg_set_destport net/tipc/msg.h:619 [inline]
msg_set_word net/tipc/msg.h:212 [inline] net/tipc/socket.c:1486
msg_set_destport net/tipc/msg.h:619 [inline] net/tipc/socket.c:1486
__tipc_sendmsg+0x44fa/0x5890 net/tipc/socket.c:1486 net/tipc/socket.c:1486
tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402
sock_sendmsg_nosec net/socket.c:704 [inline]
sock_sendmsg net/socket.c:724 [inline]
sock_sendmsg_nosec net/socket.c:704 [inline] net/socket.c:2409
sock_sendmsg net/socket.c:724 [inline] net/socket.c:2409
____sys_sendmsg+0xe11/0x12c0 net/socket.c:2409 net/socket.c:2409
___sys_sendmsg net/socket.c:2463 [inline]
___sys_sendmsg net/socket.c:2463 [inline] net/socket.c:2492
__sys_sendmsg+0x704/0x840 net/socket.c:2492 net/socket.c:2492
__do_sys_sendmsg net/socket.c:2501 [inline]
__se_sys_sendmsg net/socket.c:2499 [inline]
__do_sys_sendmsg net/socket.c:2501 [inline] net/socket.c:2499
__se_sys_sendmsg net/socket.c:2499 [inline] net/socket.c:2499
__x64_sys_sendmsg+0xe2/0x120 net/socket.c:2499 net/socket.c:2499
do_syscall_x64 arch/x86/entry/common.c:51 [inline]
do_syscall_x64 arch/x86/entry/common.c:51 [inline] arch/x86/entry/common.c:82
do_syscall_64+0x54/0xd0 arch/x86/entry/common.c:82 arch/x86/entry/common.c:82
entry_SYSCALL_64_after_hwframe+0x44/0xae
Local variable skaddr created at:
__tipc_sendmsg+0x2d0/0x5890 net/tipc/socket.c:1419 net/tipc/socket.c:1419
tipc_sendmsg+0xeb/0x140 net/tipc/socket.c:1402 net/tipc/socket.c:1402
Bytes 4-7 of 16 are uninitialized
Memory access of size 16 starts at ffff888113753e00
Data copied to user address 0000000020000280
Reported-by: [email protected]
Signed-off-by: Haimin Zhang <[email protected]>
Acked-by: Jon Maloy <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
|
other
|
ghostpdl
|
2793769ff107d8d22dadd30c6e68cd781b569550
| 1
|
pcx_write_rle(const byte * from, const byte * end, int step, gp_file * file)
{ /*
* The PCX format theoretically allows encoding runs of 63
* identical bytes, but some readers can't handle repetition
* counts greater than 15.
*/
#define MAX_RUN_COUNT 15
int max_run = step * MAX_RUN_COUNT;
while (from < end) {
byte data = *from;
from += step;
if (data != *from || from == end) {
if (data >= 0xc0)
gp_fputc(0xc1, file);
} else {
const byte *start = from;
while ((from < end) && (*from == data))
from += step;
/* Now (from - start) / step + 1 is the run length. */
while (from - start >= max_run) {
gp_fputc(0xc0 + MAX_RUN_COUNT, file);
gp_fputc(data, file);
start += max_run;
}
if (from > start || data >= 0xc0)
gp_fputc((from - start) / step + 0xc1, file);
}
gp_fputc(data, file);
}
#undef MAX_RUN_COUNT
}
| null | null | 200,305
|
324934897993024038995397206037026582626
| 34
|
Bug 701819: fixed ordering in if expression to avoid out-of-bounds access.
Fixes:
./sanbin/gs -dBATCH -dNOPAUSE -r965 -sOutputFile=tmp -sDEVICE=pcx16 ../bug-701819.pdf
|
other
|
samba
|
eb50fb8f3bf670bd7d1cf8fd4368ef4a73083696
| 1
|
static NTSTATUS vfswrap_fsctl(struct vfs_handle_struct *handle,
struct files_struct *fsp,
TALLOC_CTX *ctx,
uint32_t function,
uint16_t req_flags, /* Needed for UNICODE ... */
const uint8_t *_in_data,
uint32_t in_len,
uint8_t **_out_data,
uint32_t max_out_len,
uint32_t *out_len)
{
const char *in_data = (const char *)_in_data;
char **out_data = (char **)_out_data;
switch (function) {
case FSCTL_SET_SPARSE:
{
bool set_sparse = true;
NTSTATUS status;
if (in_len >= 1 && in_data[0] == 0) {
set_sparse = false;
}
status = file_set_sparse(handle->conn, fsp, set_sparse);
DEBUG(NT_STATUS_IS_OK(status) ? 10 : 9,
("FSCTL_SET_SPARSE: fname[%s] set[%u] - %s\n",
smb_fname_str_dbg(fsp->fsp_name), set_sparse,
nt_errstr(status)));
return status;
}
case FSCTL_CREATE_OR_GET_OBJECT_ID:
{
unsigned char objid[16];
char *return_data = NULL;
/* This should return the object-id on this file.
* I think I'll make this be the inode+dev. JRA.
*/
DEBUG(10,("FSCTL_CREATE_OR_GET_OBJECT_ID: called on %s\n",
fsp_fnum_dbg(fsp)));
*out_len = (max_out_len >= 64) ? 64 : max_out_len;
/* Hmmm, will this cause problems if less data asked for? */
return_data = talloc_array(ctx, char, 64);
if (return_data == NULL) {
return NT_STATUS_NO_MEMORY;
}
/* For backwards compatibility only store the dev/inode. */
push_file_id_16(return_data, &fsp->file_id);
memcpy(return_data+16,create_volume_objectid(fsp->conn,objid),16);
push_file_id_16(return_data+32, &fsp->file_id);
*out_data = return_data;
return NT_STATUS_OK;
}
case FSCTL_GET_REPARSE_POINT:
{
/* Fail it with STATUS_NOT_A_REPARSE_POINT */
DEBUG(10, ("FSCTL_GET_REPARSE_POINT: called on %s. "
"Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp)));
return NT_STATUS_NOT_A_REPARSE_POINT;
}
case FSCTL_SET_REPARSE_POINT:
{
/* Fail it with STATUS_NOT_A_REPARSE_POINT */
DEBUG(10, ("FSCTL_SET_REPARSE_POINT: called on %s. "
"Status: NOT_IMPLEMENTED\n", fsp_fnum_dbg(fsp)));
return NT_STATUS_NOT_A_REPARSE_POINT;
}
case FSCTL_GET_SHADOW_COPY_DATA:
{
/*
* This is called to retrieve the number of Shadow Copies (a.k.a. snapshots)
* and return their volume names. If max_data_count is 16, then it is just
* asking for the number of volumes and length of the combined names.
*
* pdata is the data allocated by our caller, but that uses
* total_data_count (which is 0 in our case) rather than max_data_count.
* Allocate the correct amount and return the pointer to let
* it be deallocated when we return.
*/
struct shadow_copy_data *shadow_data = NULL;
bool labels = False;
uint32 labels_data_count = 0;
uint32 i;
char *cur_pdata = NULL;
if (max_out_len < 16) {
DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) < 16 is invalid!\n",
max_out_len));
return NT_STATUS_INVALID_PARAMETER;
}
if (max_out_len > 16) {
labels = True;
}
shadow_data = talloc_zero(ctx, struct shadow_copy_data);
if (shadow_data == NULL) {
DEBUG(0,("TALLOC_ZERO() failed!\n"));
return NT_STATUS_NO_MEMORY;
}
/*
* Call the VFS routine to actually do the work.
*/
if (SMB_VFS_GET_SHADOW_COPY_DATA(fsp, shadow_data, labels)!=0) {
TALLOC_FREE(shadow_data);
if (errno == ENOSYS) {
DEBUG(5,("FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, not supported.\n",
fsp->conn->connectpath));
return NT_STATUS_NOT_SUPPORTED;
} else {
DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: connectpath %s, failed.\n",
fsp->conn->connectpath));
return NT_STATUS_UNSUCCESSFUL;
}
}
labels_data_count = (shadow_data->num_volumes * 2 *
sizeof(SHADOW_COPY_LABEL)) + 2;
if (!labels) {
*out_len = 16;
} else {
*out_len = 12 + labels_data_count + 4;
}
if (max_out_len < *out_len) {
DEBUG(0,("FSCTL_GET_SHADOW_COPY_DATA: max_data_count(%u) too small (%u) bytes needed!\n",
max_out_len, *out_len));
TALLOC_FREE(shadow_data);
return NT_STATUS_BUFFER_TOO_SMALL;
}
cur_pdata = talloc_zero_array(ctx, char, *out_len);
if (cur_pdata == NULL) {
TALLOC_FREE(shadow_data);
return NT_STATUS_NO_MEMORY;
}
*out_data = cur_pdata;
/* num_volumes 4 bytes */
SIVAL(cur_pdata, 0, shadow_data->num_volumes);
if (labels) {
/* num_labels 4 bytes */
SIVAL(cur_pdata, 4, shadow_data->num_volumes);
}
/* needed_data_count 4 bytes */
SIVAL(cur_pdata, 8, labels_data_count + 4);
cur_pdata += 12;
DEBUG(10,("FSCTL_GET_SHADOW_COPY_DATA: %u volumes for path[%s].\n",
shadow_data->num_volumes, fsp_str_dbg(fsp)));
if (labels && shadow_data->labels) {
for (i=0; i<shadow_data->num_volumes; i++) {
srvstr_push(cur_pdata, req_flags,
cur_pdata, shadow_data->labels[i],
2 * sizeof(SHADOW_COPY_LABEL),
STR_UNICODE|STR_TERMINATE);
cur_pdata += 2 * sizeof(SHADOW_COPY_LABEL);
DEBUGADD(10,("Label[%u]: '%s'\n",i,shadow_data->labels[i]));
}
}
TALLOC_FREE(shadow_data);
return NT_STATUS_OK;
}
case FSCTL_FIND_FILES_BY_SID:
{
/* pretend this succeeded -
*
* we have to send back a list with all files owned by this SID
*
* but I have to check that --metze
*/
struct dom_sid sid;
uid_t uid;
size_t sid_len;
DEBUG(10, ("FSCTL_FIND_FILES_BY_SID: called on %s\n",
fsp_fnum_dbg(fsp)));
if (in_len < 8) {
/* NT_STATUS_BUFFER_TOO_SMALL maybe? */
return NT_STATUS_INVALID_PARAMETER;
}
sid_len = MIN(in_len - 4,SID_MAX_SIZE);
/* unknown 4 bytes: this is not the length of the sid :-( */
/*unknown = IVAL(pdata,0);*/
if (!sid_parse(in_data + 4, sid_len, &sid)) {
return NT_STATUS_INVALID_PARAMETER;
}
DEBUGADD(10, ("for SID: %s\n", sid_string_dbg(&sid)));
if (!sid_to_uid(&sid, &uid)) {
DEBUG(0,("sid_to_uid: failed, sid[%s] sid_len[%lu]\n",
sid_string_dbg(&sid),
(unsigned long)sid_len));
uid = (-1);
}
/* we can take a look at the find source :-)
*
* find ./ -uid $uid -name '*' is what we need here
*
*
* and send 4bytes len and then NULL terminated unicode strings
* for each file
*
* but I don't know how to deal with the paged results
* (maybe we can hang the result anywhere in the fsp struct)
*
* but I don't know how to deal with the paged results
* (maybe we can hang the result anywhere in the fsp struct)
*
* we don't send all files at once
* and at the next we should *not* start from the beginning,
* so we have to cache the result
*
* --metze
*/
/* this works for now... */
return NT_STATUS_OK;
}
case FSCTL_QUERY_ALLOCATED_RANGES:
{
/* FIXME: This is just a dummy reply, telling that all of the
* file is allocated. MKS cp needs that.
* Adding the real allocated ranges via FIEMAP on Linux
* and SEEK_DATA/SEEK_HOLE on Solaris is needed to make
* this FSCTL correct for sparse files.
*/
NTSTATUS status;
uint64_t offset, length;
char *out_data_tmp = NULL;
if (in_len != 16) {
DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: data_count(%u) != 16 is invalid!\n",
in_len));
return NT_STATUS_INVALID_PARAMETER;
}
if (max_out_len < 16) {
DEBUG(0,("FSCTL_QUERY_ALLOCATED_RANGES: max_out_len (%u) < 16 is invalid!\n",
max_out_len));
return NT_STATUS_INVALID_PARAMETER;
}
offset = BVAL(in_data,0);
length = BVAL(in_data,8);
if (offset + length < offset) {
/* No 64-bit integer wrap. */
return NT_STATUS_INVALID_PARAMETER;
}
/* Shouldn't this be SMB_VFS_STAT ... ? */
status = vfs_stat_fsp(fsp);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
*out_len = 16;
out_data_tmp = talloc_array(ctx, char, *out_len);
if (out_data_tmp == NULL) {
DEBUG(10, ("unable to allocate memory for response\n"));
return NT_STATUS_NO_MEMORY;
}
if (offset > fsp->fsp_name->st.st_ex_size ||
fsp->fsp_name->st.st_ex_size == 0 ||
length == 0) {
memset(out_data_tmp, 0, *out_len);
} else {
uint64_t end = offset + length;
end = MIN(end, fsp->fsp_name->st.st_ex_size);
SBVAL(out_data_tmp, 0, 0);
SBVAL(out_data_tmp, 8, end);
}
*out_data = out_data_tmp;
return NT_STATUS_OK;
}
case FSCTL_IS_VOLUME_DIRTY:
{
DEBUG(10,("FSCTL_IS_VOLUME_DIRTY: called on %s "
"(but remotely not supported)\n", fsp_fnum_dbg(fsp)));
/*
* http://msdn.microsoft.com/en-us/library/cc232128%28PROT.10%29.aspx
* says we have to respond with NT_STATUS_INVALID_PARAMETER
*/
return NT_STATUS_INVALID_PARAMETER;
}
default:
/*
* Only print once ... unfortunately there could be lots of
* different FSCTLs that are called.
*/
if (!vfswrap_logged_ioctl_message) {
vfswrap_logged_ioctl_message = true;
DEBUG(2, ("%s (0x%x): Currently not implemented.\n",
__func__, function));
}
}
return NT_STATUS_NOT_SUPPORTED;
}
| null | null | 200,320
|
36864430679636639714404842179779335208
| 330
|
FSCTL_GET_SHADOW_COPY_DATA: Don't return 4 extra bytes at end
labels_data_count already accounts for the unicode null character at the
end of the array. There is no need in adding space for it again.
Signed-off-by: Christof Schmitt <[email protected]>
Reviewed-by: Jeremy Allison <[email protected]>
Reviewed-by: Simo Sorce <[email protected]>
Autobuild-User(master): Jeremy Allison <[email protected]>
Autobuild-Date(master): Tue Aug 6 04:03:17 CEST 2013 on sn-devel-104
|
other
|
vim
|
156d3911952d73b03d7420dc3540215247db0fe8
| 1
|
suggest_trie_walk(
suginfo_T *su,
langp_T *lp,
char_u *fword,
int soundfold)
{
char_u tword[MAXWLEN]; // good word collected so far
trystate_T stack[MAXWLEN];
char_u preword[MAXWLEN * 3]; // word found with proper case;
// concatenation of prefix compound
// words and split word. NUL terminated
// when going deeper but not when coming
// back.
char_u compflags[MAXWLEN]; // compound flags, one for each word
trystate_T *sp;
int newscore;
int score;
char_u *byts, *fbyts, *pbyts;
idx_T *idxs, *fidxs, *pidxs;
int depth;
int c, c2, c3;
int n = 0;
int flags;
garray_T *gap;
idx_T arridx;
int len;
char_u *p;
fromto_T *ftp;
int fl = 0, tl;
int repextra = 0; // extra bytes in fword[] from REP item
slang_T *slang = lp->lp_slang;
int fword_ends;
int goodword_ends;
#ifdef DEBUG_TRIEWALK
// Stores the name of the change made at each level.
char_u changename[MAXWLEN][80];
#endif
int breakcheckcount = 1000;
#ifdef FEAT_RELTIME
proftime_T time_limit;
#endif
int compound_ok;
// Go through the whole case-fold tree, try changes at each node.
// "tword[]" contains the word collected from nodes in the tree.
// "fword[]" the word we are trying to match with (initially the bad
// word).
depth = 0;
sp = &stack[0];
CLEAR_POINTER(sp);
sp->ts_curi = 1;
if (soundfold)
{
// Going through the soundfold tree.
byts = fbyts = slang->sl_sbyts;
idxs = fidxs = slang->sl_sidxs;
pbyts = NULL;
pidxs = NULL;
sp->ts_prefixdepth = PFD_NOPREFIX;
sp->ts_state = STATE_START;
}
else
{
// When there are postponed prefixes we need to use these first. At
// the end of the prefix we continue in the case-fold tree.
fbyts = slang->sl_fbyts;
fidxs = slang->sl_fidxs;
pbyts = slang->sl_pbyts;
pidxs = slang->sl_pidxs;
if (pbyts != NULL)
{
byts = pbyts;
idxs = pidxs;
sp->ts_prefixdepth = PFD_PREFIXTREE;
sp->ts_state = STATE_NOPREFIX; // try without prefix first
}
else
{
byts = fbyts;
idxs = fidxs;
sp->ts_prefixdepth = PFD_NOPREFIX;
sp->ts_state = STATE_START;
}
}
#ifdef FEAT_RELTIME
// The loop may take an indefinite amount of time. Break out after some
// time.
if (spell_suggest_timeout > 0)
profile_setlimit(spell_suggest_timeout, &time_limit);
#endif
// Loop to find all suggestions. At each round we either:
// - For the current state try one operation, advance "ts_curi",
// increase "depth".
// - When a state is done go to the next, set "ts_state".
// - When all states are tried decrease "depth".
while (depth >= 0 && !got_int)
{
sp = &stack[depth];
switch (sp->ts_state)
{
case STATE_START:
case STATE_NOPREFIX:
// Start of node: Deal with NUL bytes, which means
// tword[] may end here.
arridx = sp->ts_arridx; // current node in the tree
len = byts[arridx]; // bytes in this node
arridx += sp->ts_curi; // index of current byte
if (sp->ts_prefixdepth == PFD_PREFIXTREE)
{
// Skip over the NUL bytes, we use them later.
for (n = 0; n < len && byts[arridx + n] == 0; ++n)
;
sp->ts_curi += n;
// Always past NUL bytes now.
n = (int)sp->ts_state;
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_ENDNUL;
sp->ts_save_badflags = su->su_badflags;
// At end of a prefix or at start of prefixtree: check for
// following word.
if (depth < MAXWLEN - 1
&& (byts[arridx] == 0 || n == (int)STATE_NOPREFIX))
{
// Set su->su_badflags to the caps type at this position.
// Use the caps type until here for the prefix itself.
if (has_mbyte)
n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
else
n = sp->ts_fidx;
flags = badword_captype(su->su_badptr, su->su_badptr + n);
su->su_badflags = badword_captype(su->su_badptr + n,
su->su_badptr + su->su_badlen);
#ifdef DEBUG_TRIEWALK
sprintf(changename[depth], "prefix");
#endif
go_deeper(stack, depth, 0);
++depth;
sp = &stack[depth];
sp->ts_prefixdepth = depth - 1;
byts = fbyts;
idxs = fidxs;
sp->ts_arridx = 0;
// Move the prefix to preword[] with the right case
// and make find_keepcap_word() works.
tword[sp->ts_twordlen] = NUL;
make_case_word(tword + sp->ts_splitoff,
preword + sp->ts_prewordlen, flags);
sp->ts_prewordlen = (char_u)STRLEN(preword);
sp->ts_splitoff = sp->ts_twordlen;
}
break;
}
if (sp->ts_curi > len || byts[arridx] != 0)
{
// Past bytes in node and/or past NUL bytes.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_ENDNUL;
sp->ts_save_badflags = su->su_badflags;
break;
}
// End of word in tree.
++sp->ts_curi; // eat one NUL byte
flags = (int)idxs[arridx];
// Skip words with the NOSUGGEST flag.
if (flags & WF_NOSUGGEST)
break;
fword_ends = (fword[sp->ts_fidx] == NUL
|| (soundfold
? VIM_ISWHITE(fword[sp->ts_fidx])
: !spell_iswordp(fword + sp->ts_fidx, curwin)));
tword[sp->ts_twordlen] = NUL;
if (sp->ts_prefixdepth <= PFD_NOTSPECIAL
&& (sp->ts_flags & TSF_PREFIXOK) == 0
&& pbyts != NULL)
{
// There was a prefix before the word. Check that the prefix
// can be used with this word.
// Count the length of the NULs in the prefix. If there are
// none this must be the first try without a prefix.
n = stack[sp->ts_prefixdepth].ts_arridx;
len = pbyts[n++];
for (c = 0; c < len && pbyts[n + c] == 0; ++c)
;
if (c > 0)
{
c = valid_word_prefix(c, n, flags,
tword + sp->ts_splitoff, slang, FALSE);
if (c == 0)
break;
// Use the WF_RARE flag for a rare prefix.
if (c & WF_RAREPFX)
flags |= WF_RARE;
// Tricky: when checking for both prefix and compounding
// we run into the prefix flag first.
// Remember that it's OK, so that we accept the prefix
// when arriving at a compound flag.
sp->ts_flags |= TSF_PREFIXOK;
}
}
// Check NEEDCOMPOUND: can't use word without compounding. Do try
// appending another compound word below.
if (sp->ts_complen == sp->ts_compsplit && fword_ends
&& (flags & WF_NEEDCOMP))
goodword_ends = FALSE;
else
goodword_ends = TRUE;
p = NULL;
compound_ok = TRUE;
if (sp->ts_complen > sp->ts_compsplit)
{
if (slang->sl_nobreak)
{
// There was a word before this word. When there was no
// change in this word (it was correct) add the first word
// as a suggestion. If this word was corrected too, we
// need to check if a correct word follows.
if (sp->ts_fidx - sp->ts_splitfidx
== sp->ts_twordlen - sp->ts_splitoff
&& STRNCMP(fword + sp->ts_splitfidx,
tword + sp->ts_splitoff,
sp->ts_fidx - sp->ts_splitfidx) == 0)
{
preword[sp->ts_prewordlen] = NUL;
newscore = score_wordcount_adj(slang, sp->ts_score,
preword + sp->ts_prewordlen,
sp->ts_prewordlen > 0);
// Add the suggestion if the score isn't too bad.
if (newscore <= su->su_maxscore)
add_suggestion(su, &su->su_ga, preword,
sp->ts_splitfidx - repextra,
newscore, 0, FALSE,
lp->lp_sallang, FALSE);
break;
}
}
else
{
// There was a compound word before this word. If this
// word does not support compounding then give up
// (splitting is tried for the word without compound
// flag).
if (((unsigned)flags >> 24) == 0
|| sp->ts_twordlen - sp->ts_splitoff
< slang->sl_compminlen)
break;
// For multi-byte chars check character length against
// COMPOUNDMIN.
if (has_mbyte
&& slang->sl_compminlen > 0
&& mb_charlen(tword + sp->ts_splitoff)
< slang->sl_compminlen)
break;
compflags[sp->ts_complen] = ((unsigned)flags >> 24);
compflags[sp->ts_complen + 1] = NUL;
vim_strncpy(preword + sp->ts_prewordlen,
tword + sp->ts_splitoff,
sp->ts_twordlen - sp->ts_splitoff);
// Verify CHECKCOMPOUNDPATTERN rules.
if (match_checkcompoundpattern(preword, sp->ts_prewordlen,
&slang->sl_comppat))
compound_ok = FALSE;
if (compound_ok)
{
p = preword;
while (*skiptowhite(p) != NUL)
p = skipwhite(skiptowhite(p));
if (fword_ends && !can_compound(slang, p,
compflags + sp->ts_compsplit))
// Compound is not allowed. But it may still be
// possible if we add another (short) word.
compound_ok = FALSE;
}
// Get pointer to last char of previous word.
p = preword + sp->ts_prewordlen;
MB_PTR_BACK(preword, p);
}
}
// Form the word with proper case in preword.
// If there is a word from a previous split, append.
// For the soundfold tree don't change the case, simply append.
if (soundfold)
STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);
else if (flags & WF_KEEPCAP)
// Must find the word in the keep-case tree.
find_keepcap_word(slang, tword + sp->ts_splitoff,
preword + sp->ts_prewordlen);
else
{
// Include badflags: If the badword is onecap or allcap
// use that for the goodword too. But if the badword is
// allcap and it's only one char long use onecap.
c = su->su_badflags;
if ((c & WF_ALLCAP)
&& su->su_badlen == (*mb_ptr2len)(su->su_badptr))
c = WF_ONECAP;
c |= flags;
// When appending a compound word after a word character don't
// use Onecap.
if (p != NULL && spell_iswordp_nmw(p, curwin))
c &= ~WF_ONECAP;
make_case_word(tword + sp->ts_splitoff,
preword + sp->ts_prewordlen, c);
}
if (!soundfold)
{
// Don't use a banned word. It may appear again as a good
// word, thus remember it.
if (flags & WF_BANNED)
{
add_banned(su, preword + sp->ts_prewordlen);
break;
}
if ((sp->ts_complen == sp->ts_compsplit
&& WAS_BANNED(su, preword + sp->ts_prewordlen))
|| WAS_BANNED(su, preword))
{
if (slang->sl_compprog == NULL)
break;
// the word so far was banned but we may try compounding
goodword_ends = FALSE;
}
}
newscore = 0;
if (!soundfold) // soundfold words don't have flags
{
if ((flags & WF_REGION)
&& (((unsigned)flags >> 16) & lp->lp_region) == 0)
newscore += SCORE_REGION;
if (flags & WF_RARE)
newscore += SCORE_RARE;
if (!spell_valid_case(su->su_badflags,
captype(preword + sp->ts_prewordlen, NULL)))
newscore += SCORE_ICASE;
}
// TODO: how about splitting in the soundfold tree?
if (fword_ends
&& goodword_ends
&& sp->ts_fidx >= sp->ts_fidxtry
&& compound_ok)
{
// The badword also ends: add suggestions.
#ifdef DEBUG_TRIEWALK
if (soundfold && STRCMP(preword, "smwrd") == 0)
{
int j;
// print the stack of changes that brought us here
smsg("------ %s -------", fword);
for (j = 0; j < depth; ++j)
smsg("%s", changename[j]);
}
#endif
if (soundfold)
{
// For soundfolded words we need to find the original
// words, the edit distance and then add them.
add_sound_suggest(su, preword, sp->ts_score, lp);
}
else if (sp->ts_fidx > 0)
{
// Give a penalty when changing non-word char to word
// char, e.g., "thes," -> "these".
p = fword + sp->ts_fidx;
MB_PTR_BACK(fword, p);
if (!spell_iswordp(p, curwin) && *preword != NUL)
{
p = preword + STRLEN(preword);
MB_PTR_BACK(preword, p);
if (spell_iswordp(p, curwin))
newscore += SCORE_NONWORD;
}
// Give a bonus to words seen before.
score = score_wordcount_adj(slang,
sp->ts_score + newscore,
preword + sp->ts_prewordlen,
sp->ts_prewordlen > 0);
// Add the suggestion if the score isn't too bad.
if (score <= su->su_maxscore)
{
add_suggestion(su, &su->su_ga, preword,
sp->ts_fidx - repextra,
score, 0, FALSE, lp->lp_sallang, FALSE);
if (su->su_badflags & WF_MIXCAP)
{
// We really don't know if the word should be
// upper or lower case, add both.
c = captype(preword, NULL);
if (c == 0 || c == WF_ALLCAP)
{
make_case_word(tword + sp->ts_splitoff,
preword + sp->ts_prewordlen,
c == 0 ? WF_ALLCAP : 0);
add_suggestion(su, &su->su_ga, preword,
sp->ts_fidx - repextra,
score + SCORE_ICASE, 0, FALSE,
lp->lp_sallang, FALSE);
}
}
}
}
}
// Try word split and/or compounding.
if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)
// Don't split halfway a character.
&& (!has_mbyte || sp->ts_tcharlen == 0))
{
int try_compound;
int try_split;
// If past the end of the bad word don't try a split.
// Otherwise try changing the next word. E.g., find
// suggestions for "the the" where the second "the" is
// different. It's done like a split.
// TODO: word split for soundfold words
try_split = (sp->ts_fidx - repextra < su->su_badlen)
&& !soundfold;
// Get here in several situations:
// 1. The word in the tree ends:
// If the word allows compounding try that. Otherwise try
// a split by inserting a space. For both check that a
// valid words starts at fword[sp->ts_fidx].
// For NOBREAK do like compounding to be able to check if
// the next word is valid.
// 2. The badword does end, but it was due to a change (e.g.,
// a swap). No need to split, but do check that the
// following word is valid.
// 3. The badword and the word in the tree end. It may still
// be possible to compound another (short) word.
try_compound = FALSE;
if (!soundfold
&& !slang->sl_nocompoundsugs
&& slang->sl_compprog != NULL
&& ((unsigned)flags >> 24) != 0
&& sp->ts_twordlen - sp->ts_splitoff
>= slang->sl_compminlen
&& (!has_mbyte
|| slang->sl_compminlen == 0
|| mb_charlen(tword + sp->ts_splitoff)
>= slang->sl_compminlen)
&& (slang->sl_compsylmax < MAXWLEN
|| sp->ts_complen + 1 - sp->ts_compsplit
< slang->sl_compmax)
&& (can_be_compound(sp, slang,
compflags, ((unsigned)flags >> 24))))
{
try_compound = TRUE;
compflags[sp->ts_complen] = ((unsigned)flags >> 24);
compflags[sp->ts_complen + 1] = NUL;
}
// For NOBREAK we never try splitting, it won't make any word
// valid.
if (slang->sl_nobreak && !slang->sl_nocompoundsugs)
try_compound = TRUE;
// If we could add a compound word, and it's also possible to
// split at this point, do the split first and set
// TSF_DIDSPLIT to avoid doing it again.
else if (!fword_ends
&& try_compound
&& (sp->ts_flags & TSF_DIDSPLIT) == 0)
{
try_compound = FALSE;
sp->ts_flags |= TSF_DIDSPLIT;
--sp->ts_curi; // do the same NUL again
compflags[sp->ts_complen] = NUL;
}
else
sp->ts_flags &= ~TSF_DIDSPLIT;
if (try_split || try_compound)
{
if (!try_compound && (!fword_ends || !goodword_ends))
{
// If we're going to split need to check that the
// words so far are valid for compounding. If there
// is only one word it must not have the NEEDCOMPOUND
// flag.
if (sp->ts_complen == sp->ts_compsplit
&& (flags & WF_NEEDCOMP))
break;
p = preword;
while (*skiptowhite(p) != NUL)
p = skipwhite(skiptowhite(p));
if (sp->ts_complen > sp->ts_compsplit
&& !can_compound(slang, p,
compflags + sp->ts_compsplit))
break;
if (slang->sl_nosplitsugs)
newscore += SCORE_SPLIT_NO;
else
newscore += SCORE_SPLIT;
// Give a bonus to words seen before.
newscore = score_wordcount_adj(slang, newscore,
preword + sp->ts_prewordlen, TRUE);
}
if (TRY_DEEPER(su, stack, depth, newscore))
{
go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
if (!try_compound && !fword_ends)
sprintf(changename[depth], "%.*s-%s: split",
sp->ts_twordlen, tword, fword + sp->ts_fidx);
else
sprintf(changename[depth], "%.*s-%s: compound",
sp->ts_twordlen, tword, fword + sp->ts_fidx);
#endif
// Save things to be restored at STATE_SPLITUNDO.
sp->ts_save_badflags = su->su_badflags;
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_SPLITUNDO;
++depth;
sp = &stack[depth];
// Append a space to preword when splitting.
if (!try_compound && !fword_ends)
STRCAT(preword, " ");
sp->ts_prewordlen = (char_u)STRLEN(preword);
sp->ts_splitoff = sp->ts_twordlen;
sp->ts_splitfidx = sp->ts_fidx;
// If the badword has a non-word character at this
// position skip it. That means replacing the
// non-word character with a space. Always skip a
// character when the word ends. But only when the
// good word can end.
if (((!try_compound && !spell_iswordp_nmw(fword
+ sp->ts_fidx,
curwin))
|| fword_ends)
&& fword[sp->ts_fidx] != NUL
&& goodword_ends)
{
int l;
l = mb_ptr2len(fword + sp->ts_fidx);
if (fword_ends)
{
// Copy the skipped character to preword.
mch_memmove(preword + sp->ts_prewordlen,
fword + sp->ts_fidx, l);
sp->ts_prewordlen += l;
preword[sp->ts_prewordlen] = NUL;
}
else
sp->ts_score -= SCORE_SPLIT - SCORE_SUBST;
sp->ts_fidx += l;
}
// When compounding include compound flag in
// compflags[] (already set above). When splitting we
// may start compounding over again.
if (try_compound)
++sp->ts_complen;
else
sp->ts_compsplit = sp->ts_complen;
sp->ts_prefixdepth = PFD_NOPREFIX;
// set su->su_badflags to the caps type at this
// position
if (has_mbyte)
n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
else
n = sp->ts_fidx;
su->su_badflags = badword_captype(su->su_badptr + n,
su->su_badptr + su->su_badlen);
// Restart at top of the tree.
sp->ts_arridx = 0;
// If there are postponed prefixes, try these too.
if (pbyts != NULL)
{
byts = pbyts;
idxs = pidxs;
sp->ts_prefixdepth = PFD_PREFIXTREE;
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_NOPREFIX;
}
}
}
}
break;
case STATE_SPLITUNDO:
// Undo the changes done for word split or compound word.
su->su_badflags = sp->ts_save_badflags;
// Continue looking for NUL bytes.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_START;
// In case we went into the prefix tree.
byts = fbyts;
idxs = fidxs;
break;
case STATE_ENDNUL:
// Past the NUL bytes in the node.
su->su_badflags = sp->ts_save_badflags;
if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0)
{
// The badword ends, can't use STATE_PLAIN.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_DEL;
break;
}
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_PLAIN;
// FALLTHROUGH
case STATE_PLAIN:
// Go over all possible bytes at this node, add each to tword[]
// and use child node. "ts_curi" is the index.
arridx = sp->ts_arridx;
if (sp->ts_curi > byts[arridx])
{
// Done all bytes at this node, do next state. When still at
// already changed bytes skip the other tricks.
PROF_STORE(sp->ts_state)
if (sp->ts_fidx >= sp->ts_fidxtry)
sp->ts_state = STATE_DEL;
else
sp->ts_state = STATE_FINAL;
}
else
{
arridx += sp->ts_curi++;
c = byts[arridx];
// Normal byte, go one level deeper. If it's not equal to the
// byte in the bad word adjust the score. But don't even try
// when the byte was already changed. And don't try when we
// just deleted this byte, accepting it is always cheaper than
// delete + substitute.
if (c == fword[sp->ts_fidx]
|| (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE))
newscore = 0;
else
newscore = SCORE_SUBST;
if ((newscore == 0
|| (sp->ts_fidx >= sp->ts_fidxtry
&& ((sp->ts_flags & TSF_DIDDEL) == 0
|| c != fword[sp->ts_delidx])))
&& TRY_DEEPER(su, stack, depth, newscore))
{
go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
if (newscore > 0)
sprintf(changename[depth], "%.*s-%s: subst %c to %c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
fword[sp->ts_fidx], c);
else
sprintf(changename[depth], "%.*s-%s: accept %c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
fword[sp->ts_fidx]);
#endif
++depth;
sp = &stack[depth];
if (fword[sp->ts_fidx] != NUL)
++sp->ts_fidx;
tword[sp->ts_twordlen++] = c;
sp->ts_arridx = idxs[arridx];
if (newscore == SCORE_SUBST)
sp->ts_isdiff = DIFF_YES;
if (has_mbyte)
{
// Multi-byte characters are a bit complicated to
// handle: They differ when any of the bytes differ
// and then their length may also differ.
if (sp->ts_tcharlen == 0)
{
// First byte.
sp->ts_tcharidx = 0;
sp->ts_tcharlen = MB_BYTE2LEN(c);
sp->ts_fcharstart = sp->ts_fidx - 1;
sp->ts_isdiff = (newscore != 0)
? DIFF_YES : DIFF_NONE;
}
else if (sp->ts_isdiff == DIFF_INSERT)
// When inserting trail bytes don't advance in the
// bad word.
--sp->ts_fidx;
if (++sp->ts_tcharidx == sp->ts_tcharlen)
{
// Last byte of character.
if (sp->ts_isdiff == DIFF_YES)
{
// Correct ts_fidx for the byte length of the
// character (we didn't check that before).
sp->ts_fidx = sp->ts_fcharstart
+ mb_ptr2len(
fword + sp->ts_fcharstart);
// For changing a composing character adjust
// the score from SCORE_SUBST to
// SCORE_SUBCOMP.
if (enc_utf8
&& utf_iscomposing(
utf_ptr2char(tword
+ sp->ts_twordlen
- sp->ts_tcharlen))
&& utf_iscomposing(
utf_ptr2char(fword
+ sp->ts_fcharstart)))
sp->ts_score -=
SCORE_SUBST - SCORE_SUBCOMP;
// For a similar character adjust score from
// SCORE_SUBST to SCORE_SIMILAR.
else if (!soundfold
&& slang->sl_has_map
&& similar_chars(slang,
mb_ptr2char(tword
+ sp->ts_twordlen
- sp->ts_tcharlen),
mb_ptr2char(fword
+ sp->ts_fcharstart)))
sp->ts_score -=
SCORE_SUBST - SCORE_SIMILAR;
}
else if (sp->ts_isdiff == DIFF_INSERT
&& sp->ts_twordlen > sp->ts_tcharlen)
{
p = tword + sp->ts_twordlen - sp->ts_tcharlen;
c = mb_ptr2char(p);
if (enc_utf8 && utf_iscomposing(c))
{
// Inserting a composing char doesn't
// count that much.
sp->ts_score -= SCORE_INS - SCORE_INSCOMP;
}
else
{
// If the previous character was the same,
// thus doubling a character, give a bonus
// to the score. Also for the soundfold
// tree (might seem illogical but does
// give better scores).
MB_PTR_BACK(tword, p);
if (c == mb_ptr2char(p))
sp->ts_score -= SCORE_INS
- SCORE_INSDUP;
}
}
// Starting a new char, reset the length.
sp->ts_tcharlen = 0;
}
}
else
{
// If we found a similar char adjust the score.
// We do this after calling go_deeper() because
// it's slow.
if (newscore != 0
&& !soundfold
&& slang->sl_has_map
&& similar_chars(slang,
c, fword[sp->ts_fidx - 1]))
sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;
}
}
}
break;
case STATE_DEL:
// When past the first byte of a multi-byte char don't try
// delete/insert/swap a character.
if (has_mbyte && sp->ts_tcharlen > 0)
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_FINAL;
break;
}
// Try skipping one character in the bad word (delete it).
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_INS_PREP;
sp->ts_curi = 1;
if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')
// Deleting a vowel at the start of a word counts less, see
// soundalike_score().
newscore = 2 * SCORE_DEL / 3;
else
newscore = SCORE_DEL;
if (fword[sp->ts_fidx] != NUL
&& TRY_DEEPER(su, stack, depth, newscore))
{
go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
sprintf(changename[depth], "%.*s-%s: delete %c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
fword[sp->ts_fidx]);
#endif
++depth;
// Remember what character we deleted, so that we can avoid
// inserting it again.
stack[depth].ts_flags |= TSF_DIDDEL;
stack[depth].ts_delidx = sp->ts_fidx;
// Advance over the character in fword[]. Give a bonus to the
// score if the same character is following "nn" -> "n". It's
// a bit illogical for soundfold tree but it does give better
// results.
if (has_mbyte)
{
c = mb_ptr2char(fword + sp->ts_fidx);
stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx);
if (enc_utf8 && utf_iscomposing(c))
stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;
else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))
stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
}
else
{
++stack[depth].ts_fidx;
if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])
stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
}
break;
}
// FALLTHROUGH
case STATE_INS_PREP:
if (sp->ts_flags & TSF_DIDDEL)
{
// If we just deleted a byte then inserting won't make sense,
// a substitute is always cheaper.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_SWAP;
break;
}
// skip over NUL bytes
n = sp->ts_arridx;
for (;;)
{
if (sp->ts_curi > byts[n])
{
// Only NUL bytes at this node, go to next state.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_SWAP;
break;
}
if (byts[n + sp->ts_curi] != NUL)
{
// Found a byte to insert.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_INS;
break;
}
++sp->ts_curi;
}
break;
// FALLTHROUGH
case STATE_INS:
// Insert one byte. Repeat this for each possible byte at this
// node.
n = sp->ts_arridx;
if (sp->ts_curi > byts[n])
{
// Done all bytes at this node, go to next state.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_SWAP;
break;
}
// Do one more byte at this node, but:
// - Skip NUL bytes.
// - Skip the byte if it's equal to the byte in the word,
// accepting that byte is always better.
n += sp->ts_curi++;
c = byts[n];
if (soundfold && sp->ts_twordlen == 0 && c == '*')
// Inserting a vowel at the start of a word counts less,
// see soundalike_score().
newscore = 2 * SCORE_INS / 3;
else
newscore = SCORE_INS;
if (c != fword[sp->ts_fidx]
&& TRY_DEEPER(su, stack, depth, newscore))
{
go_deeper(stack, depth, newscore);
#ifdef DEBUG_TRIEWALK
sprintf(changename[depth], "%.*s-%s: insert %c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
c);
#endif
++depth;
sp = &stack[depth];
tword[sp->ts_twordlen++] = c;
sp->ts_arridx = idxs[n];
if (has_mbyte)
{
fl = MB_BYTE2LEN(c);
if (fl > 1)
{
// There are following bytes for the same character.
// We must find all bytes before trying
// delete/insert/swap/etc.
sp->ts_tcharlen = fl;
sp->ts_tcharidx = 1;
sp->ts_isdiff = DIFF_INSERT;
}
}
else
fl = 1;
if (fl == 1)
{
// If the previous character was the same, thus doubling a
// character, give a bonus to the score. Also for
// soundfold words (illogical but does give a better
// score).
if (sp->ts_twordlen >= 2
&& tword[sp->ts_twordlen - 2] == c)
sp->ts_score -= SCORE_INS - SCORE_INSDUP;
}
}
break;
case STATE_SWAP:
// Swap two bytes in the bad word: "12" -> "21".
// We change "fword" here, it's changed back afterwards at
// STATE_UNSWAP.
p = fword + sp->ts_fidx;
c = *p;
if (c == NUL)
{
// End of word, can't swap or replace.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_FINAL;
break;
}
// Don't swap if the first character is not a word character.
// SWAP3 etc. also don't make sense then.
if (!soundfold && !spell_iswordp(p, curwin))
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
break;
}
if (has_mbyte)
{
n = MB_CPTR2LEN(p);
c = mb_ptr2char(p);
if (p[n] == NUL)
c2 = NUL;
else if (!soundfold && !spell_iswordp(p + n, curwin))
c2 = c; // don't swap non-word char
else
c2 = mb_ptr2char(p + n);
}
else
{
if (p[1] == NUL)
c2 = NUL;
else if (!soundfold && !spell_iswordp(p + 1, curwin))
c2 = c; // don't swap non-word char
else
c2 = p[1];
}
// When the second character is NUL we can't swap.
if (c2 == NUL)
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
break;
}
// When characters are identical, swap won't do anything.
// Also get here if the second char is not a word character.
if (c == c2)
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_SWAP3;
break;
}
if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))
{
go_deeper(stack, depth, SCORE_SWAP);
#ifdef DEBUG_TRIEWALK
sprintf(changename[depth], "%.*s-%s: swap %c and %c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
c, c2);
#endif
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_UNSWAP;
++depth;
if (has_mbyte)
{
fl = mb_char2len(c2);
mch_memmove(p, p + n, fl);
mb_char2bytes(c, p + fl);
stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
}
else
{
p[0] = c2;
p[1] = c;
stack[depth].ts_fidxtry = sp->ts_fidx + 2;
}
}
else
{
// If this swap doesn't work then SWAP3 won't either.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
}
break;
case STATE_UNSWAP:
// Undo the STATE_SWAP swap: "21" -> "12".
p = fword + sp->ts_fidx;
if (has_mbyte)
{
n = mb_ptr2len(p);
c = mb_ptr2char(p + n);
mch_memmove(p + mb_ptr2len(p + n), p, n);
mb_char2bytes(c, p);
}
else
{
c = *p;
*p = p[1];
p[1] = c;
}
// FALLTHROUGH
case STATE_SWAP3:
// Swap two bytes, skipping one: "123" -> "321". We change
// "fword" here, it's changed back afterwards at STATE_UNSWAP3.
p = fword + sp->ts_fidx;
if (has_mbyte)
{
n = MB_CPTR2LEN(p);
c = mb_ptr2char(p);
fl = MB_CPTR2LEN(p + n);
c2 = mb_ptr2char(p + n);
if (!soundfold && !spell_iswordp(p + n + fl, curwin))
c3 = c; // don't swap non-word char
else
c3 = mb_ptr2char(p + n + fl);
}
else
{
c = *p;
c2 = p[1];
if (!soundfold && !spell_iswordp(p + 2, curwin))
c3 = c; // don't swap non-word char
else
c3 = p[2];
}
// When characters are identical: "121" then SWAP3 result is
// identical, ROT3L result is same as SWAP: "211", ROT3L result is
// same as SWAP on next char: "112". Thus skip all swapping.
// Also skip when c3 is NUL.
// Also get here when the third character is not a word character.
// Second character may any char: "a.b" -> "b.a"
if (c == c3 || c3 == NUL)
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
break;
}
if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
{
go_deeper(stack, depth, SCORE_SWAP3);
#ifdef DEBUG_TRIEWALK
sprintf(changename[depth], "%.*s-%s: swap3 %c and %c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
c, c3);
#endif
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_UNSWAP3;
++depth;
if (has_mbyte)
{
tl = mb_char2len(c3);
mch_memmove(p, p + n + fl, tl);
mb_char2bytes(c2, p + tl);
mb_char2bytes(c, p + fl + tl);
stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;
}
else
{
p[0] = p[2];
p[2] = c;
stack[depth].ts_fidxtry = sp->ts_fidx + 3;
}
}
else
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
}
break;
case STATE_UNSWAP3:
// Undo STATE_SWAP3: "321" -> "123"
p = fword + sp->ts_fidx;
if (has_mbyte)
{
n = mb_ptr2len(p);
c2 = mb_ptr2char(p + n);
fl = mb_ptr2len(p + n);
c = mb_ptr2char(p + n + fl);
tl = mb_ptr2len(p + n + fl);
mch_memmove(p + fl + tl, p, n);
mb_char2bytes(c, p);
mb_char2bytes(c2, p + tl);
p = p + tl;
}
else
{
c = *p;
*p = p[2];
p[2] = c;
++p;
}
if (!soundfold && !spell_iswordp(p, curwin))
{
// Middle char is not a word char, skip the rotate. First and
// third char were already checked at swap and swap3.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
break;
}
// Rotate three characters left: "123" -> "231". We change
// "fword" here, it's changed back afterwards at STATE_UNROT3L.
if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
{
go_deeper(stack, depth, SCORE_SWAP3);
#ifdef DEBUG_TRIEWALK
p = fword + sp->ts_fidx;
sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
p[0], p[1], p[2]);
#endif
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_UNROT3L;
++depth;
p = fword + sp->ts_fidx;
if (has_mbyte)
{
n = MB_CPTR2LEN(p);
c = mb_ptr2char(p);
fl = MB_CPTR2LEN(p + n);
fl += MB_CPTR2LEN(p + n + fl);
mch_memmove(p, p + n, fl);
mb_char2bytes(c, p + fl);
stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
}
else
{
c = *p;
*p = p[1];
p[1] = p[2];
p[2] = c;
stack[depth].ts_fidxtry = sp->ts_fidx + 3;
}
}
else
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
}
break;
case STATE_UNROT3L:
// Undo ROT3L: "231" -> "123"
p = fword + sp->ts_fidx;
if (has_mbyte)
{
n = mb_ptr2len(p);
n += mb_ptr2len(p + n);
c = mb_ptr2char(p + n);
tl = mb_ptr2len(p + n);
mch_memmove(p + tl, p, n);
mb_char2bytes(c, p);
}
else
{
c = p[2];
p[2] = p[1];
p[1] = *p;
*p = c;
}
// Rotate three bytes right: "123" -> "312". We change "fword"
// here, it's changed back afterwards at STATE_UNROT3R.
if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
{
go_deeper(stack, depth, SCORE_SWAP3);
#ifdef DEBUG_TRIEWALK
p = fword + sp->ts_fidx;
sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
p[0], p[1], p[2]);
#endif
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_UNROT3R;
++depth;
p = fword + sp->ts_fidx;
if (has_mbyte)
{
n = MB_CPTR2LEN(p);
n += MB_CPTR2LEN(p + n);
c = mb_ptr2char(p + n);
tl = MB_CPTR2LEN(p + n);
mch_memmove(p + tl, p, n);
mb_char2bytes(c, p);
stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;
}
else
{
c = p[2];
p[2] = p[1];
p[1] = *p;
*p = c;
stack[depth].ts_fidxtry = sp->ts_fidx + 3;
}
}
else
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_INI;
}
break;
case STATE_UNROT3R:
// Undo ROT3R: "312" -> "123"
p = fword + sp->ts_fidx;
if (has_mbyte)
{
c = mb_ptr2char(p);
tl = mb_ptr2len(p);
n = mb_ptr2len(p + tl);
n += mb_ptr2len(p + tl + n);
mch_memmove(p, p + tl, n);
mb_char2bytes(c, p + n);
}
else
{
c = *p;
*p = p[1];
p[1] = p[2];
p[2] = c;
}
// FALLTHROUGH
case STATE_REP_INI:
// Check if matching with REP items from the .aff file would work.
// Quickly skip if:
// - there are no REP items and we are not in the soundfold trie
// - the score is going to be too high anyway
// - already applied a REP item or swapped here
if ((lp->lp_replang == NULL && !soundfold)
|| sp->ts_score + SCORE_REP >= su->su_maxscore
|| sp->ts_fidx < sp->ts_fidxtry)
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_FINAL;
break;
}
// Use the first byte to quickly find the first entry that may
// match. If the index is -1 there is none.
if (soundfold)
sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];
else
sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];
if (sp->ts_curi < 0)
{
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_FINAL;
break;
}
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP;
// FALLTHROUGH
case STATE_REP:
// Try matching with REP items from the .aff file. For each match
// replace the characters and check if the resulting word is
// valid.
p = fword + sp->ts_fidx;
if (soundfold)
gap = &slang->sl_repsal;
else
gap = &lp->lp_replang->sl_rep;
while (sp->ts_curi < gap->ga_len)
{
ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
if (*ftp->ft_from != *p)
{
// past possible matching entries
sp->ts_curi = gap->ga_len;
break;
}
if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0
&& TRY_DEEPER(su, stack, depth, SCORE_REP))
{
go_deeper(stack, depth, SCORE_REP);
#ifdef DEBUG_TRIEWALK
sprintf(changename[depth], "%.*s-%s: replace %s with %s",
sp->ts_twordlen, tword, fword + sp->ts_fidx,
ftp->ft_from, ftp->ft_to);
#endif
// Need to undo this afterwards.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP_UNDO;
// Change the "from" to the "to" string.
++depth;
fl = (int)STRLEN(ftp->ft_from);
tl = (int)STRLEN(ftp->ft_to);
if (fl != tl)
{
STRMOVE(p + tl, p + fl);
repextra += tl - fl;
}
mch_memmove(p, ftp->ft_to, tl);
stack[depth].ts_fidxtry = sp->ts_fidx + tl;
stack[depth].ts_tcharlen = 0;
break;
}
}
if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)
{
// No (more) matches.
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_FINAL;
}
break;
case STATE_REP_UNDO:
// Undo a REP replacement and continue with the next one.
if (soundfold)
gap = &slang->sl_repsal;
else
gap = &lp->lp_replang->sl_rep;
ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
fl = (int)STRLEN(ftp->ft_from);
tl = (int)STRLEN(ftp->ft_to);
p = fword + sp->ts_fidx;
if (fl != tl)
{
STRMOVE(p + fl, p + tl);
repextra -= tl - fl;
}
mch_memmove(p, ftp->ft_from, fl);
PROF_STORE(sp->ts_state)
sp->ts_state = STATE_REP;
break;
default:
// Did all possible states at this level, go up one level.
--depth;
if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)
{
// Continue in or go back to the prefix tree.
byts = pbyts;
idxs = pidxs;
}
// Don't check for CTRL-C too often, it takes time.
if (--breakcheckcount == 0)
{
ui_breakcheck();
breakcheckcount = 1000;
#ifdef FEAT_RELTIME
if (spell_suggest_timeout > 0
&& profile_passed_limit(&time_limit))
got_int = TRUE;
#endif
}
}
}
}
| null | null | 200,323
|
78345173681102282641073828675589193816
| 1,430
|
patch 8.2.5123: using invalid index when looking for spell suggestions
Problem: Using invalid index when looking for spell suggestions.
Solution: Do not decrement the index when it is zero.
|
other
|
radare2
|
48f0ea79f99174fb0a62cb2354e13496ce5b7c44
| 1
|
RList *r_bin_ne_get_segments(r_bin_ne_obj_t *bin) {
int i;
if (!bin) {
return NULL;
}
RList *segments = r_list_newf (free);
for (i = 0; i < bin->ne_header->SegCount; i++) {
RBinSection *bs = R_NEW0 (RBinSection);
if (!bs) {
return segments;
}
NE_image_segment_entry *se = &bin->segment_entries[i];
bs->size = se->length;
bs->vsize = se->minAllocSz ? se->minAllocSz : 64000;
bs->bits = R_SYS_BITS_16;
bs->is_data = se->flags & IS_DATA;
bs->perm = __translate_perms (se->flags);
bs->paddr = (ut64)se->offset * bin->alignment;
bs->name = r_str_newf ("%s.%" PFMT64d, se->flags & IS_MOVEABLE ? "MOVEABLE" : "FIXED", bs->paddr);
bs->is_segment = true;
r_list_append (segments, bs);
}
bin->segments = segments;
return segments;
}
| null | null | 200,379
|
238157226993888060412008928414827920796
| 25
|
Fix null deref in ne parser ##crash
* Reported by @cnitlrt via huntr.dev
* BountyID: d8b6d239-6d7b-4783-b26b-5be848c01aa1/
* Reproducer: nenull
|
other
|
qemu
|
bc6f28995ff88f5d82c38afcfd65406f0ae375aa
| 1
|
static void sdhci_do_adma(SDHCIState *s)
{
unsigned int begin, length;
const uint16_t block_size = s->blksize & BLOCK_SIZE_MASK;
ADMADescr dscr = {};
int i;
if (s->trnmod & SDHC_TRNS_BLK_CNT_EN && !s->blkcnt) {
/* Stop Multiple Transfer */
sdhci_end_transfer(s);
return;
}
for (i = 0; i < SDHC_ADMA_DESCS_PER_DELAY; ++i) {
s->admaerr &= ~SDHC_ADMAERR_LENGTH_MISMATCH;
get_adma_description(s, &dscr);
trace_sdhci_adma_loop(dscr.addr, dscr.length, dscr.attr);
if ((dscr.attr & SDHC_ADMA_ATTR_VALID) == 0) {
/* Indicate that error occurred in ST_FDS state */
s->admaerr &= ~SDHC_ADMAERR_STATE_MASK;
s->admaerr |= SDHC_ADMAERR_STATE_ST_FDS;
/* Generate ADMA error interrupt */
if (s->errintstsen & SDHC_EISEN_ADMAERR) {
s->errintsts |= SDHC_EIS_ADMAERR;
s->norintsts |= SDHC_NIS_ERR;
}
sdhci_update_irq(s);
return;
}
length = dscr.length ? dscr.length : 64 * KiB;
switch (dscr.attr & SDHC_ADMA_ATTR_ACT_MASK) {
case SDHC_ADMA_ATTR_ACT_TRAN: /* data transfer */
if (s->trnmod & SDHC_TRNS_READ) {
while (length) {
if (s->data_count == 0) {
sdbus_read_data(&s->sdbus, s->fifo_buffer, block_size);
}
begin = s->data_count;
if ((length + begin) < block_size) {
s->data_count = length + begin;
length = 0;
} else {
s->data_count = block_size;
length -= block_size - begin;
}
dma_memory_write(s->dma_as, dscr.addr,
&s->fifo_buffer[begin],
s->data_count - begin);
dscr.addr += s->data_count - begin;
if (s->data_count == block_size) {
s->data_count = 0;
if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
s->blkcnt--;
if (s->blkcnt == 0) {
break;
}
}
}
}
} else {
while (length) {
begin = s->data_count;
if ((length + begin) < block_size) {
s->data_count = length + begin;
length = 0;
} else {
s->data_count = block_size;
length -= block_size - begin;
}
dma_memory_read(s->dma_as, dscr.addr,
&s->fifo_buffer[begin],
s->data_count - begin);
dscr.addr += s->data_count - begin;
if (s->data_count == block_size) {
sdbus_write_data(&s->sdbus, s->fifo_buffer, block_size);
s->data_count = 0;
if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
s->blkcnt--;
if (s->blkcnt == 0) {
break;
}
}
}
}
}
s->admasysaddr += dscr.incr;
break;
case SDHC_ADMA_ATTR_ACT_LINK: /* link to next descriptor table */
s->admasysaddr = dscr.addr;
trace_sdhci_adma("link", s->admasysaddr);
break;
default:
s->admasysaddr += dscr.incr;
break;
}
if (dscr.attr & SDHC_ADMA_ATTR_INT) {
trace_sdhci_adma("interrupt", s->admasysaddr);
if (s->norintstsen & SDHC_NISEN_DMA) {
s->norintsts |= SDHC_NIS_DMA;
}
if (sdhci_update_irq(s) && !(dscr.attr & SDHC_ADMA_ATTR_END)) {
/* IRQ delivered, reschedule current transfer */
break;
}
}
/* ADMA transfer terminates if blkcnt == 0 or by END attribute */
if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
(s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) {
trace_sdhci_adma_transfer_completed();
if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) &&
(s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
s->blkcnt != 0)) {
trace_sdhci_error("SD/MMC host ADMA length mismatch");
s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH |
SDHC_ADMAERR_STATE_ST_TFR;
if (s->errintstsen & SDHC_EISEN_ADMAERR) {
trace_sdhci_error("Set ADMA error flag");
s->errintsts |= SDHC_EIS_ADMAERR;
s->norintsts |= SDHC_NIS_ERR;
}
sdhci_update_irq(s);
}
sdhci_end_transfer(s);
return;
}
}
/* we have unfinished business - reschedule to continue ADMA */
timer_mod(s->transfer_timer,
qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY);
}
| null | null | 200,672
|
86932256731604059074971414280380924075
| 142
|
hw/sd: sdhci: Correctly set the controller status for ADMA
When an ADMA transfer is started, the codes forget to set the
controller status to indicate a transfer is in progress.
With this fix, the following 2 reproducers:
https://paste.debian.net/plain/1185136
https://paste.debian.net/plain/1185141
cannot be reproduced with the following QEMU command line:
$ qemu-system-x86_64 -nographic -machine accel=qtest -m 512M \
-nodefaults -device sdhci-pci,sd-spec-version=3 \
-drive if=sd,index=0,file=null-co://,format=raw,id=mydrive \
-device sd-card,drive=mydrive -qtest stdio
Cc: [email protected]
Fixes: CVE-2020-17380
Fixes: CVE-2020-25085
Fixes: CVE-2021-3409
Fixes: d7dfca0807a0 ("hw/sdhci: introduce standard SD host controller")
Reported-by: Alexander Bulekov <[email protected]>
Reported-by: Cornelius Aschermann (Ruhr-Universität Bochum)
Reported-by: Sergej Schumilo (Ruhr-Universität Bochum)
Reported-by: Simon Wörner (Ruhr-Universität Bochum)
Buglink: https://bugs.launchpad.net/qemu/+bug/1892960
Buglink: https://bugs.launchpad.net/qemu/+bug/1909418
Buglink: https://bugzilla.redhat.com/show_bug.cgi?id=1928146
Tested-by: Alexander Bulekov <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Signed-off-by: Bin Meng <[email protected]>
Message-Id: <[email protected]>
Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
|
other
|
jdk8u
|
1dafef08cc922ee85a8e216387100dc681a5484d
| 1
|
ciConstant ciEnv::get_constant_by_index_impl(constantPoolHandle cpool,
int pool_index, int cache_index,
ciInstanceKlass* accessor) {
bool ignore_will_link;
EXCEPTION_CONTEXT;
int index = pool_index;
if (cache_index >= 0) {
assert(index < 0, "only one kind of index at a time");
oop obj = cpool->resolved_references()->obj_at(cache_index);
if (obj != NULL) {
ciObject* ciobj = get_object(obj);
if (ciobj->is_array()) {
return ciConstant(T_ARRAY, ciobj);
} else {
assert(ciobj->is_instance(), "should be an instance");
return ciConstant(T_OBJECT, ciobj);
}
}
index = cpool->object_to_cp_index(cache_index);
}
constantTag tag = cpool->tag_at(index);
if (tag.is_int()) {
return ciConstant(T_INT, (jint)cpool->int_at(index));
} else if (tag.is_long()) {
return ciConstant((jlong)cpool->long_at(index));
} else if (tag.is_float()) {
return ciConstant((jfloat)cpool->float_at(index));
} else if (tag.is_double()) {
return ciConstant((jdouble)cpool->double_at(index));
} else if (tag.is_string()) {
oop string = NULL;
assert(cache_index >= 0, "should have a cache index");
if (cpool->is_pseudo_string_at(index)) {
string = cpool->pseudo_string_at(index, cache_index);
} else {
string = cpool->string_at(index, cache_index, THREAD);
if (HAS_PENDING_EXCEPTION) {
CLEAR_PENDING_EXCEPTION;
record_out_of_memory_failure();
return ciConstant();
}
}
ciObject* constant = get_object(string);
if (constant->is_array()) {
return ciConstant(T_ARRAY, constant);
} else {
assert (constant->is_instance(), "must be an instance, or not? ");
return ciConstant(T_OBJECT, constant);
}
} else if (tag.is_klass() || tag.is_unresolved_klass()) {
// 4881222: allow ldc to take a class type
ciKlass* klass = get_klass_by_index_impl(cpool, index, ignore_will_link, accessor);
if (HAS_PENDING_EXCEPTION) {
CLEAR_PENDING_EXCEPTION;
record_out_of_memory_failure();
return ciConstant();
}
assert (klass->is_instance_klass() || klass->is_array_klass(),
"must be an instance or array klass ");
return ciConstant(T_OBJECT, klass->java_mirror());
} else if (tag.is_method_type()) {
// must execute Java code to link this CP entry into cache[i].f1
ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
ciObject* ciobj = get_unloaded_method_type_constant(signature);
return ciConstant(T_OBJECT, ciobj);
} else if (tag.is_method_handle()) {
// must execute Java code to link this CP entry into cache[i].f1
int ref_kind = cpool->method_handle_ref_kind_at(index);
int callee_index = cpool->method_handle_klass_index_at(index);
ciKlass* callee = get_klass_by_index_impl(cpool, callee_index, ignore_will_link, accessor);
ciSymbol* name = get_symbol(cpool->method_handle_name_ref_at(index));
ciSymbol* signature = get_symbol(cpool->method_handle_signature_ref_at(index));
ciObject* ciobj = get_unloaded_method_handle_constant(callee, name, signature, ref_kind);
return ciConstant(T_OBJECT, ciobj);
} else {
ShouldNotReachHere();
return ciConstant();
}
}
| null | null | 200,680
|
213862644864366524796846638949126077190
| 79
|
8281859: Improve class compilation
Reviewed-by: andrew
Backport-of: 3ac62a66efd05d0842076dd4cfbea0e53b12630f
|
other
|
linux
|
fc739a058d99c9297ef6bfd923b809d85855b9a9
| 1
|
static int fastrpc_dma_buf_attach(struct dma_buf *dmabuf,
struct dma_buf_attachment *attachment)
{
struct fastrpc_dma_buf_attachment *a;
struct fastrpc_buf *buffer = dmabuf->priv;
int ret;
a = kzalloc(sizeof(*a), GFP_KERNEL);
if (!a)
return -ENOMEM;
ret = dma_get_sgtable(buffer->dev, &a->sgt, buffer->virt,
FASTRPC_PHYS(buffer->phys), buffer->size);
if (ret < 0) {
dev_err(buffer->dev, "failed to get scatterlist from DMA API\n");
return -EINVAL;
}
a->dev = attachment->dev;
INIT_LIST_HEAD(&a->node);
attachment->priv = a;
mutex_lock(&buffer->lock);
list_add(&a->node, &buffer->attachments);
mutex_unlock(&buffer->lock);
return 0;
}
| null | null | 200,695
|
144310532328839814413685692402685184168
| 28
|
misc: fastrpc: prevent memory leak in fastrpc_dma_buf_attach
In fastrpc_dma_buf_attach if dma_get_sgtable fails the allocated memory
for a should be released.
Signed-off-by: Navid Emamdoost <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Greg Kroah-Hartman <[email protected]>
|
other
|
ncurses
|
790a85dbd4a81d5f5d8dd02a44d84f01512ef443
| 1
|
cvtchar(register const char *sp)
/* convert a character to a terminfo push */
{
unsigned char c = 0;
int len;
switch (*sp) {
case '\\':
switch (*++sp) {
case '\'':
case '$':
case '\\':
case '%':
c = UChar(*sp);
len = 2;
break;
case '\0':
c = '\\';
len = 1;
break;
case '0':
case '1':
case '2':
case '3':
len = 1;
while (isdigit(UChar(*sp))) {
c = UChar(8 * c + (*sp++ - '0'));
len++;
}
break;
default:
c = UChar(*sp);
len = (c != '\0') ? 2 : 1;
break;
}
break;
case '^':
c = UChar(*++sp);
if (c == '?')
c = 127;
else
c &= 0x1f;
len = 2;
break;
default:
c = UChar(*sp);
len = (c != '\0') ? 1 : 0;
}
if (isgraph(c) && c != ',' && c != '\'' && c != '\\' && c != ':') {
dp = save_string(dp, "%\'");
dp = save_char(dp, c);
dp = save_char(dp, '\'');
} else if (c != '\0') {
dp = save_string(dp, "%{");
if (c > 99)
dp = save_char(dp, c / 100 + '0');
if (c > 9)
dp = save_char(dp, ((int) (c / 10)) % 10 + '0');
dp = save_char(dp, c % 10 + '0');
dp = save_char(dp, '}');
}
return len;
}
| null | null | 200,781
|
301385257558584493033269260420493542879
| 63
|
ncurses 6.2 - patch 20200531
+ correct configure version-check/warnng for g++ to allow for 10.x
+ re-enable "bel" in konsole-base (report by Nia Huang)
+ add linux-s entry (patch by Alexandre Montaron).
+ drop long-obsolete convert_configure.pl
+ add test/test_parm.c, for checking tparm changes.
+ improve parameter-checking for tparm, adding function _nc_tiparm() to
handle the most-used case, which accepts only numeric parameters
(report/testcase by "puppet-meteor").
+ use a more conservative estimate of the buffer-size in lib_tparm.c's
save_text() and save_number(), in case the sprintf() function
passes-through unexpected characters from a format specifier
(report/testcase by "puppet-meteor").
+ add a check for end-of-string in cvtchar to handle a malformed
string in infotocap (report/testcase by "puppet-meteor").
|
other
|
tor
|
00fffbc1a15e2696a89c721d0c94dc333ff419ef
| 1
|
set_routerstatus_from_routerinfo(routerstatus_t *rs,
routerinfo_t *ri, time_t now,
int naming, int listbadexits,
int listbaddirs, int vote_on_hsdirs)
{
int unstable_version =
!tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs");
memset(rs, 0, sizeof(routerstatus_t));
rs->is_authority =
router_digest_is_trusted_dir(ri->cache_info.identity_digest);
/* Already set by compute_performance_thresholds. */
rs->is_exit = ri->is_exit;
rs->is_stable = ri->is_stable =
router_is_active(ri, now) &&
!dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&
!unstable_version;
rs->is_fast = ri->is_fast =
router_is_active(ri, now) &&
!dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
rs->is_running = ri->is_running; /* computed above */
if (naming) {
uint32_t name_status = dirserv_get_name_status(
ri->cache_info.identity_digest, ri->nickname);
rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;
rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;
}
rs->is_valid = ri->is_valid;
if (rs->is_fast &&
(router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD ||
router_get_advertised_bandwidth(ri) >=
MIN(guard_bandwidth_including_exits,
guard_bandwidth_excluding_exits))) {
long tk = rep_hist_get_weighted_time_known(
ri->cache_info.identity_digest, now);
double wfu = rep_hist_get_weighted_fractional_uptime(
ri->cache_info.identity_digest, now);
rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
} else {
rs->is_possible_guard = 0;
}
rs->is_bad_directory = listbaddirs && ri->is_bad_directory;
rs->is_bad_exit = listbadexits && ri->is_bad_exit;
ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now);
rs->is_hs_dir = vote_on_hsdirs && ri->is_hs_dir;
rs->is_v2_dir = ri->dir_port != 0;
if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
rs->is_named = rs->is_unnamed = 0;
rs->published_on = ri->cache_info.published_on;
memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN);
memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
DIGEST_LEN);
rs->addr = ri->addr;
strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
rs->or_port = ri->or_port;
rs->dir_port = ri->dir_port;
}
| null | null | 200,831
|
316658529587567882032614137079274414942
| 62
|
Don't give the Guard flag to relays without the CVE-2011-2768 fix
|
other
|
vim
|
d6c67629ed05aae436164eec474832daf8ba7420
| 1
|
call_qftf_func(qf_list_T *qfl, int qf_winid, long start_idx, long end_idx)
{
callback_T *cb = &qftf_cb;
list_T *qftf_list = NULL;
// If 'quickfixtextfunc' is set, then use the user-supplied function to get
// the text to display. Use the local value of 'quickfixtextfunc' if it is
// set.
if (qfl->qf_qftf_cb.cb_name != NULL)
cb = &qfl->qf_qftf_cb;
if (cb->cb_name != NULL)
{
typval_T args[1];
dict_T *d;
typval_T rettv;
// create the dict argument
if ((d = dict_alloc_lock(VAR_FIXED)) == NULL)
return NULL;
dict_add_number(d, "quickfix", (long)IS_QF_LIST(qfl));
dict_add_number(d, "winid", (long)qf_winid);
dict_add_number(d, "id", (long)qfl->qf_id);
dict_add_number(d, "start_idx", start_idx);
dict_add_number(d, "end_idx", end_idx);
++d->dv_refcount;
args[0].v_type = VAR_DICT;
args[0].vval.v_dict = d;
qftf_list = NULL;
if (call_callback(cb, 0, &rettv, 1, args) != FAIL)
{
if (rettv.v_type == VAR_LIST)
{
qftf_list = rettv.vval.v_list;
qftf_list->lv_refcount++;
}
clear_tv(&rettv);
}
dict_unref(d);
}
return qftf_list;
}
| null | null | 200,895
|
248939390106946692584192281141425533800
| 43
|
patch 9.0.0260: using freed memory when using 'quickfixtextfunc' recursively
Problem: Using freed memory when using 'quickfixtextfunc' recursively.
Solution: Do not allow for recursion.
|
other
|
libvirt
|
524de6cc35d3b222f0e940bb0fd027f5482572c5
| 1
|
testBackingParse(const void *args)
{
const struct testBackingParseData *data = args;
g_auto(virBuffer) buf = VIR_BUFFER_INITIALIZER;
g_autofree char *xml = NULL;
g_autoptr(virStorageSource) src = NULL;
int rc;
int erc = data->rv;
/* expect failure return code with NULL expected data */
if (!data->expect)
erc = -1;
if ((rc = virStorageSourceNewFromBackingAbsolute(data->backing, &src)) != erc) {
fprintf(stderr, "expected return value '%d' actual '%d'\n", erc, rc);
return -1;
}
if (!src)
return 0;
if (src && !data->expect) {
fprintf(stderr, "parsing of backing store string '%s' should "
"have failed\n", data->backing);
return -1;
}
if (virDomainDiskSourceFormat(&buf, src, "source", 0, false, 0, true, NULL) < 0 ||
!(xml = virBufferContentAndReset(&buf))) {
fprintf(stderr, "failed to format disk source xml\n");
return -1;
}
if (STRNEQ(xml, data->expect)) {
fprintf(stderr, "\n backing store string '%s'\n"
"expected storage source xml:\n%s\n"
"actual storage source xml:\n%s\n",
data->backing, data->expect, xml);
return -1;
}
return 0;
}
| null | null | 200,934
|
151807476267028301989246359746793865740
| 43
|
virstoragetest: testBackingParse: Use VIR_DOMAIN_DEF_FORMAT_SECURE when formatting xml
We want to format even the secure information in tests.
Signed-off-by: Peter Krempa <[email protected]>
Reviewed-by: Erik Skultety <[email protected]>
|
other
|
linux
|
148ca04518070910739dfc4eeda765057856403d
| 1
|
static void rose_remove_neigh(struct rose_neigh *rose_neigh)
{
struct rose_neigh *s;
rose_stop_ftimer(rose_neigh);
rose_stop_t0timer(rose_neigh);
skb_queue_purge(&rose_neigh->queue);
if ((s = rose_neigh_list) == rose_neigh) {
rose_neigh_list = rose_neigh->next;
if (rose_neigh->ax25)
ax25_cb_put(rose_neigh->ax25);
kfree(rose_neigh->digipeat);
kfree(rose_neigh);
return;
}
while (s != NULL && s->next != NULL) {
if (s->next == rose_neigh) {
s->next = rose_neigh->next;
if (rose_neigh->ax25)
ax25_cb_put(rose_neigh->ax25);
kfree(rose_neigh->digipeat);
kfree(rose_neigh);
return;
}
s = s->next;
}
}
| null | null | 200,957
|
309659171338623815913030392054624006065
| 31
|
net: rose: fix UAF bug caused by rose_t0timer_expiry
There are UAF bugs caused by rose_t0timer_expiry(). The
root cause is that del_timer() could not stop the timer
handler that is running and there is no synchronization.
One of the race conditions is shown below:
(thread 1) | (thread 2)
| rose_device_event
| rose_rt_device_down
| rose_remove_neigh
rose_t0timer_expiry | rose_stop_t0timer(rose_neigh)
... | del_timer(&neigh->t0timer)
| kfree(rose_neigh) //[1]FREE
neigh->dce_mode //[2]USE |
The rose_neigh is deallocated in position [1] and use in
position [2].
The crash trace triggered by POC is like below:
BUG: KASAN: use-after-free in expire_timers+0x144/0x320
Write of size 8 at addr ffff888009b19658 by task swapper/0/0
...
Call Trace:
<IRQ>
dump_stack_lvl+0xbf/0xee
print_address_description+0x7b/0x440
print_report+0x101/0x230
? expire_timers+0x144/0x320
kasan_report+0xed/0x120
? expire_timers+0x144/0x320
expire_timers+0x144/0x320
__run_timers+0x3ff/0x4d0
run_timer_softirq+0x41/0x80
__do_softirq+0x233/0x544
...
This patch changes rose_stop_ftimer() and rose_stop_t0timer()
in rose_remove_neigh() to del_timer_sync() in order that the
timer handler could be finished before the resources such as
rose_neigh and so on are deallocated. As a result, the UAF
bugs could be mitigated.
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Duoming Zhou <[email protected]>
Link: https://lore.kernel.org/r/[email protected]
Signed-off-by: Jakub Kicinski <[email protected]>
|
other
|
vim
|
395bd1f6d3edc9f7edb5d1f2d7deaf5a9e3ab93c
| 1
|
get_visual_text(
cmdarg_T *cap,
char_u **pp, // return: start of selected text
int *lenp) // return: length of selected text
{
if (VIsual_mode != 'V')
unadjust_for_sel();
if (VIsual.lnum != curwin->w_cursor.lnum)
{
if (cap != NULL)
clearopbeep(cap->oap);
return FAIL;
}
if (VIsual_mode == 'V')
{
*pp = ml_get_curline();
*lenp = (int)STRLEN(*pp);
}
else
{
if (LT_POS(curwin->w_cursor, VIsual))
{
*pp = ml_get_pos(&curwin->w_cursor);
*lenp = VIsual.col - curwin->w_cursor.col + 1;
}
else
{
*pp = ml_get_pos(&VIsual);
*lenp = curwin->w_cursor.col - VIsual.col + 1;
}
if (**pp == NUL)
*lenp = 0;
if (has_mbyte && *lenp > 0)
// Correct the length to include all bytes of the last character.
*lenp += (*mb_ptr2len)(*pp + (*lenp - 1)) - 1;
}
reset_VIsual_and_resel();
return OK;
}
| null | null | 200,976
|
257613917374460380078341275128073985512
| 39
|
patch 8.2.4956: reading past end of line with "gf" in Visual block mode
Problem: Reading past end of line with "gf" in Visual block mode.
Solution: Do not include the NUL in the length.
|
other
|
linux
|
2a8859f373b0a86f0ece8ec8312607eacf12485d
| 1
|
static int FNAME(cmpxchg_gpte)(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
pt_element_t __user *ptep_user, unsigned index,
pt_element_t orig_pte, pt_element_t new_pte)
{
int npages;
pt_element_t ret;
pt_element_t *table;
struct page *page;
npages = get_user_pages_fast((unsigned long)ptep_user, 1, FOLL_WRITE, &page);
if (likely(npages == 1)) {
table = kmap_atomic(page);
ret = CMPXCHG(&table[index], orig_pte, new_pte);
kunmap_atomic(table);
kvm_release_page_dirty(page);
} else {
struct vm_area_struct *vma;
unsigned long vaddr = (unsigned long)ptep_user & PAGE_MASK;
unsigned long pfn;
unsigned long paddr;
mmap_read_lock(current->mm);
vma = find_vma_intersection(current->mm, vaddr, vaddr + PAGE_SIZE);
if (!vma || !(vma->vm_flags & VM_PFNMAP)) {
mmap_read_unlock(current->mm);
return -EFAULT;
}
pfn = ((vaddr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
paddr = pfn << PAGE_SHIFT;
table = memremap(paddr, PAGE_SIZE, MEMREMAP_WB);
if (!table) {
mmap_read_unlock(current->mm);
return -EFAULT;
}
ret = CMPXCHG(&table[index], orig_pte, new_pte);
memunmap(table);
mmap_read_unlock(current->mm);
}
return (ret != orig_pte);
}
| null | null | 201,006
|
242802409117904906138634378200961998106
| 42
|
KVM: x86/mmu: do compare-and-exchange of gPTE via the user address
FNAME(cmpxchg_gpte) is an inefficient mess. It is at least decent if it
can go through get_user_pages_fast(), but if it cannot then it tries to
use memremap(); that is not just terribly slow, it is also wrong because
it assumes that the VM_PFNMAP VMA is contiguous.
The right way to do it would be to do the same thing as
hva_to_pfn_remapped() does since commit add6a0cd1c5b ("KVM: MMU: try to
fix up page faults before giving up", 2016-07-05), using follow_pte()
and fixup_user_fault() to determine the correct address to use for
memremap(). To do this, one could for example extract hva_to_pfn()
for use outside virt/kvm/kvm_main.c. But really there is no reason to
do that either, because there is already a perfectly valid address to
do the cmpxchg() on, only it is a userspace address. That means doing
user_access_begin()/user_access_end() and writing the code in assembly
to handle exceptions correctly. Worse, the guest PTE can be 8-byte
even on i686 so there is the extra complication of using cmpxchg8b to
account for. But at least it is an efficient mess.
(Thanks to Linus for suggesting improvement on the inline assembly).
Reported-by: Qiuhao Li <[email protected]>
Reported-by: Gaoning Pan <[email protected]>
Reported-by: Yongkang Jia <[email protected]>
Reported-by: [email protected]
Debugged-by: Tadeusz Struk <[email protected]>
Tested-by: Maxim Levitsky <[email protected]>
Cc: [email protected]
Fixes: bd53cb35a3e9 ("X86/KVM: Handle PFNs outside of kernel reach when touching GPTEs")
Signed-off-by: Paolo Bonzini <[email protected]>
|
other
|
pjproject
|
560a1346f87aabe126509bb24930106dea292b00
| 1
|
static int print_media_desc(const pjmedia_sdp_media *m, char *buf, pj_size_t len)
{
char *p = buf;
char *end = buf+len;
unsigned i;
int printed;
/* check length for the "m=" line. */
if (len < (pj_size_t)m->desc.media.slen+m->desc.transport.slen+12+24) {
return -1;
}
*p++ = 'm'; /* m= */
*p++ = '=';
pj_memcpy(p, m->desc.media.ptr, m->desc.media.slen);
p += m->desc.media.slen;
*p++ = ' ';
printed = pj_utoa(m->desc.port, p);
p += printed;
if (m->desc.port_count > 1) {
*p++ = '/';
printed = pj_utoa(m->desc.port_count, p);
p += printed;
}
*p++ = ' ';
pj_memcpy(p, m->desc.transport.ptr, m->desc.transport.slen);
p += m->desc.transport.slen;
for (i=0; i<m->desc.fmt_count; ++i) {
*p++ = ' ';
pj_memcpy(p, m->desc.fmt[i].ptr, m->desc.fmt[i].slen);
p += m->desc.fmt[i].slen;
}
*p++ = '\r';
*p++ = '\n';
/* print connection info, if present. */
if (m->conn) {
printed = print_connection_info(m->conn, p, (int)(end-p));
if (printed < 0) {
return -1;
}
p += printed;
}
/* print optional bandwidth info. */
for (i=0; i<m->bandw_count; ++i) {
printed = (int)print_bandw(m->bandw[i], p, end-p);
if (printed < 0) {
return -1;
}
p += printed;
}
/* print attributes. */
for (i=0; i<m->attr_count; ++i) {
printed = (int)print_attr(m->attr[i], p, end-p);
if (printed < 0) {
return -1;
}
p += printed;
}
return (int)(p-buf);
}
| null | null | 201,007
|
133454390800145611389529375903489549180
| 63
|
Merge pull request from GHSA-f5qg-pqcg-765m
|
other
|
linux
|
a3727a8bac0a9e77c70820655fd8715523ba3db7
| 1
|
static int selinux_ptrace_traceme(struct task_struct *parent)
{
return avc_has_perm(&selinux_state,
task_sid_subj(parent), task_sid_obj(current),
SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
}
| null | null | 201,343
|
63175626254905822917570001000286668928
| 6
|
selinux,smack: fix subjective/objective credential use mixups
Jann Horn reported a problem with commit eb1231f73c4d ("selinux:
clarify task subjective and objective credentials") where some LSM
hooks were attempting to access the subjective credentials of a task
other than the current task. Generally speaking, it is not safe to
access another task's subjective credentials and doing so can cause
a number of problems.
Further, while looking into the problem, I realized that Smack was
suffering from a similar problem brought about by a similar commit
1fb057dcde11 ("smack: differentiate between subjective and objective
task credentials").
This patch addresses this problem by restoring the use of the task's
objective credentials in those cases where the task is other than the
current executing task. Not only does this resolve the problem
reported by Jann, it is arguably the correct thing to do in these
cases.
Cc: [email protected]
Fixes: eb1231f73c4d ("selinux: clarify task subjective and objective credentials")
Fixes: 1fb057dcde11 ("smack: differentiate between subjective and objective task credentials")
Reported-by: Jann Horn <[email protected]>
Acked-by: Eric W. Biederman <[email protected]>
Acked-by: Casey Schaufler <[email protected]>
Signed-off-by: Paul Moore <[email protected]>
|
other
|
wireless-drivers
|
8b51dc7291473093c821195c4b6af85fadedbc2f
| 1
|
static int rsi_init_usb_interface(struct rsi_hw *adapter,
struct usb_interface *pfunction)
{
struct rsi_91x_usbdev *rsi_dev;
int status;
rsi_dev = kzalloc(sizeof(*rsi_dev), GFP_KERNEL);
if (!rsi_dev)
return -ENOMEM;
adapter->rsi_dev = rsi_dev;
rsi_dev->usbdev = interface_to_usbdev(pfunction);
rsi_dev->priv = (void *)adapter;
if (rsi_find_bulk_in_and_out_endpoints(pfunction, adapter)) {
status = -EINVAL;
goto fail_eps;
}
adapter->device = &pfunction->dev;
usb_set_intfdata(pfunction, adapter);
rsi_dev->tx_buffer = kmalloc(2048, GFP_KERNEL);
if (!rsi_dev->tx_buffer) {
status = -ENOMEM;
goto fail_eps;
}
if (rsi_usb_init_rx(adapter)) {
rsi_dbg(ERR_ZONE, "Failed to init RX handle\n");
status = -ENOMEM;
goto fail_rx;
}
rsi_dev->tx_blk_size = 252;
adapter->block_size = rsi_dev->tx_blk_size;
/* Initializing function callbacks */
adapter->check_hw_queue_status = rsi_usb_check_queue_status;
adapter->determine_event_timeout = rsi_usb_event_timeout;
adapter->rsi_host_intf = RSI_HOST_INTF_USB;
adapter->host_intf_ops = &usb_host_intf_ops;
#ifdef CONFIG_RSI_DEBUGFS
/* In USB, one less than the MAX_DEBUGFS_ENTRIES entries is required */
adapter->num_debugfs_entries = (MAX_DEBUGFS_ENTRIES - 1);
#endif
rsi_dbg(INIT_ZONE, "%s: Enabled the interface\n", __func__);
return 0;
fail_rx:
kfree(rsi_dev->tx_buffer);
fail_eps:
kfree(rsi_dev);
return status;
}
| null | null | 201,353
|
280465873125983838963359867810805220918
| 59
|
rsi: fix a double free bug in rsi_91x_deinit()
`dev` (struct rsi_91x_usbdev *) field of adapter
(struct rsi_91x_usbdev *) is allocated and initialized in
`rsi_init_usb_interface`. If any error is detected in information
read from the device side, `rsi_init_usb_interface` will be
freed. However, in the higher level error handling code in
`rsi_probe`, if error is detected, `rsi_91x_deinit` is called
again, in which `dev` will be freed again, resulting double free.
This patch fixes the double free by removing the free operation on
`dev` in `rsi_init_usb_interface`, because `rsi_91x_deinit` is also
used in `rsi_disconnect`, in that code path, the `dev` field is not
(and thus needs to be) freed.
This bug was found in v4.19, but is also present in the latest version
of kernel. Fixes CVE-2019-15504.
Reported-by: Hui Peng <[email protected]>
Reported-by: Mathias Payer <[email protected]>
Signed-off-by: Hui Peng <[email protected]>
Reviewed-by: Guenter Roeck <[email protected]>
Signed-off-by: Kalle Valo <[email protected]>
|
other
|
gerbv
|
672214abb47a802fc000125996e6e0a46c623a4e
| 1
|
drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,
gerbv_image_t *image, ssize_t file_line)
{
int tool_num;
gboolean done = FALSE;
int temp;
double size;
gerbv_drill_stats_t *stats = image->drill_stats;
gerbv_aperture_t *apert;
gchar *tmps;
gchar *string;
dprintf("---> entering %s()...\n", __FUNCTION__);
/* Sneak a peek at what's hiding after the 'T'. Ugly fix for
broken headers from Orcad, which is crap */
temp = gerb_fgetc(fd);
dprintf(" Found a char '%s' (0x%02x) after the T\n",
gerbv_escape_char(temp), temp);
/* might be a tool tool change stop switch on/off*/
if((temp == 'C') && ((fd->ptr + 2) < fd->datalen)){
if(gerb_fgetc(fd) == 'S'){
if (gerb_fgetc(fd) == 'T' ){
fd->ptr -= 4;
tmps = get_line(fd++);
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
_("Tool change stop switch found \"%s\" "
"at line %ld in file \"%s\""),
tmps, file_line, fd->filename);
g_free (tmps);
return -1;
}
gerb_ungetc(fd);
}
gerb_ungetc(fd);
}
if( !(isdigit(temp) != 0 || temp == '+' || temp =='-') ) {
if(temp != EOF) {
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
_("OrCAD bug: Junk text found in place of tool definition"));
tmps = get_line(fd);
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
_("Junk text \"%s\" "
"at line %ld in file \"%s\""),
tmps, file_line, fd->filename);
g_free (tmps);
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
_("Ignoring junk text"));
}
return -1;
}
gerb_ungetc(fd);
tool_num = (int) gerb_fgetint(fd, NULL);
dprintf (" Handling tool T%d at line %ld\n", tool_num, file_line);
if (tool_num == 0)
return tool_num; /* T00 is a command to unload the drill */
if (tool_num < TOOL_MIN || tool_num >= TOOL_MAX) {
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
_("Out of bounds drill number %d "
"at line %ld in file \"%s\""),
tool_num, file_line, fd->filename);
}
/* Set the current tool to the correct one */
state->current_tool = tool_num;
apert = image->aperture[tool_num];
/* Check for a size definition */
temp = gerb_fgetc(fd);
/* This bit of code looks for a tool definition by scanning for strings
* of form TxxC, TxxF, TxxS. */
while (!done) {
switch((char)temp) {
case 'C':
size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals);
dprintf (" Read a size of %g\n", size);
if (state->unit == GERBV_UNIT_MM) {
size /= 25.4;
} else if(size >= 4.0) {
/* If the drill size is >= 4 inches, assume that this
must be wrong and that the units are mils.
The limit being 4 inches is because the smallest drill
I've ever seen used is 0,3mm(about 12mil). Half of that
seemed a bit too small a margin, so a third it is */
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
_("Read a drill of diameter %g inches "
"at line %ld in file \"%s\""),
size, file_line, fd->filename);
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
_("Assuming units are mils"));
size /= 1000.0;
}
if (size <= 0. || size >= 10000.) {
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
_("Unreasonable drill size %g found for drill %d "
"at line %ld in file \"%s\""),
size, tool_num, file_line, fd->filename);
} else {
if (apert != NULL) {
/* allow a redefine of a tool only if the new definition is exactly the same.
* This avoid lots of spurious complaints with the output of some cad
* tools while keeping complaints if there is a true problem
*/
if (apert->parameter[0] != size
|| apert->type != GERBV_APTYPE_CIRCLE
|| apert->nuf_parameters != 1
|| apert->unit != GERBV_UNIT_INCH) {
gerbv_stats_printf(stats->error_list,
GERBV_MESSAGE_ERROR, -1,
_("Found redefinition of drill %d "
"at line %ld in file \"%s\""),
tool_num, file_line, fd->filename);
}
} else {
apert = image->aperture[tool_num] =
g_new0(gerbv_aperture_t, 1);
if (apert == NULL)
GERB_FATAL_ERROR("malloc tool failed in %s()",
__FUNCTION__);
/* There's really no way of knowing what unit the tools
are defined in without sneaking a peek in the rest of
the file first. That's done in drill_guess_format() */
apert->parameter[0] = size;
apert->type = GERBV_APTYPE_CIRCLE;
apert->nuf_parameters = 1;
apert->unit = GERBV_UNIT_INCH;
}
}
/* Add the tool whose definition we just found into the list
* of tools for this layer used to generate statistics. */
stats = image->drill_stats;
string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch")));
drill_stats_add_to_drill_list(stats->drill_list,
tool_num,
state->unit == GERBV_UNIT_MM ? size*25.4 : size,
string);
g_free(string);
break;
case 'F':
case 'S' :
/* Silently ignored. They're not important. */
gerb_fgetint(fd, NULL);
break;
default:
/* Stop when finding anything but what's expected
(and put it back) */
gerb_ungetc(fd);
done = TRUE;
break;
} /* switch((char)temp) */
temp = gerb_fgetc(fd);
if (EOF == temp) {
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
_("Unexpected EOF encountered in header of "
"drill file \"%s\""), fd->filename);
/* Restore new line character for processing */
if ('\n' == temp || '\r' == temp)
gerb_ungetc(fd);
}
} /* while(!done) */ /* Done looking at tool definitions */
/* Catch the tools that aren't defined.
This isn't strictly a good thing, but at least something is shown */
if (apert == NULL) {
double dia;
apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1);
if (apert == NULL)
GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__);
/* See if we have the tool table */
dia = gerbv_get_tool_diameter(tool_num);
if (dia <= 0) {
/*
* There is no tool. So go out and make some.
* This size calculation is, of course, totally bogus.
*/
dia = (double)(16 + 8 * tool_num) / 1000;
/*
* Oooh, this is sooo ugly. But some CAD systems seem to always
* use T00 at the end of the file while others that don't have
* tool definitions inside the file never seem to use T00 at all.
*/
if (tool_num != 0) {
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
_("Tool %02d used without being defined "
"at line %ld in file \"%s\""),
tool_num, file_line, fd->filename);
gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
_("Setting a default size of %g\""), dia);
}
}
apert->type = GERBV_APTYPE_CIRCLE;
apert->nuf_parameters = 1;
apert->parameter[0] = dia;
/* Add the tool whose definition we just found into the list
* of tools for this layer used to generate statistics. */
if (tool_num != 0) { /* Only add non-zero tool nums.
* Zero = unload command. */
stats = image->drill_stats;
string = g_strdup_printf("%s",
(state->unit == GERBV_UNIT_MM ? _("mm") : _("inch")));
drill_stats_add_to_drill_list(stats->drill_list,
tool_num,
state->unit == GERBV_UNIT_MM ? dia*25.4 : dia,
string);
g_free(string);
}
} /* if(image->aperture[tool_num] == NULL) */
dprintf("<---- ...leaving %s()\n", __FUNCTION__);
return tool_num;
} /* drill_parse_T_code() */
| null | null | 201,382
|
112903329744372590974166759703865752022
| 233
|
Add test to demonstrate buffer overrun
|
other
|
vim
|
34f8117dec685ace52cd9e578e2729db278163fc
| 1
|
ga_concat_shorten_esc(garray_T *gap, char_u *str)
{
char_u *p;
char_u *s;
int c;
int clen;
char_u buf[NUMBUFLEN];
int same_len;
if (str == NULL)
{
ga_concat(gap, (char_u *)"NULL");
return;
}
for (p = str; *p != NUL; ++p)
{
same_len = 1;
s = p;
c = mb_ptr2char_adv(&s);
clen = s - p;
while (*s != NUL && c == mb_ptr2char(s))
{
++same_len;
s += clen;
}
if (same_len > 20)
{
ga_concat(gap, (char_u *)"\\[");
ga_concat_esc(gap, p, clen);
ga_concat(gap, (char_u *)" occurs ");
vim_snprintf((char *)buf, NUMBUFLEN, "%d", same_len);
ga_concat(gap, buf);
ga_concat(gap, (char_u *)" times]");
p = s - 1;
}
else
ga_concat_esc(gap, p, clen);
}
}
| null | null | 201,384
|
326862570358098253942059677394751984490
| 40
|
patch 8.2.4397: crash when using many composing characters in error message
Problem: Crash when using many composing characters in error message.
Solution: Use mb_cptr2char_adv() instead of mb_ptr2char_adv().
|
other
|
ImageMagick6
|
e6ea5876e0228165ee3abc6e959aa174cee06680
| 1
|
static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define MonoColorType 1
#define RGBColorType 3
char
property[MaxTextExtent];
CINInfo
cin;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
offset;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
ssize_t
i;
PixelPacket
*q;
size_t
extent,
length;
ssize_t
count,
y;
unsigned char
magick[4],
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
File information.
*/
offset=0;
count=ReadBlob(image,4,magick);
offset+=count;
if ((count != 4) ||
((LocaleNCompare((char *) magick,"\200\052\137\327",4) != 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
memset(&cin,0,sizeof(cin));
image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) &&
(magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian;
cin.file.image_offset=ReadBlobLong(image);
offset+=4;
cin.file.generic_length=ReadBlobLong(image);
offset+=4;
cin.file.industry_length=ReadBlobLong(image);
offset+=4;
cin.file.user_length=ReadBlobLong(image);
offset+=4;
cin.file.file_size=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *)
cin.file.version);
(void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version));
(void) SetImageProperty(image,"dpx:file.version",property);
offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *)
cin.file.filename);
(void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename));
(void) SetImageProperty(image,"dpx:file.filename",property);
offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *)
cin.file.create_date);
(void) CopyMagickString(property,cin.file.create_date,
sizeof(cin.file.create_date));
(void) SetImageProperty(image,"dpx:file.create_date",property);
offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *)
cin.file.create_time);
(void) CopyMagickString(property,cin.file.create_time,
sizeof(cin.file.create_time));
(void) SetImageProperty(image,"dpx:file.create_time",property);
offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *)
cin.file.reserve);
/*
Image information.
*/
cin.image.orientation=(unsigned char) ReadBlobByte(image);
offset++;
if (cin.image.orientation != (unsigned char) (~0))
(void) FormatImageProperty(image,"dpx:image.orientation","%d",
cin.image.orientation);
switch (cin.image.orientation)
{
default:
case 0: image->orientation=TopLeftOrientation; break;
case 1: image->orientation=TopRightOrientation; break;
case 2: image->orientation=BottomLeftOrientation; break;
case 3: image->orientation=BottomRightOrientation; break;
case 4: image->orientation=LeftTopOrientation; break;
case 5: image->orientation=RightTopOrientation; break;
case 6: image->orientation=LeftBottomOrientation; break;
case 7: image->orientation=RightBottomOrientation; break;
}
cin.image.number_channels=(unsigned char) ReadBlobByte(image);
offset++;
offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *)
cin.image.reserve1);
for (i=0; i < 8; i++)
{
cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image);
offset++;
cin.image.channel[i].pixels_per_line=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].lines_per_image=ReadBlobLong(image);
offset+=4;
cin.image.channel[i].min_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].min_quantity=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_data=ReadBlobFloat(image);
offset+=4;
cin.image.channel[i].max_quantity=ReadBlobFloat(image);
offset+=4;
}
cin.image.white_point[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse)
image->chromaticity.white_point.x=cin.image.white_point[0];
cin.image.white_point[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse)
image->chromaticity.white_point.y=cin.image.white_point[1];
cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0];
cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1];
cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0];
cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1];
cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse)
image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0];
cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse)
image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1];
offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *)
cin.image.label);
(void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label));
(void) SetImageProperty(image,"dpx:image.label",property);
offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *)
cin.image.reserve);
/*
Image data format information.
*/
cin.data_format.interleave=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.packing=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sign=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.sense=(unsigned char) ReadBlobByte(image);
offset++;
cin.data_format.line_pad=ReadBlobLong(image);
offset+=4;
cin.data_format.channel_pad=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *)
cin.data_format.reserve);
/*
Image origination information.
*/
cin.origination.x_offset=ReadBlobSignedLong(image);
offset+=4;
if ((size_t) cin.origination.x_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.x_offset","%.20g",
(double) cin.origination.x_offset);
cin.origination.y_offset=(ssize_t) ReadBlobLong(image);
offset+=4;
if ((size_t) cin.origination.y_offset != ~0UL)
(void) FormatImageProperty(image,"dpx:origination.y_offset","%.20g",
(double) cin.origination.y_offset);
offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *)
cin.origination.filename);
(void) CopyMagickString(property,cin.origination.filename,
sizeof(cin.origination.filename));
(void) SetImageProperty(image,"dpx:origination.filename",property);
offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *)
cin.origination.create_date);
(void) CopyMagickString(property,cin.origination.create_date,
sizeof(cin.origination.create_date));
(void) SetImageProperty(image,"dpx:origination.create_date",property);
offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *)
cin.origination.create_time);
(void) CopyMagickString(property,cin.origination.create_time,
sizeof(cin.origination.create_time));
(void) SetImageProperty(image,"dpx:origination.create_time",property);
offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *)
cin.origination.device);
(void) CopyMagickString(property,cin.origination.device,
sizeof(cin.origination.device));
(void) SetImageProperty(image,"dpx:origination.device",property);
offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *)
cin.origination.model);
(void) CopyMagickString(property,cin.origination.model,
sizeof(cin.origination.model));
(void) SetImageProperty(image,"dpx:origination.model",property);
(void) memset(cin.origination.serial,0,
sizeof(cin.origination.serial));
offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *)
cin.origination.serial);
(void) CopyMagickString(property,cin.origination.serial,
sizeof(cin.origination.serial));
(void) SetImageProperty(image,"dpx:origination.serial",property);
cin.origination.x_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.y_pitch=ReadBlobFloat(image);
offset+=4;
cin.origination.gamma=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.origination.gamma) != MagickFalse)
image->gamma=cin.origination.gamma;
offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *)
cin.origination.reserve);
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
int
c;
/*
Image film information.
*/
cin.film.id=ReadBlobByte(image);
offset++;
c=cin.film.id;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.id","%d",cin.film.id);
cin.film.type=ReadBlobByte(image);
offset++;
c=cin.film.type;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.type","%d",cin.film.type);
cin.film.offset=ReadBlobByte(image);
offset++;
c=cin.film.offset;
if (c != ~0)
(void) FormatImageProperty(image,"dpx:film.offset","%d",
cin.film.offset);
cin.film.reserve1=ReadBlobByte(image);
offset++;
cin.film.prefix=ReadBlobLong(image);
offset+=4;
if (cin.film.prefix != ~0UL)
(void) FormatImageProperty(image,"dpx:film.prefix","%.20g",(double)
cin.film.prefix);
cin.film.count=ReadBlobLong(image);
offset+=4;
offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *)
cin.film.format);
(void) CopyMagickString(property,cin.film.format,
sizeof(cin.film.format));
(void) SetImageProperty(image,"dpx:film.format",property);
cin.film.frame_position=ReadBlobLong(image);
offset+=4;
if (cin.film.frame_position != ~0UL)
(void) FormatImageProperty(image,"dpx:film.frame_position","%.20g",
(double) cin.film.frame_position);
cin.film.frame_rate=ReadBlobFloat(image);
offset+=4;
if (IsFloatDefined(cin.film.frame_rate) != MagickFalse)
(void) FormatImageProperty(image,"dpx:film.frame_rate","%g",
cin.film.frame_rate);
offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *)
cin.film.frame_id);
(void) CopyMagickString(property,cin.film.frame_id,
sizeof(cin.film.frame_id));
(void) SetImageProperty(image,"dpx:film.frame_id",property);
offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *)
cin.film.slate_info);
(void) CopyMagickString(property,cin.film.slate_info,
sizeof(cin.film.slate_info));
(void) SetImageProperty(image,"dpx:film.slate_info",property);
offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *)
cin.film.reserve);
}
if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0))
{
StringInfo
*profile;
/*
User defined data.
*/
if (cin.file.user_length > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
profile=BlobToStringInfo((const void *) NULL,cin.file.user_length);
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
offset+=ReadBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) SetImageProfile(image,"dpx:user.data",profile);
profile=DestroyStringInfo(profile);
}
image->depth=cin.image.channel[0].bits_per_pixel;
image->columns=cin.image.channel[0].pixels_per_line;
image->rows=cin.image.channel[0].lines_per_image;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
if (((MagickSizeType) image->columns*image->rows/8) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
if (offset < (MagickOffsetType) cin.file.image_offset)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image);
/*
Convert CIN raster image to pixel packets.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
SetQuantumQuantum(quantum_info,32);
SetQuantumPack(quantum_info,MagickFalse);
quantum_type=RGBQuantum;
extent=GetQuantumExtent(image,quantum_info,quantum_type);
(void) extent;
length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue);
if (cin.image.number_channels == 1)
{
quantum_type=GrayQuantum;
length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue);
}
status=SetQuantumPad(image,quantum_info,0);
pixels=GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
const void
*stream;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
stream=ReadBlobStream(image,length,pixels,&count);
if (count != (ssize_t) length)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,(unsigned char *) stream,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
SetImageColorspace(image,LogColorspace);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| null | null | 201,451
|
66454786120255316890965543442280788990
| 418
|
https://github.com/ImageMagick/ImageMagick/issues/4988
|
other
|
linux
|
b49a0e69a7b1a68c8d3f64097d06dabb770fec96
| 1
|
static int aspeed_lpc_ctrl_mmap(struct file *file, struct vm_area_struct *vma)
{
struct aspeed_lpc_ctrl *lpc_ctrl = file_aspeed_lpc_ctrl(file);
unsigned long vsize = vma->vm_end - vma->vm_start;
pgprot_t prot = vma->vm_page_prot;
if (vma->vm_pgoff + vsize > lpc_ctrl->mem_base + lpc_ctrl->mem_size)
return -EINVAL;
/* ast2400/2500 AHB accesses are not cache coherent */
prot = pgprot_noncached(prot);
if (remap_pfn_range(vma, vma->vm_start,
(lpc_ctrl->mem_base >> PAGE_SHIFT) + vma->vm_pgoff,
vsize, prot))
return -EAGAIN;
return 0;
}
| null | null | 201,794
|
309099081422887809703549687415049166224
| 19
|
soc: aspeed: lpc-ctrl: Fix boundary check for mmap
The check mixes pages (vm_pgoff) with bytes (vm_start, vm_end) on one
side of the comparison, and uses resource address (rather than just the
resource size) on the other side of the comparison.
This can allow malicious userspace to easily bypass the boundary check and
map pages that are located outside memory-region reserved by the driver.
Fixes: 6c4e97678501 ("drivers/misc: Add Aspeed LPC control driver")
Cc: [email protected]
Signed-off-by: Iwona Winiarska <[email protected]>
Reviewed-by: Andrew Jeffery <[email protected]>
Tested-by: Andrew Jeffery <[email protected]>
Reviewed-by: Joel Stanley <[email protected]>
Signed-off-by: Joel Stanley <[email protected]>
|
other
|
gnutls
|
20a98e817713764b9df5306286091df1b61190d9
| 1
|
_gnutls_server_select_suite(gnutls_session_t session, uint8_t * data,
unsigned int datalen)
{
int ret;
unsigned int i, j, cipher_suites_size;
size_t pk_algos_size;
uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];
int retval;
gnutls_pk_algorithm_t pk_algos[MAX_ALGOS]; /* will hold the pk algorithms
* supported by the peer.
*/
for (i = 0; i < datalen; i += 2) {
/* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */
if (session->internals.priorities.sr != SR_DISABLED &&
data[i] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR &&
data[i + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) {
_gnutls_handshake_log
("HSK[%p]: Received safe renegotiation CS\n",
session);
retval = _gnutls_ext_sr_recv_cs(session);
if (retval < 0) {
gnutls_assert();
return retval;
}
}
/* TLS_FALLBACK_SCSV */
if (data[i] == GNUTLS_FALLBACK_SCSV_MAJOR &&
data[i + 1] == GNUTLS_FALLBACK_SCSV_MINOR) {
_gnutls_handshake_log
("HSK[%p]: Received fallback CS\n",
session);
if (gnutls_protocol_get_version(session) !=
GNUTLS_TLS_VERSION_MAX)
return GNUTLS_E_INAPPROPRIATE_FALLBACK;
}
}
pk_algos_size = MAX_ALGOS;
ret =
server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos,
&pk_algos_size);
if (ret < 0)
return gnutls_assert_val(ret);
ret =
_gnutls_supported_ciphersuites(session, cipher_suites,
sizeof(cipher_suites));
if (ret < 0)
return gnutls_assert_val(ret);
cipher_suites_size = ret;
/* Here we remove any ciphersuite that does not conform
* the certificate requested, or to the
* authentication requested (e.g. SRP).
*/
ret =
_gnutls_remove_unwanted_ciphersuites(session, cipher_suites,
cipher_suites_size,
pk_algos, pk_algos_size);
if (ret <= 0) {
gnutls_assert();
if (ret < 0)
return ret;
else
return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
}
cipher_suites_size = ret;
/* Data length should be zero mod 2 since
* every ciphersuite is 2 bytes. (this check is needed
* see below).
*/
if (datalen % 2 != 0) {
gnutls_assert();
return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
}
memset(session->security_parameters.cipher_suite, 0, 2);
retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;
_gnutls_handshake_log
("HSK[%p]: Requested cipher suites[size: %d]: \n", session,
(int) datalen);
if (session->internals.priorities.server_precedence == 0) {
for (j = 0; j < datalen; j += 2) {
_gnutls_handshake_log("\t0x%.2x, 0x%.2x %s\n",
data[j], data[j + 1],
_gnutls_cipher_suite_get_name
(&data[j]));
for (i = 0; i < cipher_suites_size; i += 2) {
if (memcmp(&cipher_suites[i], &data[j], 2)
== 0) {
_gnutls_handshake_log
("HSK[%p]: Selected cipher suite: %s\n",
session,
_gnutls_cipher_suite_get_name
(&data[j]));
memcpy(session->
security_parameters.
cipher_suite,
&cipher_suites[i], 2);
_gnutls_epoch_set_cipher_suite
(session, EPOCH_NEXT,
session->security_parameters.
cipher_suite);
retval = 0;
goto finish;
}
}
}
} else { /* server selects */
for (i = 0; i < cipher_suites_size; i += 2) {
for (j = 0; j < datalen; j += 2) {
if (memcmp(&cipher_suites[i], &data[j], 2)
== 0) {
_gnutls_handshake_log
("HSK[%p]: Selected cipher suite: %s\n",
session,
_gnutls_cipher_suite_get_name
(&data[j]));
memcpy(session->
security_parameters.
cipher_suite,
&cipher_suites[i], 2);
_gnutls_epoch_set_cipher_suite
(session, EPOCH_NEXT,
session->security_parameters.
cipher_suite);
retval = 0;
goto finish;
}
}
}
}
finish:
if (retval != 0) {
gnutls_assert();
return retval;
}
/* check if the credentials (username, public key etc.) are ok
*/
if (_gnutls_get_kx_cred
(session,
_gnutls_cipher_suite_get_kx_algo(session->security_parameters.
cipher_suite)) == NULL) {
gnutls_assert();
return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
}
/* set the mod_auth_st to the appropriate struct
* according to the KX algorithm. This is needed since all the
* handshake functions are read from there;
*/
session->internals.auth_struct =
_gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo
(session->security_parameters.
cipher_suite));
if (session->internals.auth_struct == NULL) {
_gnutls_handshake_log
("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
session);
gnutls_assert();
return GNUTLS_E_INTERNAL_ERROR;
}
return 0;
}
| null | null | 201,872
|
142548387300837609415546667828512694218
| 184
|
handshake: check inappropriate fallback against the configured max version
That allows to operate on a server which is explicitly configured to
utilize earlier than TLS 1.2 versions.
|
other
|
vim
|
b55986c52d4cd88a22d0b0b0e8a79547ba13e1d5
| 1
|
regmatch(
char_u *scan, // Current node.
proftime_T *tm UNUSED, // timeout limit or NULL
int *timed_out UNUSED) // flag set on timeout or NULL
{
char_u *next; // Next node.
int op;
int c;
regitem_T *rp;
int no;
int status; // one of the RA_ values:
#ifdef FEAT_RELTIME
int tm_count = 0;
#endif
// Make "regstack" and "backpos" empty. They are allocated and freed in
// bt_regexec_both() to reduce malloc()/free() calls.
regstack.ga_len = 0;
backpos.ga_len = 0;
// Repeat until "regstack" is empty.
for (;;)
{
// Some patterns may take a long time to match, e.g., "\([a-z]\+\)\+Q".
// Allow interrupting them with CTRL-C.
fast_breakcheck();
#ifdef DEBUG
if (scan != NULL && regnarrate)
{
mch_errmsg((char *)regprop(scan));
mch_errmsg("(\n");
}
#endif
// Repeat for items that can be matched sequentially, without using the
// regstack.
for (;;)
{
if (got_int || scan == NULL)
{
status = RA_FAIL;
break;
}
#ifdef FEAT_RELTIME
// Check for timeout once in a 100 times to avoid overhead.
if (tm != NULL && ++tm_count == 100)
{
tm_count = 0;
if (profile_passed_limit(tm))
{
if (timed_out != NULL)
*timed_out = TRUE;
status = RA_FAIL;
break;
}
}
#endif
status = RA_CONT;
#ifdef DEBUG
if (regnarrate)
{
mch_errmsg((char *)regprop(scan));
mch_errmsg("...\n");
# ifdef FEAT_SYN_HL
if (re_extmatch_in != NULL)
{
int i;
mch_errmsg(_("External submatches:\n"));
for (i = 0; i < NSUBEXP; i++)
{
mch_errmsg(" \"");
if (re_extmatch_in->matches[i] != NULL)
mch_errmsg((char *)re_extmatch_in->matches[i]);
mch_errmsg("\"\n");
}
}
# endif
}
#endif
next = regnext(scan);
op = OP(scan);
// Check for character class with NL added.
if (!rex.reg_line_lbr && WITH_NL(op) && REG_MULTI
&& *rex.input == NUL && rex.lnum <= rex.reg_maxline)
{
reg_nextline();
}
else if (rex.reg_line_lbr && WITH_NL(op) && *rex.input == '\n')
{
ADVANCE_REGINPUT();
}
else
{
if (WITH_NL(op))
op -= ADD_NL;
if (has_mbyte)
c = (*mb_ptr2char)(rex.input);
else
c = *rex.input;
switch (op)
{
case BOL:
if (rex.input != rex.line)
status = RA_NOMATCH;
break;
case EOL:
if (c != NUL)
status = RA_NOMATCH;
break;
case RE_BOF:
// We're not at the beginning of the file when below the first
// line where we started, not at the start of the line or we
// didn't start at the first line of the buffer.
if (rex.lnum != 0 || rex.input != rex.line
|| (REG_MULTI && rex.reg_firstlnum > 1))
status = RA_NOMATCH;
break;
case RE_EOF:
if (rex.lnum != rex.reg_maxline || c != NUL)
status = RA_NOMATCH;
break;
case CURSOR:
// Check if the buffer is in a window and compare the
// rex.reg_win->w_cursor position to the match position.
if (rex.reg_win == NULL
|| (rex.lnum + rex.reg_firstlnum
!= rex.reg_win->w_cursor.lnum)
|| ((colnr_T)(rex.input - rex.line)
!= rex.reg_win->w_cursor.col))
status = RA_NOMATCH;
break;
case RE_MARK:
// Compare the mark position to the match position.
{
int mark = OPERAND(scan)[0];
int cmp = OPERAND(scan)[1];
pos_T *pos;
pos = getmark_buf(rex.reg_buf, mark, FALSE);
if (pos == NULL // mark doesn't exist
|| pos->lnum <= 0) // mark isn't set in reg_buf
{
status = RA_NOMATCH;
}
else
{
colnr_T pos_col = pos->lnum == rex.lnum + rex.reg_firstlnum
&& pos->col == MAXCOL
? (colnr_T)STRLEN(reg_getline(
pos->lnum - rex.reg_firstlnum))
: pos->col;
if ((pos->lnum == rex.lnum + rex.reg_firstlnum
? (pos_col == (colnr_T)(rex.input - rex.line)
? (cmp == '<' || cmp == '>')
: (pos_col < (colnr_T)(rex.input - rex.line)
? cmp != '>'
: cmp != '<'))
: (pos->lnum < rex.lnum + rex.reg_firstlnum
? cmp != '>'
: cmp != '<')))
status = RA_NOMATCH;
}
}
break;
case RE_VISUAL:
if (!reg_match_visual())
status = RA_NOMATCH;
break;
case RE_LNUM:
if (!REG_MULTI || !re_num_cmp((long_u)(rex.lnum + rex.reg_firstlnum),
scan))
status = RA_NOMATCH;
break;
case RE_COL:
if (!re_num_cmp((long_u)(rex.input - rex.line) + 1, scan))
status = RA_NOMATCH;
break;
case RE_VCOL:
if (!re_num_cmp((long_u)win_linetabsize(
rex.reg_win == NULL ? curwin : rex.reg_win,
rex.line, (colnr_T)(rex.input - rex.line)) + 1, scan))
status = RA_NOMATCH;
break;
case BOW: // \<word; rex.input points to w
if (c == NUL) // Can't match at end of line
status = RA_NOMATCH;
else if (has_mbyte)
{
int this_class;
// Get class of current and previous char (if it exists).
this_class = mb_get_class_buf(rex.input, rex.reg_buf);
if (this_class <= 1)
status = RA_NOMATCH; // not on a word at all
else if (reg_prev_class() == this_class)
status = RA_NOMATCH; // previous char is in same word
}
else
{
if (!vim_iswordc_buf(c, rex.reg_buf) || (rex.input > rex.line
&& vim_iswordc_buf(rex.input[-1], rex.reg_buf)))
status = RA_NOMATCH;
}
break;
case EOW: // word\>; rex.input points after d
if (rex.input == rex.line) // Can't match at start of line
status = RA_NOMATCH;
else if (has_mbyte)
{
int this_class, prev_class;
// Get class of current and previous char (if it exists).
this_class = mb_get_class_buf(rex.input, rex.reg_buf);
prev_class = reg_prev_class();
if (this_class == prev_class
|| prev_class == 0 || prev_class == 1)
status = RA_NOMATCH;
}
else
{
if (!vim_iswordc_buf(rex.input[-1], rex.reg_buf)
|| (rex.input[0] != NUL
&& vim_iswordc_buf(c, rex.reg_buf)))
status = RA_NOMATCH;
}
break; // Matched with EOW
case ANY:
// ANY does not match new lines.
if (c == NUL)
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case IDENT:
if (!vim_isIDc(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SIDENT:
if (VIM_ISDIGIT(*rex.input) || !vim_isIDc(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case KWORD:
if (!vim_iswordp_buf(rex.input, rex.reg_buf))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SKWORD:
if (VIM_ISDIGIT(*rex.input)
|| !vim_iswordp_buf(rex.input, rex.reg_buf))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case FNAME:
if (!vim_isfilec(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SFNAME:
if (VIM_ISDIGIT(*rex.input) || !vim_isfilec(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case PRINT:
if (!vim_isprintc(PTR2CHAR(rex.input)))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case SPRINT:
if (VIM_ISDIGIT(*rex.input) || !vim_isprintc(PTR2CHAR(rex.input)))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case WHITE:
if (!VIM_ISWHITE(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NWHITE:
if (c == NUL || VIM_ISWHITE(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case DIGIT:
if (!ri_digit(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NDIGIT:
if (c == NUL || ri_digit(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case HEX:
if (!ri_hex(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NHEX:
if (c == NUL || ri_hex(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case OCTAL:
if (!ri_octal(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NOCTAL:
if (c == NUL || ri_octal(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case WORD:
if (!ri_word(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NWORD:
if (c == NUL || ri_word(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case HEAD:
if (!ri_head(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NHEAD:
if (c == NUL || ri_head(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case ALPHA:
if (!ri_alpha(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NALPHA:
if (c == NUL || ri_alpha(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case LOWER:
if (!ri_lower(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NLOWER:
if (c == NUL || ri_lower(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case UPPER:
if (!ri_upper(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case NUPPER:
if (c == NUL || ri_upper(c))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case EXACTLY:
{
int len;
char_u *opnd;
opnd = OPERAND(scan);
// Inline the first byte, for speed.
if (*opnd != *rex.input
&& (!rex.reg_ic
|| (!enc_utf8
&& MB_TOLOWER(*opnd) != MB_TOLOWER(*rex.input))))
status = RA_NOMATCH;
else if (*opnd == NUL)
{
// match empty string always works; happens when "~" is
// empty.
}
else
{
if (opnd[1] == NUL && !(enc_utf8 && rex.reg_ic))
{
len = 1; // matched a single byte above
}
else
{
// Need to match first byte again for multi-byte.
len = (int)STRLEN(opnd);
if (cstrncmp(opnd, rex.input, &len) != 0)
status = RA_NOMATCH;
}
// Check for following composing character, unless %C
// follows (skips over all composing chars).
if (status != RA_NOMATCH
&& enc_utf8
&& UTF_COMPOSINGLIKE(rex.input, rex.input + len)
&& !rex.reg_icombine
&& OP(next) != RE_COMPOSING)
{
// raaron: This code makes a composing character get
// ignored, which is the correct behavior (sometimes)
// for voweled Hebrew texts.
status = RA_NOMATCH;
}
if (status != RA_NOMATCH)
rex.input += len;
}
}
break;
case ANYOF:
case ANYBUT:
if (c == NUL)
status = RA_NOMATCH;
else if ((cstrchr(OPERAND(scan), c) == NULL) == (op == ANYOF))
status = RA_NOMATCH;
else
ADVANCE_REGINPUT();
break;
case MULTIBYTECODE:
if (has_mbyte)
{
int i, len;
char_u *opnd;
int opndc = 0, inpc;
opnd = OPERAND(scan);
// Safety check (just in case 'encoding' was changed since
// compiling the program).
if ((len = (*mb_ptr2len)(opnd)) < 2)
{
status = RA_NOMATCH;
break;
}
if (enc_utf8)
opndc = utf_ptr2char(opnd);
if (enc_utf8 && utf_iscomposing(opndc))
{
// When only a composing char is given match at any
// position where that composing char appears.
status = RA_NOMATCH;
for (i = 0; rex.input[i] != NUL;
i += utf_ptr2len(rex.input + i))
{
inpc = utf_ptr2char(rex.input + i);
if (!utf_iscomposing(inpc))
{
if (i > 0)
break;
}
else if (opndc == inpc)
{
// Include all following composing chars.
len = i + utfc_ptr2len(rex.input + i);
status = RA_MATCH;
break;
}
}
}
else
for (i = 0; i < len; ++i)
if (opnd[i] != rex.input[i])
{
status = RA_NOMATCH;
break;
}
rex.input += len;
}
else
status = RA_NOMATCH;
break;
case RE_COMPOSING:
if (enc_utf8)
{
// Skip composing characters.
while (utf_iscomposing(utf_ptr2char(rex.input)))
MB_CPTR_ADV(rex.input);
}
break;
case NOTHING:
break;
case BACK:
{
int i;
backpos_T *bp;
// When we run into BACK we need to check if we don't keep
// looping without matching any input. The second and later
// times a BACK is encountered it fails if the input is still
// at the same position as the previous time.
// The positions are stored in "backpos" and found by the
// current value of "scan", the position in the RE program.
bp = (backpos_T *)backpos.ga_data;
for (i = 0; i < backpos.ga_len; ++i)
if (bp[i].bp_scan == scan)
break;
if (i == backpos.ga_len)
{
// First time at this BACK, make room to store the pos.
if (ga_grow(&backpos, 1) == FAIL)
status = RA_FAIL;
else
{
// get "ga_data" again, it may have changed
bp = (backpos_T *)backpos.ga_data;
bp[i].bp_scan = scan;
++backpos.ga_len;
}
}
else if (reg_save_equal(&bp[i].bp_pos))
// Still at same position as last time, fail.
status = RA_NOMATCH;
if (status != RA_FAIL && status != RA_NOMATCH)
reg_save(&bp[i].bp_pos, &backpos);
}
break;
case MOPEN + 0: // Match start: \zs
case MOPEN + 1: // \(
case MOPEN + 2:
case MOPEN + 3:
case MOPEN + 4:
case MOPEN + 5:
case MOPEN + 6:
case MOPEN + 7:
case MOPEN + 8:
case MOPEN + 9:
{
no = op - MOPEN;
cleanup_subexpr();
rp = regstack_push(RS_MOPEN, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, &rex.reg_startpos[no],
&rex.reg_startp[no]);
// We simply continue and handle the result when done.
}
}
break;
case NOPEN: // \%(
case NCLOSE: // \) after \%(
if (regstack_push(RS_NOPEN, scan) == NULL)
status = RA_FAIL;
// We simply continue and handle the result when done.
break;
#ifdef FEAT_SYN_HL
case ZOPEN + 1:
case ZOPEN + 2:
case ZOPEN + 3:
case ZOPEN + 4:
case ZOPEN + 5:
case ZOPEN + 6:
case ZOPEN + 7:
case ZOPEN + 8:
case ZOPEN + 9:
{
no = op - ZOPEN;
cleanup_zsubexpr();
rp = regstack_push(RS_ZOPEN, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_startzpos[no],
®_startzp[no]);
// We simply continue and handle the result when done.
}
}
break;
#endif
case MCLOSE + 0: // Match end: \ze
case MCLOSE + 1: // \)
case MCLOSE + 2:
case MCLOSE + 3:
case MCLOSE + 4:
case MCLOSE + 5:
case MCLOSE + 6:
case MCLOSE + 7:
case MCLOSE + 8:
case MCLOSE + 9:
{
no = op - MCLOSE;
cleanup_subexpr();
rp = regstack_push(RS_MCLOSE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, &rex.reg_endpos[no],
&rex.reg_endp[no]);
// We simply continue and handle the result when done.
}
}
break;
#ifdef FEAT_SYN_HL
case ZCLOSE + 1: // \) after \z(
case ZCLOSE + 2:
case ZCLOSE + 3:
case ZCLOSE + 4:
case ZCLOSE + 5:
case ZCLOSE + 6:
case ZCLOSE + 7:
case ZCLOSE + 8:
case ZCLOSE + 9:
{
no = op - ZCLOSE;
cleanup_zsubexpr();
rp = regstack_push(RS_ZCLOSE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
save_se(&rp->rs_un.sesave, ®_endzpos[no],
®_endzp[no]);
// We simply continue and handle the result when done.
}
}
break;
#endif
case BACKREF + 1:
case BACKREF + 2:
case BACKREF + 3:
case BACKREF + 4:
case BACKREF + 5:
case BACKREF + 6:
case BACKREF + 7:
case BACKREF + 8:
case BACKREF + 9:
{
int len;
no = op - BACKREF;
cleanup_subexpr();
if (!REG_MULTI) // Single-line regexp
{
if (rex.reg_startp[no] == NULL || rex.reg_endp[no] == NULL)
{
// Backref was not set: Match an empty string.
len = 0;
}
else
{
// Compare current input with back-ref in the same
// line.
len = (int)(rex.reg_endp[no] - rex.reg_startp[no]);
if (cstrncmp(rex.reg_startp[no], rex.input, &len) != 0)
status = RA_NOMATCH;
}
}
else // Multi-line regexp
{
if (rex.reg_startpos[no].lnum < 0
|| rex.reg_endpos[no].lnum < 0)
{
// Backref was not set: Match an empty string.
len = 0;
}
else
{
if (rex.reg_startpos[no].lnum == rex.lnum
&& rex.reg_endpos[no].lnum == rex.lnum)
{
// Compare back-ref within the current line.
len = rex.reg_endpos[no].col
- rex.reg_startpos[no].col;
if (cstrncmp(rex.line + rex.reg_startpos[no].col,
rex.input, &len) != 0)
status = RA_NOMATCH;
}
else
{
// Messy situation: Need to compare between two
// lines.
int r = match_with_backref(
rex.reg_startpos[no].lnum,
rex.reg_startpos[no].col,
rex.reg_endpos[no].lnum,
rex.reg_endpos[no].col,
&len);
if (r != RA_MATCH)
status = r;
}
}
}
// Matched the backref, skip over it.
rex.input += len;
}
break;
#ifdef FEAT_SYN_HL
case ZREF + 1:
case ZREF + 2:
case ZREF + 3:
case ZREF + 4:
case ZREF + 5:
case ZREF + 6:
case ZREF + 7:
case ZREF + 8:
case ZREF + 9:
{
int len;
cleanup_zsubexpr();
no = op - ZREF;
if (re_extmatch_in != NULL
&& re_extmatch_in->matches[no] != NULL)
{
len = (int)STRLEN(re_extmatch_in->matches[no]);
if (cstrncmp(re_extmatch_in->matches[no],
rex.input, &len) != 0)
status = RA_NOMATCH;
else
rex.input += len;
}
else
{
// Backref was not set: Match an empty string.
}
}
break;
#endif
case BRANCH:
{
if (OP(next) != BRANCH) // No choice.
next = OPERAND(scan); // Avoid recursion.
else
{
rp = regstack_push(RS_BRANCH, scan);
if (rp == NULL)
status = RA_FAIL;
else
status = RA_BREAK; // rest is below
}
}
break;
case BRACE_LIMITS:
{
if (OP(next) == BRACE_SIMPLE)
{
bl_minval = OPERAND_MIN(scan);
bl_maxval = OPERAND_MAX(scan);
}
else if (OP(next) >= BRACE_COMPLEX
&& OP(next) < BRACE_COMPLEX + 10)
{
no = OP(next) - BRACE_COMPLEX;
brace_min[no] = OPERAND_MIN(scan);
brace_max[no] = OPERAND_MAX(scan);
brace_count[no] = 0;
}
else
{
internal_error("BRACE_LIMITS");
status = RA_FAIL;
}
}
break;
case BRACE_COMPLEX + 0:
case BRACE_COMPLEX + 1:
case BRACE_COMPLEX + 2:
case BRACE_COMPLEX + 3:
case BRACE_COMPLEX + 4:
case BRACE_COMPLEX + 5:
case BRACE_COMPLEX + 6:
case BRACE_COMPLEX + 7:
case BRACE_COMPLEX + 8:
case BRACE_COMPLEX + 9:
{
no = op - BRACE_COMPLEX;
++brace_count[no];
// If not matched enough times yet, try one more
if (brace_count[no] <= (brace_min[no] <= brace_max[no]
? brace_min[no] : brace_max[no]))
{
rp = regstack_push(RS_BRCPLX_MORE, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
// We continue and handle the result when done.
}
break;
}
// If matched enough times, may try matching some more
if (brace_min[no] <= brace_max[no])
{
// Range is the normal way around, use longest match
if (brace_count[no] <= brace_max[no])
{
rp = regstack_push(RS_BRCPLX_LONG, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = no;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
// We continue and handle the result when done.
}
}
}
else
{
// Range is backwards, use shortest match first
if (brace_count[no] <= brace_min[no])
{
rp = regstack_push(RS_BRCPLX_SHORT, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
reg_save(&rp->rs_un.regsave, &backpos);
// We continue and handle the result when done.
}
}
}
}
break;
case BRACE_SIMPLE:
case STAR:
case PLUS:
{
regstar_T rst;
// Lookahead to avoid useless match attempts when we know
// what character comes next.
if (OP(next) == EXACTLY)
{
rst.nextb = *OPERAND(next);
if (rex.reg_ic)
{
if (MB_ISUPPER(rst.nextb))
rst.nextb_ic = MB_TOLOWER(rst.nextb);
else
rst.nextb_ic = MB_TOUPPER(rst.nextb);
}
else
rst.nextb_ic = rst.nextb;
}
else
{
rst.nextb = NUL;
rst.nextb_ic = NUL;
}
if (op != BRACE_SIMPLE)
{
rst.minval = (op == STAR) ? 0 : 1;
rst.maxval = MAX_LIMIT;
}
else
{
rst.minval = bl_minval;
rst.maxval = bl_maxval;
}
// When maxval > minval, try matching as much as possible, up
// to maxval. When maxval < minval, try matching at least the
// minimal number (since the range is backwards, that's also
// maxval!).
rst.count = regrepeat(OPERAND(scan), rst.maxval);
if (got_int)
{
status = RA_FAIL;
break;
}
if (rst.minval <= rst.maxval
? rst.count >= rst.minval : rst.count >= rst.maxval)
{
// It could match. Prepare for trying to match what
// follows. The code is below. Parameters are stored in
// a regstar_T on the regstack.
if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
{
emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
status = RA_FAIL;
}
else if (ga_grow(®stack, sizeof(regstar_T)) == FAIL)
status = RA_FAIL;
else
{
regstack.ga_len += sizeof(regstar_T);
rp = regstack_push(rst.minval <= rst.maxval
? RS_STAR_LONG : RS_STAR_SHORT, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
*(((regstar_T *)rp) - 1) = rst;
status = RA_BREAK; // skip the restore bits
}
}
}
else
status = RA_NOMATCH;
}
break;
case NOMATCH:
case MATCH:
case SUBPAT:
rp = regstack_push(RS_NOMATCH, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
rp->rs_no = op;
reg_save(&rp->rs_un.regsave, &backpos);
next = OPERAND(scan);
// We continue and handle the result when done.
}
break;
case BEHIND:
case NOBEHIND:
// Need a bit of room to store extra positions.
if ((long)((unsigned)regstack.ga_len >> 10) >= p_mmp)
{
emsg(_(e_pattern_uses_more_memory_than_maxmempattern));
status = RA_FAIL;
}
else if (ga_grow(®stack, sizeof(regbehind_T)) == FAIL)
status = RA_FAIL;
else
{
regstack.ga_len += sizeof(regbehind_T);
rp = regstack_push(RS_BEHIND1, scan);
if (rp == NULL)
status = RA_FAIL;
else
{
// Need to save the subexpr to be able to restore them
// when there is a match but we don't use it.
save_subexpr(((regbehind_T *)rp) - 1);
rp->rs_no = op;
reg_save(&rp->rs_un.regsave, &backpos);
// First try if what follows matches. If it does then we
// check the behind match by looping.
}
}
break;
case BHPOS:
if (REG_MULTI)
{
if (behind_pos.rs_u.pos.col != (colnr_T)(rex.input - rex.line)
|| behind_pos.rs_u.pos.lnum != rex.lnum)
status = RA_NOMATCH;
}
else if (behind_pos.rs_u.ptr != rex.input)
status = RA_NOMATCH;
break;
case NEWL:
if ((c != NUL || !REG_MULTI || rex.lnum > rex.reg_maxline
|| rex.reg_line_lbr)
&& (c != '\n' || !rex.reg_line_lbr))
status = RA_NOMATCH;
else if (rex.reg_line_lbr)
ADVANCE_REGINPUT();
else
reg_nextline();
break;
case END:
status = RA_MATCH; // Success!
break;
default:
iemsg(_(e_corrupted_regexp_program));
#ifdef DEBUG
printf("Illegal op code %d\n", op);
#endif
status = RA_FAIL;
break;
}
}
// If we can't continue sequentially, break the inner loop.
if (status != RA_CONT)
break;
// Continue in inner loop, advance to next item.
scan = next;
} // end of inner loop
// If there is something on the regstack execute the code for the state.
// If the state is popped then loop and use the older state.
while (regstack.ga_len > 0 && status != RA_FAIL)
{
rp = (regitem_T *)((char *)regstack.ga_data + regstack.ga_len) - 1;
switch (rp->rs_state)
{
case RS_NOPEN:
// Result is passed on as-is, simply pop the state.
regstack_pop(&scan);
break;
case RS_MOPEN:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, &rex.reg_startpos[rp->rs_no],
&rex.reg_startp[rp->rs_no]);
regstack_pop(&scan);
break;
#ifdef FEAT_SYN_HL
case RS_ZOPEN:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_startzpos[rp->rs_no],
®_startzp[rp->rs_no]);
regstack_pop(&scan);
break;
#endif
case RS_MCLOSE:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, &rex.reg_endpos[rp->rs_no],
&rex.reg_endp[rp->rs_no]);
regstack_pop(&scan);
break;
#ifdef FEAT_SYN_HL
case RS_ZCLOSE:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
restore_se(&rp->rs_un.sesave, ®_endzpos[rp->rs_no],
®_endzp[rp->rs_no]);
regstack_pop(&scan);
break;
#endif
case RS_BRANCH:
if (status == RA_MATCH)
// this branch matched, use it
regstack_pop(&scan);
else
{
if (status != RA_BREAK)
{
// After a non-matching branch: try next one.
reg_restore(&rp->rs_un.regsave, &backpos);
scan = rp->rs_scan;
}
if (scan == NULL || OP(scan) != BRANCH)
{
// no more branches, didn't find a match
status = RA_NOMATCH;
regstack_pop(&scan);
}
else
{
// Prepare to try a branch.
rp->rs_scan = regnext(scan);
reg_save(&rp->rs_un.regsave, &backpos);
scan = OPERAND(scan);
}
}
break;
case RS_BRCPLX_MORE:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
{
reg_restore(&rp->rs_un.regsave, &backpos);
--brace_count[rp->rs_no]; // decrement match count
}
regstack_pop(&scan);
break;
case RS_BRCPLX_LONG:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
{
// There was no match, but we did find enough matches.
reg_restore(&rp->rs_un.regsave, &backpos);
--brace_count[rp->rs_no];
// continue with the items after "\{}"
status = RA_CONT;
}
regstack_pop(&scan);
if (status == RA_CONT)
scan = regnext(scan);
break;
case RS_BRCPLX_SHORT:
// Pop the state. Restore pointers when there is no match.
if (status == RA_NOMATCH)
// There was no match, try to match one more item.
reg_restore(&rp->rs_un.regsave, &backpos);
regstack_pop(&scan);
if (status == RA_NOMATCH)
{
scan = OPERAND(scan);
status = RA_CONT;
}
break;
case RS_NOMATCH:
// Pop the state. If the operand matches for NOMATCH or
// doesn't match for MATCH/SUBPAT, we fail. Otherwise backup,
// except for SUBPAT, and continue with the next item.
if (status == (rp->rs_no == NOMATCH ? RA_MATCH : RA_NOMATCH))
status = RA_NOMATCH;
else
{
status = RA_CONT;
if (rp->rs_no != SUBPAT) // zero-width
reg_restore(&rp->rs_un.regsave, &backpos);
}
regstack_pop(&scan);
if (status == RA_CONT)
scan = regnext(scan);
break;
case RS_BEHIND1:
if (status == RA_NOMATCH)
{
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
else
{
// The stuff after BEHIND/NOBEHIND matches. Now try if
// the behind part does (not) match before the current
// position in the input. This must be done at every
// position in the input and checking if the match ends at
// the current position.
// save the position after the found match for next
reg_save(&(((regbehind_T *)rp) - 1)->save_after, &backpos);
// Start looking for a match with operand at the current
// position. Go back one character until we find the
// result, hitting the start of the line or the previous
// line (for multi-line matching).
// Set behind_pos to where the match should end, BHPOS
// will match it. Save the current value.
(((regbehind_T *)rp) - 1)->save_behind = behind_pos;
behind_pos = rp->rs_un.regsave;
rp->rs_state = RS_BEHIND2;
reg_restore(&rp->rs_un.regsave, &backpos);
scan = OPERAND(rp->rs_scan) + 4;
}
break;
case RS_BEHIND2:
// Looping for BEHIND / NOBEHIND match.
if (status == RA_MATCH && reg_save_equal(&behind_pos))
{
// found a match that ends where "next" started
behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
if (rp->rs_no == BEHIND)
reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
&backpos);
else
{
// But we didn't want a match. Need to restore the
// subexpr, because what follows matched, so they have
// been set.
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
else
{
long limit;
// No match or a match that doesn't end where we want it: Go
// back one character. May go to previous line once.
no = OK;
limit = OPERAND_MIN(rp->rs_scan);
if (REG_MULTI)
{
if (limit > 0
&& ((rp->rs_un.regsave.rs_u.pos.lnum
< behind_pos.rs_u.pos.lnum
? (colnr_T)STRLEN(rex.line)
: behind_pos.rs_u.pos.col)
- rp->rs_un.regsave.rs_u.pos.col >= limit))
no = FAIL;
else if (rp->rs_un.regsave.rs_u.pos.col == 0)
{
if (rp->rs_un.regsave.rs_u.pos.lnum
< behind_pos.rs_u.pos.lnum
|| reg_getline(
--rp->rs_un.regsave.rs_u.pos.lnum)
== NULL)
no = FAIL;
else
{
reg_restore(&rp->rs_un.regsave, &backpos);
rp->rs_un.regsave.rs_u.pos.col =
(colnr_T)STRLEN(rex.line);
}
}
else
{
if (has_mbyte)
{
char_u *line =
reg_getline(rp->rs_un.regsave.rs_u.pos.lnum);
rp->rs_un.regsave.rs_u.pos.col -=
(*mb_head_off)(line, line
+ rp->rs_un.regsave.rs_u.pos.col - 1) + 1;
}
else
--rp->rs_un.regsave.rs_u.pos.col;
}
}
else
{
if (rp->rs_un.regsave.rs_u.ptr == rex.line)
no = FAIL;
else
{
MB_PTR_BACK(rex.line, rp->rs_un.regsave.rs_u.ptr);
if (limit > 0 && (long)(behind_pos.rs_u.ptr
- rp->rs_un.regsave.rs_u.ptr) > limit)
no = FAIL;
}
}
if (no == OK)
{
// Advanced, prepare for finding match again.
reg_restore(&rp->rs_un.regsave, &backpos);
scan = OPERAND(rp->rs_scan) + 4;
if (status == RA_MATCH)
{
// We did match, so subexpr may have been changed,
// need to restore them for the next try.
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
}
else
{
// Can't advance. For NOBEHIND that's a match.
behind_pos = (((regbehind_T *)rp) - 1)->save_behind;
if (rp->rs_no == NOBEHIND)
{
reg_restore(&(((regbehind_T *)rp) - 1)->save_after,
&backpos);
status = RA_MATCH;
}
else
{
// We do want a proper match. Need to restore the
// subexpr if we had a match, because they may have
// been set.
if (status == RA_MATCH)
{
status = RA_NOMATCH;
restore_subexpr(((regbehind_T *)rp) - 1);
}
}
regstack_pop(&scan);
regstack.ga_len -= sizeof(regbehind_T);
}
}
break;
case RS_STAR_LONG:
case RS_STAR_SHORT:
{
regstar_T *rst = ((regstar_T *)rp) - 1;
if (status == RA_MATCH)
{
regstack_pop(&scan);
regstack.ga_len -= sizeof(regstar_T);
break;
}
// Tried once already, restore input pointers.
if (status != RA_BREAK)
reg_restore(&rp->rs_un.regsave, &backpos);
// Repeat until we found a position where it could match.
for (;;)
{
if (status != RA_BREAK)
{
// Tried first position already, advance.
if (rp->rs_state == RS_STAR_LONG)
{
// Trying for longest match, but couldn't or
// didn't match -- back up one char.
if (--rst->count < rst->minval)
break;
if (rex.input == rex.line)
{
// backup to last char of previous line
if (rex.lnum == 0)
{
status = RA_NOMATCH;
break;
}
--rex.lnum;
rex.line = reg_getline(rex.lnum);
// Just in case regrepeat() didn't count
// right.
if (rex.line == NULL)
break;
rex.input = rex.line + STRLEN(rex.line);
fast_breakcheck();
}
else
MB_PTR_BACK(rex.line, rex.input);
}
else
{
// Range is backwards, use shortest match first.
// Careful: maxval and minval are exchanged!
// Couldn't or didn't match: try advancing one
// char.
if (rst->count == rst->minval
|| regrepeat(OPERAND(rp->rs_scan), 1L) == 0)
break;
++rst->count;
}
if (got_int)
break;
}
else
status = RA_NOMATCH;
// If it could match, try it.
if (rst->nextb == NUL || *rex.input == rst->nextb
|| *rex.input == rst->nextb_ic)
{
reg_save(&rp->rs_un.regsave, &backpos);
scan = regnext(rp->rs_scan);
status = RA_CONT;
break;
}
}
if (status != RA_CONT)
{
// Failed.
regstack_pop(&scan);
regstack.ga_len -= sizeof(regstar_T);
status = RA_NOMATCH;
}
}
break;
}
// If we want to continue the inner loop or didn't pop a state
// continue matching loop
if (status == RA_CONT || rp == (regitem_T *)
((char *)regstack.ga_data + regstack.ga_len) - 1)
break;
}
// May need to continue with the inner loop, starting at "scan".
if (status == RA_CONT)
continue;
// If the regstack is empty or something failed we are done.
if (regstack.ga_len == 0 || status == RA_FAIL)
{
if (scan == NULL)
{
// We get here only if there's trouble -- normally "case END" is
// the terminating point.
iemsg(_(e_corrupted_regexp_program));
#ifdef DEBUG
printf("Premature EOL\n");
#endif
}
return (status == RA_MATCH);
}
} // End of loop until the regstack is empty.
// NOTREACHED
}
| null | null | 201,885
|
60421016800793793166359282492826671366
| 1,486
|
patch 8.2.4646: using buffer line after it has been freed
Problem: Using buffer line after it has been freed in old regexp engine.
Solution: After getting mark get the line again.
|
other
|
libarchive
|
e2ad1a2c3064fa9eba6274b3641c4c1beed25c0b
| 1
|
set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
mode_t mode, unsigned long set, unsigned long clear)
{
int ret;
int myfd = fd;
int newflags, oldflags;
/*
* Linux has no define for the flags that are only settable by
* the root user. This code may seem a little complex, but
* there seem to be some Linux systems that lack these
* defines. (?) The code below degrades reasonably gracefully
* if sf_mask is incomplete.
*/
const int sf_mask = 0
#if defined(FS_IMMUTABLE_FL)
| FS_IMMUTABLE_FL
#elif defined(EXT2_IMMUTABLE_FL)
| EXT2_IMMUTABLE_FL
#endif
#if defined(FS_APPEND_FL)
| FS_APPEND_FL
#elif defined(EXT2_APPEND_FL)
| EXT2_APPEND_FL
#endif
#if defined(FS_JOURNAL_DATA_FL)
| FS_JOURNAL_DATA_FL
#endif
;
if (set == 0 && clear == 0)
return (ARCHIVE_OK);
/* Only regular files and dirs can have flags. */
if (!S_ISREG(mode) && !S_ISDIR(mode))
return (ARCHIVE_OK);
/* If we weren't given an fd, open it ourselves. */
if (myfd < 0) {
myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(myfd);
}
if (myfd < 0)
return (ARCHIVE_OK);
/*
* XXX As above, this would be way simpler if we didn't have
* to read the current flags from disk. XXX
*/
ret = ARCHIVE_OK;
/* Read the current file flags. */
if (ioctl(myfd,
#ifdef FS_IOC_GETFLAGS
FS_IOC_GETFLAGS,
#else
EXT2_IOC_GETFLAGS,
#endif
&oldflags) < 0)
goto fail;
/* Try setting the flags as given. */
newflags = (oldflags & ~clear) | set;
if (ioctl(myfd,
#ifdef FS_IOC_SETFLAGS
FS_IOC_SETFLAGS,
#else
EXT2_IOC_SETFLAGS,
#endif
&newflags) >= 0)
goto cleanup;
if (errno != EPERM)
goto fail;
/* If we couldn't set all the flags, try again with a subset. */
newflags &= ~sf_mask;
oldflags &= sf_mask;
newflags |= oldflags;
if (ioctl(myfd,
#ifdef FS_IOC_SETFLAGS
FS_IOC_SETFLAGS,
#else
EXT2_IOC_SETFLAGS,
#endif
&newflags) >= 0)
goto cleanup;
/* We couldn't set the flags, so report the failure. */
fail:
archive_set_error(&a->archive, errno,
"Failed to set file flags");
ret = ARCHIVE_WARN;
cleanup:
if (fd < 0)
close(myfd);
return (ret);
}
| null | null | 201,913
|
113558799892805605593256307933918259832
| 95
|
Never follow symlinks when setting file flags on Linux
When opening a file descriptor to set file flags on linux, ensure
no symbolic links are followed. This fixes the case when an archive
contains a directory entry followed by a symlink entry with the same
path. The fixup code would modify file flags of the symlink target.
|
other
|
linux
|
e6a21a14106d9718aa4f8e115b1e474888eeba44
| 1
|
*vidtv_s302m_encoder_init(struct vidtv_s302m_encoder_init_args args)
{
u32 priv_sz = sizeof(struct vidtv_s302m_ctx);
struct vidtv_s302m_ctx *ctx;
struct vidtv_encoder *e;
e = kzalloc(sizeof(*e), GFP_KERNEL);
if (!e)
return NULL;
e->id = S302M;
if (args.name)
e->name = kstrdup(args.name, GFP_KERNEL);
e->encoder_buf = vzalloc(VIDTV_S302M_BUF_SZ);
e->encoder_buf_sz = VIDTV_S302M_BUF_SZ;
e->encoder_buf_offset = 0;
e->sample_count = 0;
e->src_buf = (args.src_buf) ? args.src_buf : NULL;
e->src_buf_sz = (args.src_buf) ? args.src_buf_sz : 0;
e->src_buf_offset = 0;
e->is_video_encoder = false;
ctx = kzalloc(priv_sz, GFP_KERNEL);
if (!ctx) {
kfree(e);
return NULL;
}
e->ctx = ctx;
ctx->last_duration = 0;
e->encode = vidtv_s302m_encode;
e->clear = vidtv_s302m_clear;
e->es_pid = cpu_to_be16(args.es_pid);
e->stream_id = cpu_to_be16(PES_PRIVATE_STREAM_1);
e->sync = args.sync;
e->sampling_rate_hz = S302M_SAMPLING_RATE_HZ;
e->last_sample_cb = args.last_sample_cb;
e->destroy = vidtv_s302m_encoder_destroy;
if (args.head) {
while (args.head->next)
args.head = args.head->next;
args.head->next = e;
}
e->next = NULL;
return e;
}
| null | null | 201,925
|
220376165242545767374971532665904547126
| 60
|
media: vidtv: Check for null return of vzalloc
As the possible failure of the vzalloc(), e->encoder_buf might be NULL.
Therefore, it should be better to check it in order
to guarantee the success of the initialization.
If fails, we need to free not only 'e' but also 'e->name'.
Also, if the allocation for ctx fails, we need to free 'e->encoder_buf'
else.
Fixes: f90cf6079bf6 ("media: vidtv: add a bridge driver")
Signed-off-by: Jiasheng Jiang <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
|
other
|
vim
|
d25f003342aca9889067f2e839963dfeccf1fe05
| 1
|
do_put(
int regname,
char_u *expr_result, // result for regname "=" when compiled
int dir, // BACKWARD for 'P', FORWARD for 'p'
long count,
int flags)
{
char_u *ptr;
char_u *newp, *oldp;
int yanklen;
int totlen = 0; // init for gcc
linenr_T lnum;
colnr_T col;
long i; // index in y_array[]
int y_type;
long y_size;
int oldlen;
long y_width = 0;
colnr_T vcol;
int delcount;
int incr = 0;
long j;
struct block_def bd;
char_u **y_array = NULL;
yankreg_T *y_current_used = NULL;
long nr_lines = 0;
pos_T new_cursor;
int indent;
int orig_indent = 0; // init for gcc
int indent_diff = 0; // init for gcc
int first_indent = TRUE;
int lendiff = 0;
pos_T old_pos;
char_u *insert_string = NULL;
int allocated = FALSE;
long cnt;
pos_T orig_start = curbuf->b_op_start;
pos_T orig_end = curbuf->b_op_end;
unsigned int cur_ve_flags = get_ve_flags();
#ifdef FEAT_CLIPBOARD
// Adjust register name for "unnamed" in 'clipboard'.
adjust_clip_reg(®name);
(void)may_get_selection(regname);
#endif
if (flags & PUT_FIXINDENT)
orig_indent = get_indent();
curbuf->b_op_start = curwin->w_cursor; // default for '[ mark
curbuf->b_op_end = curwin->w_cursor; // default for '] mark
// Using inserted text works differently, because the register includes
// special characters (newlines, etc.).
if (regname == '.')
{
if (VIsual_active)
stuffcharReadbuff(VIsual_mode);
(void)stuff_inserted((dir == FORWARD ? (count == -1 ? 'o' : 'a') :
(count == -1 ? 'O' : 'i')), count, FALSE);
// Putting the text is done later, so can't really move the cursor to
// the next character. Use "l" to simulate it.
if ((flags & PUT_CURSEND) && gchar_cursor() != NUL)
stuffcharReadbuff('l');
return;
}
// For special registers '%' (file name), '#' (alternate file name) and
// ':' (last command line), etc. we have to create a fake yank register.
// For compiled code "expr_result" holds the expression result.
if (regname == '=' && expr_result != NULL)
insert_string = expr_result;
else if (get_spec_reg(regname, &insert_string, &allocated, TRUE)
&& insert_string == NULL)
return;
// Autocommands may be executed when saving lines for undo. This might
// make "y_array" invalid, so we start undo now to avoid that.
if (u_save(curwin->w_cursor.lnum, curwin->w_cursor.lnum + 1) == FAIL)
goto end;
if (insert_string != NULL)
{
y_type = MCHAR;
#ifdef FEAT_EVAL
if (regname == '=')
{
// For the = register we need to split the string at NL
// characters.
// Loop twice: count the number of lines and save them.
for (;;)
{
y_size = 0;
ptr = insert_string;
while (ptr != NULL)
{
if (y_array != NULL)
y_array[y_size] = ptr;
++y_size;
ptr = vim_strchr(ptr, '\n');
if (ptr != NULL)
{
if (y_array != NULL)
*ptr = NUL;
++ptr;
// A trailing '\n' makes the register linewise.
if (*ptr == NUL)
{
y_type = MLINE;
break;
}
}
}
if (y_array != NULL)
break;
y_array = ALLOC_MULT(char_u *, y_size);
if (y_array == NULL)
goto end;
}
}
else
#endif
{
y_size = 1; // use fake one-line yank register
y_array = &insert_string;
}
}
else
{
get_yank_register(regname, FALSE);
y_type = y_current->y_type;
y_width = y_current->y_width;
y_size = y_current->y_size;
y_array = y_current->y_array;
y_current_used = y_current;
}
if (y_type == MLINE)
{
if (flags & PUT_LINE_SPLIT)
{
char_u *p;
// "p" or "P" in Visual mode: split the lines to put the text in
// between.
if (u_save_cursor() == FAIL)
goto end;
p = ml_get_cursor();
if (dir == FORWARD && *p != NUL)
MB_PTR_ADV(p);
ptr = vim_strsave(p);
if (ptr == NULL)
goto end;
ml_append(curwin->w_cursor.lnum, ptr, (colnr_T)0, FALSE);
vim_free(ptr);
oldp = ml_get_curline();
p = oldp + curwin->w_cursor.col;
if (dir == FORWARD && *p != NUL)
MB_PTR_ADV(p);
ptr = vim_strnsave(oldp, p - oldp);
if (ptr == NULL)
goto end;
ml_replace(curwin->w_cursor.lnum, ptr, FALSE);
++nr_lines;
dir = FORWARD;
}
if (flags & PUT_LINE_FORWARD)
{
// Must be "p" for a Visual block, put lines below the block.
curwin->w_cursor = curbuf->b_visual.vi_end;
dir = FORWARD;
}
curbuf->b_op_start = curwin->w_cursor; // default for '[ mark
curbuf->b_op_end = curwin->w_cursor; // default for '] mark
}
if (flags & PUT_LINE) // :put command or "p" in Visual line mode.
y_type = MLINE;
if (y_size == 0 || y_array == NULL)
{
semsg(_(e_nothing_in_register_str),
regname == 0 ? (char_u *)"\"" : transchar(regname));
goto end;
}
if (y_type == MBLOCK)
{
lnum = curwin->w_cursor.lnum + y_size + 1;
if (lnum > curbuf->b_ml.ml_line_count)
lnum = curbuf->b_ml.ml_line_count + 1;
if (u_save(curwin->w_cursor.lnum - 1, lnum) == FAIL)
goto end;
}
else if (y_type == MLINE)
{
lnum = curwin->w_cursor.lnum;
#ifdef FEAT_FOLDING
// Correct line number for closed fold. Don't move the cursor yet,
// u_save() uses it.
if (dir == BACKWARD)
(void)hasFolding(lnum, &lnum, NULL);
else
(void)hasFolding(lnum, NULL, &lnum);
#endif
if (dir == FORWARD)
++lnum;
// In an empty buffer the empty line is going to be replaced, include
// it in the saved lines.
if ((BUFEMPTY() ? u_save(0, 2) : u_save(lnum - 1, lnum)) == FAIL)
goto end;
#ifdef FEAT_FOLDING
if (dir == FORWARD)
curwin->w_cursor.lnum = lnum - 1;
else
curwin->w_cursor.lnum = lnum;
curbuf->b_op_start = curwin->w_cursor; // for mark_adjust()
#endif
}
else if (u_save_cursor() == FAIL)
goto end;
yanklen = (int)STRLEN(y_array[0]);
if (cur_ve_flags == VE_ALL && y_type == MCHAR)
{
if (gchar_cursor() == TAB)
{
int viscol = getviscol();
int ts = curbuf->b_p_ts;
// Don't need to insert spaces when "p" on the last position of a
// tab or "P" on the first position.
if (dir == FORWARD ?
#ifdef FEAT_VARTABS
tabstop_padding(viscol, ts, curbuf->b_p_vts_array) != 1
#else
ts - (viscol % ts) != 1
#endif
: curwin->w_cursor.coladd > 0)
coladvance_force(viscol);
else
curwin->w_cursor.coladd = 0;
}
else if (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)
coladvance_force(getviscol() + (dir == FORWARD));
}
lnum = curwin->w_cursor.lnum;
col = curwin->w_cursor.col;
// Block mode
if (y_type == MBLOCK)
{
int c = gchar_cursor();
colnr_T endcol2 = 0;
if (dir == FORWARD && c != NUL)
{
if (cur_ve_flags == VE_ALL)
getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
else
getvcol(curwin, &curwin->w_cursor, NULL, NULL, &col);
if (has_mbyte)
// move to start of next multi-byte character
curwin->w_cursor.col += (*mb_ptr2len)(ml_get_cursor());
else
if (c != TAB || cur_ve_flags != VE_ALL)
++curwin->w_cursor.col;
++col;
}
else
getvcol(curwin, &curwin->w_cursor, &col, NULL, &endcol2);
col += curwin->w_cursor.coladd;
if (cur_ve_flags == VE_ALL
&& (curwin->w_cursor.coladd > 0
|| endcol2 == curwin->w_cursor.col))
{
if (dir == FORWARD && c == NUL)
++col;
if (dir != FORWARD && c != NUL && curwin->w_cursor.coladd > 0)
++curwin->w_cursor.col;
if (c == TAB)
{
if (dir == BACKWARD && curwin->w_cursor.col)
curwin->w_cursor.col--;
if (dir == FORWARD && col - 1 == endcol2)
curwin->w_cursor.col++;
}
}
curwin->w_cursor.coladd = 0;
bd.textcol = 0;
for (i = 0; i < y_size; ++i)
{
int spaces = 0;
char shortline;
bd.startspaces = 0;
bd.endspaces = 0;
vcol = 0;
delcount = 0;
// add a new line
if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
{
if (ml_append(curbuf->b_ml.ml_line_count, (char_u *)"",
(colnr_T)1, FALSE) == FAIL)
break;
++nr_lines;
}
// get the old line and advance to the position to insert at
oldp = ml_get_curline();
oldlen = (int)STRLEN(oldp);
for (ptr = oldp; vcol < col && *ptr; )
{
// Count a tab for what it's worth (if list mode not on)
incr = lbr_chartabsize_adv(oldp, &ptr, vcol);
vcol += incr;
}
bd.textcol = (colnr_T)(ptr - oldp);
shortline = (vcol < col) || (vcol == col && !*ptr) ;
if (vcol < col) // line too short, padd with spaces
bd.startspaces = col - vcol;
else if (vcol > col)
{
bd.endspaces = vcol - col;
bd.startspaces = incr - bd.endspaces;
--bd.textcol;
delcount = 1;
if (has_mbyte)
bd.textcol -= (*mb_head_off)(oldp, oldp + bd.textcol);
if (oldp[bd.textcol] != TAB)
{
// Only a Tab can be split into spaces. Other
// characters will have to be moved to after the
// block, causing misalignment.
delcount = 0;
bd.endspaces = 0;
}
}
yanklen = (int)STRLEN(y_array[i]);
if ((flags & PUT_BLOCK_INNER) == 0)
{
// calculate number of spaces required to fill right side of
// block
spaces = y_width + 1;
for (j = 0; j < yanklen; j++)
spaces -= lbr_chartabsize(NULL, &y_array[i][j], 0);
if (spaces < 0)
spaces = 0;
}
// Insert the new text.
// First check for multiplication overflow.
if (yanklen + spaces != 0
&& count > ((INT_MAX - (bd.startspaces + bd.endspaces))
/ (yanklen + spaces)))
{
emsg(_(e_resulting_text_too_long));
break;
}
totlen = count * (yanklen + spaces) + bd.startspaces + bd.endspaces;
newp = alloc(totlen + oldlen + 1);
if (newp == NULL)
break;
// copy part up to cursor to new line
ptr = newp;
mch_memmove(ptr, oldp, (size_t)bd.textcol);
ptr += bd.textcol;
// may insert some spaces before the new text
vim_memset(ptr, ' ', (size_t)bd.startspaces);
ptr += bd.startspaces;
// insert the new text
for (j = 0; j < count; ++j)
{
mch_memmove(ptr, y_array[i], (size_t)yanklen);
ptr += yanklen;
// insert block's trailing spaces only if there's text behind
if ((j < count - 1 || !shortline) && spaces)
{
vim_memset(ptr, ' ', (size_t)spaces);
ptr += spaces;
}
}
// may insert some spaces after the new text
vim_memset(ptr, ' ', (size_t)bd.endspaces);
ptr += bd.endspaces;
// move the text after the cursor to the end of the line.
mch_memmove(ptr, oldp + bd.textcol + delcount,
(size_t)(oldlen - bd.textcol - delcount + 1));
ml_replace(curwin->w_cursor.lnum, newp, FALSE);
++curwin->w_cursor.lnum;
if (i == 0)
curwin->w_cursor.col += bd.startspaces;
}
changed_lines(lnum, 0, curwin->w_cursor.lnum, nr_lines);
// Set '[ mark.
curbuf->b_op_start = curwin->w_cursor;
curbuf->b_op_start.lnum = lnum;
// adjust '] mark
curbuf->b_op_end.lnum = curwin->w_cursor.lnum - 1;
curbuf->b_op_end.col = bd.textcol + totlen - 1;
curbuf->b_op_end.coladd = 0;
if (flags & PUT_CURSEND)
{
colnr_T len;
curwin->w_cursor = curbuf->b_op_end;
curwin->w_cursor.col++;
// in Insert mode we might be after the NUL, correct for that
len = (colnr_T)STRLEN(ml_get_curline());
if (curwin->w_cursor.col > len)
curwin->w_cursor.col = len;
}
else
curwin->w_cursor.lnum = lnum;
}
else
{
// Character or Line mode
if (y_type == MCHAR)
{
// if type is MCHAR, FORWARD is the same as BACKWARD on the next
// char
if (dir == FORWARD && gchar_cursor() != NUL)
{
if (has_mbyte)
{
int bytelen = (*mb_ptr2len)(ml_get_cursor());
// put it on the next of the multi-byte character.
col += bytelen;
if (yanklen)
{
curwin->w_cursor.col += bytelen;
curbuf->b_op_end.col += bytelen;
}
}
else
{
++col;
if (yanklen)
{
++curwin->w_cursor.col;
++curbuf->b_op_end.col;
}
}
}
curbuf->b_op_start = curwin->w_cursor;
}
// Line mode: BACKWARD is the same as FORWARD on the previous line
else if (dir == BACKWARD)
--lnum;
new_cursor = curwin->w_cursor;
// simple case: insert into one line at a time
if (y_type == MCHAR && y_size == 1)
{
linenr_T end_lnum = 0; // init for gcc
linenr_T start_lnum = lnum;
int first_byte_off = 0;
if (VIsual_active)
{
end_lnum = curbuf->b_visual.vi_end.lnum;
if (end_lnum < curbuf->b_visual.vi_start.lnum)
end_lnum = curbuf->b_visual.vi_start.lnum;
if (end_lnum > start_lnum)
{
pos_T pos;
// "col" is valid for the first line, in following lines
// the virtual column needs to be used. Matters for
// multi-byte characters.
pos.lnum = lnum;
pos.col = col;
pos.coladd = 0;
getvcol(curwin, &pos, NULL, &vcol, NULL);
}
}
if (count == 0 || yanklen == 0)
{
if (VIsual_active)
lnum = end_lnum;
}
else if (count > INT_MAX / yanklen)
// multiplication overflow
emsg(_(e_resulting_text_too_long));
else
{
totlen = count * yanklen;
do {
oldp = ml_get(lnum);
oldlen = (int)STRLEN(oldp);
if (lnum > start_lnum)
{
pos_T pos;
pos.lnum = lnum;
if (getvpos(&pos, vcol) == OK)
col = pos.col;
else
col = MAXCOL;
}
if (VIsual_active && col > oldlen)
{
lnum++;
continue;
}
newp = alloc(totlen + oldlen + 1);
if (newp == NULL)
goto end; // alloc() gave an error message
mch_memmove(newp, oldp, (size_t)col);
ptr = newp + col;
for (i = 0; i < count; ++i)
{
mch_memmove(ptr, y_array[0], (size_t)yanklen);
ptr += yanklen;
}
STRMOVE(ptr, oldp + col);
ml_replace(lnum, newp, FALSE);
// compute the byte offset for the last character
first_byte_off = mb_head_off(newp, ptr - 1);
// Place cursor on last putted char.
if (lnum == curwin->w_cursor.lnum)
{
// make sure curwin->w_virtcol is updated
changed_cline_bef_curs();
curwin->w_cursor.col += (colnr_T)(totlen - 1);
}
if (VIsual_active)
lnum++;
} while (VIsual_active && lnum <= end_lnum);
if (VIsual_active) // reset lnum to the last visual line
lnum--;
}
// put '] at the first byte of the last character
curbuf->b_op_end = curwin->w_cursor;
curbuf->b_op_end.col -= first_byte_off;
// For "CTRL-O p" in Insert mode, put cursor after last char
if (totlen && (restart_edit != 0 || (flags & PUT_CURSEND)))
++curwin->w_cursor.col;
else
curwin->w_cursor.col -= first_byte_off;
changed_bytes(lnum, col);
}
else
{
linenr_T new_lnum = new_cursor.lnum;
size_t len;
// Insert at least one line. When y_type is MCHAR, break the first
// line in two.
for (cnt = 1; cnt <= count; ++cnt)
{
i = 0;
if (y_type == MCHAR)
{
// Split the current line in two at the insert position.
// First insert y_array[size - 1] in front of second line.
// Then append y_array[0] to first line.
lnum = new_cursor.lnum;
ptr = ml_get(lnum) + col;
totlen = (int)STRLEN(y_array[y_size - 1]);
newp = alloc(STRLEN(ptr) + totlen + 1);
if (newp == NULL)
goto error;
STRCPY(newp, y_array[y_size - 1]);
STRCAT(newp, ptr);
// insert second line
ml_append(lnum, newp, (colnr_T)0, FALSE);
++new_lnum;
vim_free(newp);
oldp = ml_get(lnum);
newp = alloc(col + yanklen + 1);
if (newp == NULL)
goto error;
// copy first part of line
mch_memmove(newp, oldp, (size_t)col);
// append to first line
mch_memmove(newp + col, y_array[0], (size_t)(yanklen + 1));
ml_replace(lnum, newp, FALSE);
curwin->w_cursor.lnum = lnum;
i = 1;
}
for (; i < y_size; ++i)
{
if (y_type != MCHAR || i < y_size - 1)
{
if (ml_append(lnum, y_array[i], (colnr_T)0, FALSE)
== FAIL)
goto error;
new_lnum++;
}
lnum++;
++nr_lines;
if (flags & PUT_FIXINDENT)
{
old_pos = curwin->w_cursor;
curwin->w_cursor.lnum = lnum;
ptr = ml_get(lnum);
if (cnt == count && i == y_size - 1)
lendiff = (int)STRLEN(ptr);
if (*ptr == '#' && preprocs_left())
indent = 0; // Leave # lines at start
else
if (*ptr == NUL)
indent = 0; // Ignore empty lines
else if (first_indent)
{
indent_diff = orig_indent - get_indent();
indent = orig_indent;
first_indent = FALSE;
}
else if ((indent = get_indent() + indent_diff) < 0)
indent = 0;
(void)set_indent(indent, 0);
curwin->w_cursor = old_pos;
// remember how many chars were removed
if (cnt == count && i == y_size - 1)
lendiff -= (int)STRLEN(ml_get(lnum));
}
}
if (cnt == 1)
new_lnum = lnum;
}
error:
// Adjust marks.
if (y_type == MLINE)
{
curbuf->b_op_start.col = 0;
if (dir == FORWARD)
curbuf->b_op_start.lnum++;
}
// Skip mark_adjust when adding lines after the last one, there
// can't be marks there. But still needed in diff mode.
if (curbuf->b_op_start.lnum + (y_type == MCHAR) - 1 + nr_lines
< curbuf->b_ml.ml_line_count
#ifdef FEAT_DIFF
|| curwin->w_p_diff
#endif
)
mark_adjust(curbuf->b_op_start.lnum + (y_type == MCHAR),
(linenr_T)MAXLNUM, nr_lines, 0L);
// note changed text for displaying and folding
if (y_type == MCHAR)
changed_lines(curwin->w_cursor.lnum, col,
curwin->w_cursor.lnum + 1, nr_lines);
else
changed_lines(curbuf->b_op_start.lnum, 0,
curbuf->b_op_start.lnum, nr_lines);
if (y_current_used != NULL && (y_current_used != y_current
|| y_current->y_array != y_array))
{
// Something invoked through changed_lines() has changed the
// yank buffer, e.g. a GUI clipboard callback.
emsg(_(e_yank_register_changed_while_using_it));
goto end;
}
// Put the '] mark on the first byte of the last inserted character.
// Correct the length for change in indent.
curbuf->b_op_end.lnum = new_lnum;
len = STRLEN(y_array[y_size - 1]);
col = (colnr_T)len - lendiff;
if (col > 1)
{
curbuf->b_op_end.col = col - 1;
if (len > 0)
curbuf->b_op_end.col -= mb_head_off(y_array[y_size - 1],
y_array[y_size - 1] + len - 1);
}
else
curbuf->b_op_end.col = 0;
if (flags & PUT_CURSLINE)
{
// ":put": put cursor on last inserted line
curwin->w_cursor.lnum = lnum;
beginline(BL_WHITE | BL_FIX);
}
else if (flags & PUT_CURSEND)
{
// put cursor after inserted text
if (y_type == MLINE)
{
if (lnum >= curbuf->b_ml.ml_line_count)
curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
else
curwin->w_cursor.lnum = lnum + 1;
curwin->w_cursor.col = 0;
}
else
{
curwin->w_cursor.lnum = new_lnum;
curwin->w_cursor.col = col;
curbuf->b_op_end = curwin->w_cursor;
if (col > 1)
curbuf->b_op_end.col = col - 1;
}
}
else if (y_type == MLINE)
{
// put cursor on first non-blank in first inserted line
curwin->w_cursor.col = 0;
if (dir == FORWARD)
++curwin->w_cursor.lnum;
beginline(BL_WHITE | BL_FIX);
}
else // put cursor on first inserted character
curwin->w_cursor = new_cursor;
}
}
msgmore(nr_lines);
curwin->w_set_curswant = TRUE;
end:
if (cmdmod.cmod_flags & CMOD_LOCKMARKS)
{
curbuf->b_op_start = orig_start;
curbuf->b_op_end = orig_end;
}
if (allocated)
vim_free(insert_string);
if (regname == '=')
vim_free(y_array);
VIsual_active = FALSE;
// If the cursor is past the end of the line put it at the end.
adjust_cursor_eol();
}
| null | null | 202,081
|
264433559967000230598420957654051673771
| 764
|
patch 9.0.0011: reading beyond the end of the line with put command
Problem: Reading beyond the end of the line with put command.
Solution: Adjust the end mark position.
|
other
|
radare2
|
ecc44b6a2f18ee70ac133365de0e509d26d5e168
| 1
|
R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaBootStrapMethod *bsm = NULL;
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR;
attr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.bootstrap_methods_attr.bootstrap_methods = r_list_newf (r_bin_java_bootstrap_method_free);
for (i = 0; i < attr->info.bootstrap_methods_attr.num_bootstrap_methods; i++) {
// bsm = r_bin_java_bootstrap_method_new (bin, bin->b->cur);
if (offset >= sz) {
break;
}
bsm = r_bin_java_bootstrap_method_new (buffer + offset, sz - offset, buf_offset + offset);
if (bsm) {
offset += bsm->size;
r_list_append (attr->info.bootstrap_methods_attr.bootstrap_methods, (void *) bsm);
} else {
// TODO eprintf Failed to read the %d boot strap method.
}
}
attr->size = offset;
}
return attr;
}
| null | null | 202,082
|
144678045984176110578223629747221025527
| 28
|
Fix oobread in java parser ##crash
* Reported by @bet4it via @huntrdev
* BountyID c8f4c2de-7d96-4ad4-857a-c099effca2d6
* Reproducer: bootstrap.class
|
other
|
cairo
|
03a820b173ed1fdef6ff14b4468f5dbc02ff59be
| 1
|
_inplace_src_spans (void *abstract_renderer, int y, int h,
const cairo_half_open_span_t *spans,
unsigned num_spans)
{
cairo_image_span_renderer_t *r = abstract_renderer;
uint8_t *m;
int x0;
if (num_spans == 0)
return CAIRO_STATUS_SUCCESS;
x0 = spans[0].x;
m = r->_buf;
do {
int len = spans[1].x - spans[0].x;
if (len >= r->u.composite.run_length && spans[0].coverage == 0xff) {
if (spans[0].x != x0) {
#if PIXMAN_HAS_OP_LERP
pixman_image_composite32 (PIXMAN_OP_LERP_SRC,
r->src, r->mask, r->u.composite.dst,
x0 + r->u.composite.src_x,
y + r->u.composite.src_y,
0, 0,
x0, y,
spans[0].x - x0, h);
#else
pixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,
r->mask, NULL, r->u.composite.dst,
0, 0,
0, 0,
x0, y,
spans[0].x - x0, h);
pixman_image_composite32 (PIXMAN_OP_ADD,
r->src, r->mask, r->u.composite.dst,
x0 + r->u.composite.src_x,
y + r->u.composite.src_y,
0, 0,
x0, y,
spans[0].x - x0, h);
#endif
}
pixman_image_composite32 (PIXMAN_OP_SRC,
r->src, NULL, r->u.composite.dst,
spans[0].x + r->u.composite.src_x,
y + r->u.composite.src_y,
0, 0,
spans[0].x, y,
spans[1].x - spans[0].x, h);
m = r->_buf;
x0 = spans[1].x;
} else if (spans[0].coverage == 0x0) {
if (spans[0].x != x0) {
#if PIXMAN_HAS_OP_LERP
pixman_image_composite32 (PIXMAN_OP_LERP_SRC,
r->src, r->mask, r->u.composite.dst,
x0 + r->u.composite.src_x,
y + r->u.composite.src_y,
0, 0,
x0, y,
spans[0].x - x0, h);
#else
pixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,
r->mask, NULL, r->u.composite.dst,
0, 0,
0, 0,
x0, y,
spans[0].x - x0, h);
pixman_image_composite32 (PIXMAN_OP_ADD,
r->src, r->mask, r->u.composite.dst,
x0 + r->u.composite.src_x,
y + r->u.composite.src_y,
0, 0,
x0, y,
spans[0].x - x0, h);
#endif
}
m = r->_buf;
x0 = spans[1].x;
} else {
*m++ = spans[0].coverage;
if (len > 1) {
memset (m, spans[0].coverage, --len);
m += len;
}
}
spans++;
} while (--num_spans > 1);
if (spans[0].x != x0) {
#if PIXMAN_HAS_OP_LERP
pixman_image_composite32 (PIXMAN_OP_LERP_SRC,
r->src, r->mask, r->u.composite.dst,
x0 + r->u.composite.src_x,
y + r->u.composite.src_y,
0, 0,
x0, y,
spans[0].x - x0, h);
#else
pixman_image_composite32 (PIXMAN_OP_OUT_REVERSE,
r->mask, NULL, r->u.composite.dst,
0, 0,
0, 0,
x0, y,
spans[0].x - x0, h);
pixman_image_composite32 (PIXMAN_OP_ADD,
r->src, r->mask, r->u.composite.dst,
x0 + r->u.composite.src_x,
y + r->u.composite.src_y,
0, 0,
x0, y,
spans[0].x - x0, h);
#endif
}
return CAIRO_STATUS_SUCCESS;
}
| null | null | 202,125
|
143821191893000201866286427652701042245
| 119
|
Fix mask usage in image-compositor
|
other
|
qtbase
|
6b400e3147dcfd8cc3a393ace1bd118c93762e0c
| 1
|
void QPaintEngineEx::stroke(const QVectorPath &path, const QPen &inPen)
{
#ifdef QT_DEBUG_DRAW
qDebug() << "QPaintEngineEx::stroke()" << pen;
#endif
Q_D(QPaintEngineEx);
if (path.isEmpty())
return;
if (!d->strokeHandler) {
d->strokeHandler = new StrokeHandler(path.elementCount()+4);
d->stroker.setMoveToHook(qpaintengineex_moveTo);
d->stroker.setLineToHook(qpaintengineex_lineTo);
d->stroker.setCubicToHook(qpaintengineex_cubicTo);
}
QRectF clipRect;
QPen pen = inPen;
if (pen.style() > Qt::SolidLine) {
QRectF cpRect = path.controlPointRect();
const QTransform &xf = state()->matrix;
if (pen.isCosmetic()) {
clipRect = d->exDeviceRect;
cpRect.translate(xf.dx(), xf.dy());
} else {
clipRect = xf.inverted().mapRect(QRectF(d->exDeviceRect));
}
// Check to avoid generating unwieldy amount of dashes that will not be visible anyway
QRectF extentRect = cpRect & clipRect;
qreal extent = qMax(extentRect.width(), extentRect.height());
qreal patternLength = 0;
const QList<qreal> pattern = pen.dashPattern();
const int patternSize = qMin(pattern.size(), 32);
for (int i = 0; i < patternSize; i++)
patternLength += qMax(pattern.at(i), qreal(0));
if (pen.widthF())
patternLength *= pen.widthF();
if (qFuzzyIsNull(patternLength)) {
pen.setStyle(Qt::NoPen);
} else if (extent / patternLength > 10000) {
// approximate stream of tiny dashes with semi-transparent solid line
pen.setStyle(Qt::SolidLine);
QColor color(pen.color());
color.setAlpha(color.alpha() / 2);
pen.setColor(color);
}
}
if (!qpen_fast_equals(pen, d->strokerPen)) {
d->strokerPen = pen;
d->stroker.setJoinStyle(pen.joinStyle());
d->stroker.setCapStyle(pen.capStyle());
d->stroker.setMiterLimit(pen.miterLimit());
qreal penWidth = pen.widthF();
if (penWidth == 0)
d->stroker.setStrokeWidth(1);
else
d->stroker.setStrokeWidth(penWidth);
Qt::PenStyle style = pen.style();
if (style == Qt::SolidLine) {
d->activeStroker = &d->stroker;
} else if (style == Qt::NoPen) {
d->activeStroker = nullptr;
} else {
d->dasher.setDashPattern(pen.dashPattern());
d->dasher.setDashOffset(pen.dashOffset());
d->activeStroker = &d->dasher;
}
}
if (!d->activeStroker) {
return;
}
if (!clipRect.isNull())
d->activeStroker->setClipRect(clipRect);
if (d->activeStroker == &d->stroker)
d->stroker.setForceOpen(path.hasExplicitOpen());
const QPainterPath::ElementType *types = path.elements();
const qreal *points = path.points();
int pointCount = path.elementCount();
const qreal *lastPoint = points + (pointCount<<1);
d->strokeHandler->types.reset();
d->strokeHandler->pts.reset();
// Some engines might decide to optimize for the non-shape hint later on...
uint flags = QVectorPath::WindingFill;
if (path.elementCount() > 2)
flags |= QVectorPath::NonConvexShapeMask;
if (d->stroker.capStyle() == Qt::RoundCap || d->stroker.joinStyle() == Qt::RoundJoin)
flags |= QVectorPath::CurvedShapeMask;
// ### Perspective Xforms are currently not supported...
if (!pen.isCosmetic()) {
// We include cosmetic pens in this case to avoid having to
// change the current transform. Normal transformed,
// non-cosmetic pens will be transformed as part of fill
// later, so they are also covered here..
d->activeStroker->setCurveThresholdFromTransform(state()->matrix);
d->activeStroker->begin(d->strokeHandler);
if (types) {
while (points < lastPoint) {
switch (*types) {
case QPainterPath::MoveToElement:
d->activeStroker->moveTo(points[0], points[1]);
points += 2;
++types;
break;
case QPainterPath::LineToElement:
d->activeStroker->lineTo(points[0], points[1]);
points += 2;
++types;
break;
case QPainterPath::CurveToElement:
d->activeStroker->cubicTo(points[0], points[1],
points[2], points[3],
points[4], points[5]);
points += 6;
types += 3;
flags |= QVectorPath::CurvedShapeMask;
break;
default:
break;
}
}
if (path.hasImplicitClose())
d->activeStroker->lineTo(path.points()[0], path.points()[1]);
} else {
d->activeStroker->moveTo(points[0], points[1]);
points += 2;
while (points < lastPoint) {
d->activeStroker->lineTo(points[0], points[1]);
points += 2;
}
if (path.hasImplicitClose())
d->activeStroker->lineTo(path.points()[0], path.points()[1]);
}
d->activeStroker->end();
if (!d->strokeHandler->types.size()) // an empty path...
return;
QVectorPath strokePath(d->strokeHandler->pts.data(),
d->strokeHandler->types.size(),
d->strokeHandler->types.data(),
flags);
fill(strokePath, pen.brush());
} else {
// For cosmetic pens we need a bit of trickery... We to process xform the input points
if (state()->matrix.type() >= QTransform::TxProject) {
QPainterPath painterPath = state()->matrix.map(path.convertToPainterPath());
d->activeStroker->strokePath(painterPath, d->strokeHandler, QTransform());
} else {
d->activeStroker->setCurveThresholdFromTransform(QTransform());
d->activeStroker->begin(d->strokeHandler);
if (types) {
while (points < lastPoint) {
switch (*types) {
case QPainterPath::MoveToElement: {
QPointF pt = (*(const QPointF *) points) * state()->matrix;
d->activeStroker->moveTo(pt.x(), pt.y());
points += 2;
++types;
break;
}
case QPainterPath::LineToElement: {
QPointF pt = (*(const QPointF *) points) * state()->matrix;
d->activeStroker->lineTo(pt.x(), pt.y());
points += 2;
++types;
break;
}
case QPainterPath::CurveToElement: {
QPointF c1 = ((const QPointF *) points)[0] * state()->matrix;
QPointF c2 = ((const QPointF *) points)[1] * state()->matrix;
QPointF e = ((const QPointF *) points)[2] * state()->matrix;
d->activeStroker->cubicTo(c1.x(), c1.y(), c2.x(), c2.y(), e.x(), e.y());
points += 6;
types += 3;
flags |= QVectorPath::CurvedShapeMask;
break;
}
default:
break;
}
}
if (path.hasImplicitClose()) {
QPointF pt = * ((const QPointF *) path.points()) * state()->matrix;
d->activeStroker->lineTo(pt.x(), pt.y());
}
} else {
QPointF p = ((const QPointF *)points)[0] * state()->matrix;
d->activeStroker->moveTo(p.x(), p.y());
points += 2;
while (points < lastPoint) {
QPointF p = ((const QPointF *)points)[0] * state()->matrix;
d->activeStroker->lineTo(p.x(), p.y());
points += 2;
}
if (path.hasImplicitClose())
d->activeStroker->lineTo(p.x(), p.y());
}
d->activeStroker->end();
}
QVectorPath strokePath(d->strokeHandler->pts.data(),
d->strokeHandler->types.size(),
d->strokeHandler->types.data(),
flags);
QTransform xform = state()->matrix;
state()->matrix = QTransform();
transformChanged();
QBrush brush = pen.brush();
if (qbrush_style(brush) != Qt::SolidPattern)
brush.setTransform(brush.transform() * xform);
fill(strokePath, brush);
state()->matrix = xform;
transformChanged();
}
}
| null | null | 202,256
|
55204517510126430026163855942382840984
| 235
|
Improve fix for avoiding huge number of tiny dashes
Some pathological cases were not caught by the previous fix.
Fixes: QTBUG-95239
Pick-to: 6.2 6.1 5.15
Change-Id: I0337ee3923ff93ccb36c4d7b810a9c0667354cc5
Reviewed-by: Robert Löhning <[email protected]>
|
other
|
vim
|
57df9e8a9f9ae1aafdde9b86b10ad907627a87dc
| 1
|
block_insert(
oparg_T *oap,
char_u *s,
int b_insert,
struct block_def *bdp)
{
int ts_val;
int count = 0; // extra spaces to replace a cut TAB
int spaces = 0; // non-zero if cutting a TAB
colnr_T offset; // pointer along new line
colnr_T startcol; // column where insert starts
unsigned s_len; // STRLEN(s)
char_u *newp, *oldp; // new, old lines
linenr_T lnum; // loop var
int oldstate = State;
State = INSERT; // don't want REPLACE for State
s_len = (unsigned)STRLEN(s);
for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++)
{
block_prep(oap, bdp, lnum, TRUE);
if (bdp->is_short && b_insert)
continue; // OP_INSERT, line ends before block start
oldp = ml_get(lnum);
if (b_insert)
{
ts_val = bdp->start_char_vcols;
spaces = bdp->startspaces;
if (spaces != 0)
count = ts_val - 1; // we're cutting a TAB
offset = bdp->textcol;
}
else // append
{
ts_val = bdp->end_char_vcols;
if (!bdp->is_short) // spaces = padding after block
{
spaces = (bdp->endspaces ? ts_val - bdp->endspaces : 0);
if (spaces != 0)
count = ts_val - 1; // we're cutting a TAB
offset = bdp->textcol + bdp->textlen - (spaces != 0);
}
else // spaces = padding to block edge
{
// if $ used, just append to EOL (ie spaces==0)
if (!bdp->is_MAX)
spaces = (oap->end_vcol - bdp->end_vcol) + 1;
count = spaces;
offset = bdp->textcol + bdp->textlen;
}
}
if (has_mbyte && spaces > 0)
{
int off;
// Avoid starting halfway a multi-byte character.
if (b_insert)
{
off = (*mb_head_off)(oldp, oldp + offset + spaces);
spaces -= off;
count -= off;
}
else
{
// spaces fill the gap, the character that's at the edge moves
// right
off = (*mb_head_off)(oldp, oldp + offset);
offset -= off;
}
}
if (spaces < 0) // can happen when the cursor was moved
spaces = 0;
// Make sure the allocated size matches what is actually copied below.
newp = alloc(STRLEN(oldp) + spaces + s_len
+ (spaces > 0 && !bdp->is_short ? ts_val - spaces : 0)
+ count + 1);
if (newp == NULL)
continue;
// copy up to shifted part
mch_memmove(newp, oldp, (size_t)offset);
oldp += offset;
// insert pre-padding
vim_memset(newp + offset, ' ', (size_t)spaces);
startcol = offset + spaces;
// copy the new text
mch_memmove(newp + startcol, s, (size_t)s_len);
offset += s_len;
if (spaces > 0 && !bdp->is_short)
{
if (*oldp == TAB)
{
// insert post-padding
vim_memset(newp + offset + spaces, ' ',
(size_t)(ts_val - spaces));
// we're splitting a TAB, don't copy it
oldp++;
// We allowed for that TAB, remember this now
count++;
}
else
// Not a TAB, no extra spaces
count = spaces;
}
if (spaces > 0)
offset += count;
STRMOVE(newp + offset, oldp);
ml_replace(lnum, newp, FALSE);
if (b_insert)
// correct any text properties
inserted_bytes(lnum, startcol, s_len);
if (lnum == oap->end.lnum)
{
// Set "']" mark to the end of the block instead of the end of
// the insert in the first line.
curbuf->b_op_end.lnum = oap->end.lnum;
curbuf->b_op_end.col = offset;
}
} // for all lnum
changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L);
State = oldstate;
}
| null | null | 202,276
|
189173942762862898619196400675767937016
| 136
|
patch 8.2.4151: reading beyond the end of a line
Problem: Reading beyond the end of a line.
Solution: For block insert only use the offset for correcting the length.
|
other
|
vim
|
65b605665997fad54ef39a93199e305af2fe4d7f
| 1
|
find_match_text(colnr_T startcol, int regstart, char_u *match_text)
{
colnr_T col = startcol;
int c1, c2;
int len1, len2;
int match;
for (;;)
{
match = TRUE;
len2 = MB_CHAR2LEN(regstart); // skip regstart
for (len1 = 0; match_text[len1] != NUL; len1 += MB_CHAR2LEN(c1))
{
c1 = PTR2CHAR(match_text + len1);
c2 = PTR2CHAR(rex.line + col + len2);
if (c1 != c2 && (!rex.reg_ic || MB_CASEFOLD(c1) != MB_CASEFOLD(c2)))
{
match = FALSE;
break;
}
len2 += MB_CHAR2LEN(c2);
}
if (match
// check that no composing char follows
&& !(enc_utf8
&& utf_iscomposing(PTR2CHAR(rex.line + col + len2))))
{
cleanup_subexpr();
if (REG_MULTI)
{
rex.reg_startpos[0].lnum = rex.lnum;
rex.reg_startpos[0].col = col;
rex.reg_endpos[0].lnum = rex.lnum;
rex.reg_endpos[0].col = col + len2;
}
else
{
rex.reg_startp[0] = rex.line + col;
rex.reg_endp[0] = rex.line + col + len2;
}
return 1L;
}
// Try finding regstart after the current match.
col += MB_CHAR2LEN(regstart); // skip regstart
if (skip_to_start(regstart, &col) == FAIL)
break;
}
return 0L;
}
| null | null | 202,304
|
110852340714559231006619790061251971138
| 50
|
patch 8.2.3409: reading beyond end of line with invalid utf-8 character
Problem: Reading beyond end of line with invalid utf-8 character.
Solution: Check for NUL when advancing.
|
other
|
php-src
|
8fa9d1ce28f3a894b104979df30d0b65e0f21107
| 1
|
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)
{
unsigned int u = 0;
LineContribType *res;
int overflow_error = 0;
res = (LineContribType *) gdMalloc(sizeof(LineContribType));
if (!res) {
return NULL;
}
res->WindowSize = windows_size;
res->LineLength = line_length;
if (overflow2(line_length, sizeof(ContributionType))) {
gdFree(res);
return NULL;
}
res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));
if (res->ContribRow == NULL) {
gdFree(res);
return NULL;
}
for (u = 0 ; u < line_length ; u++) {
if (overflow2(windows_size, sizeof(double))) {
overflow_error = 1;
} else {
res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));
}
if (overflow_error == 1 || res->ContribRow[u].Weights == NULL) {
u--;
while (u >= 0) {
gdFree(res->ContribRow[u].Weights);
u--;
}
return NULL;
}
}
return res;
}
| null | null | 202,392
|
19140960796540862352900148581784184138
| 38
|
improve fix #72558, while (u>=0) with unsigned int will always be true
|
other
|
vim
|
d88934406c5375d88f8f1b65331c9f0cab68cc6c
| 1
|
append_command(char_u *cmd)
{
char_u *s = cmd;
char_u *d;
STRCAT(IObuff, ": ");
d = IObuff + STRLEN(IObuff);
while (*s != NUL && d - IObuff < IOSIZE - 7)
{
if (enc_utf8 ? (s[0] == 0xc2 && s[1] == 0xa0) : *s == 0xa0)
{
s += enc_utf8 ? 2 : 1;
STRCPY(d, "<a0>");
d += 4;
}
else
MB_COPY_CHAR(s, d);
}
*d = NUL;
}
| null | null | 202,600
|
134818511108757274321926311203770845382
| 20
|
patch 8.2.4895: buffer overflow with invalid command with composing chars
Problem: Buffer overflow with invalid command with composing chars.
Solution: Check that the whole character fits in the buffer.
|
other
|
linux
|
e9da0b56fe27206b49f39805f7dcda8a89379062
| 1
|
static int sr9700_rx_fixup(struct usbnet *dev, struct sk_buff *skb)
{
struct sk_buff *sr_skb;
int len;
/* skb content (packets) format :
* p0 p1 p2 ...... pm
* / \
* / \
* / \
* / \
* p0b0 p0b1 p0b2 p0b3 ...... p0b(n-4) p0b(n-3)...p0bn
*
* p0 : packet 0
* p0b0 : packet 0 byte 0
*
* b0: rx status
* b1: packet length (incl crc) low
* b2: packet length (incl crc) high
* b3..n-4: packet data
* bn-3..bn: ethernet packet crc
*/
if (unlikely(skb->len < SR_RX_OVERHEAD)) {
netdev_err(dev->net, "unexpected tiny rx frame\n");
return 0;
}
/* one skb may contains multiple packets */
while (skb->len > SR_RX_OVERHEAD) {
if (skb->data[0] != 0x40)
return 0;
/* ignore the CRC length */
len = (skb->data[1] | (skb->data[2] << 8)) - 4;
if (len > ETH_FRAME_LEN)
return 0;
/* the last packet of current skb */
if (skb->len == (len + SR_RX_OVERHEAD)) {
skb_pull(skb, 3);
skb->len = len;
skb_set_tail_pointer(skb, len);
skb->truesize = len + sizeof(struct sk_buff);
return 2;
}
/* skb_clone is used for address align */
sr_skb = skb_clone(skb, GFP_ATOMIC);
if (!sr_skb)
return 0;
sr_skb->len = len;
sr_skb->data = skb->data + 3;
skb_set_tail_pointer(sr_skb, len);
sr_skb->truesize = len + sizeof(struct sk_buff);
usbnet_skb_return(dev, sr_skb);
skb_pull(skb, len + SR_RX_OVERHEAD);
}
return 0;
}
| null | null | 202,652
|
195202623015285248525846769171078492631
| 63
|
sr9700: sanity check for packet length
A malicious device can leak heap data to user space
providing bogus frame lengths. Introduce a sanity check.
Signed-off-by: Oliver Neukum <[email protected]>
Reviewed-by: Grant Grundler <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
net
|
7892032cfe67f4bde6fc2ee967e45a8fbaf33756
| 1
|
static void ip6gre_err(struct sk_buff *skb, struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
const struct ipv6hdr *ipv6h = (const struct ipv6hdr *)skb->data;
__be16 *p = (__be16 *)(skb->data + offset);
int grehlen = offset + 4;
struct ip6_tnl *t;
__be16 flags;
flags = p[0];
if (flags&(GRE_CSUM|GRE_KEY|GRE_SEQ|GRE_ROUTING|GRE_VERSION)) {
if (flags&(GRE_VERSION|GRE_ROUTING))
return;
if (flags&GRE_KEY) {
grehlen += 4;
if (flags&GRE_CSUM)
grehlen += 4;
}
}
/* If only 8 bytes returned, keyed message will be dropped here */
if (!pskb_may_pull(skb, grehlen))
return;
ipv6h = (const struct ipv6hdr *)skb->data;
p = (__be16 *)(skb->data + offset);
t = ip6gre_tunnel_lookup(skb->dev, &ipv6h->daddr, &ipv6h->saddr,
flags & GRE_KEY ?
*(((__be32 *)p) + (grehlen / 4) - 1) : 0,
p[1]);
if (!t)
return;
switch (type) {
__u32 teli;
struct ipv6_tlv_tnl_enc_lim *tel;
__u32 mtu;
case ICMPV6_DEST_UNREACH:
net_dbg_ratelimited("%s: Path to destination invalid or inactive!\n",
t->parms.name);
break;
case ICMPV6_TIME_EXCEED:
if (code == ICMPV6_EXC_HOPLIMIT) {
net_dbg_ratelimited("%s: Too small hop limit or routing loop in tunnel!\n",
t->parms.name);
}
break;
case ICMPV6_PARAMPROB:
teli = 0;
if (code == ICMPV6_HDR_FIELD)
teli = ip6_tnl_parse_tlv_enc_lim(skb, skb->data);
if (teli && teli == be32_to_cpu(info) - 2) {
tel = (struct ipv6_tlv_tnl_enc_lim *) &skb->data[teli];
if (tel->encap_limit == 0) {
net_dbg_ratelimited("%s: Too small encapsulation limit or routing loop in tunnel!\n",
t->parms.name);
}
} else {
net_dbg_ratelimited("%s: Recipient unable to parse tunneled packet!\n",
t->parms.name);
}
break;
case ICMPV6_PKT_TOOBIG:
mtu = be32_to_cpu(info) - offset;
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
t->dev->mtu = mtu;
break;
}
if (time_before(jiffies, t->err_time + IP6TUNNEL_ERR_TIMEO))
t->err_count++;
else
t->err_count = 1;
t->err_time = jiffies;
}
| null | null | 202,659
|
282482266041275026104160850622813981004
| 77
|
ip6_gre: fix ip6gre_err() invalid reads
Andrey Konovalov reported out of bound accesses in ip6gre_err()
If GRE flags contains GRE_KEY, the following expression
*(((__be32 *)p) + (grehlen / 4) - 1)
accesses data ~40 bytes after the expected point, since
grehlen includes the size of IPv6 headers.
Let's use a "struct gre_base_hdr *greh" pointer to make this
code more readable.
p[1] becomes greh->protocol.
grhlen is the GRE header length.
Fixes: c12b395a4664 ("gre: Support GRE over IPv6")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
qemu
|
9302e863aa8baa5d932fc078967050c055fa1a7f
| 1
|
static int parallels_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVParallelsState *s = bs->opaque;
int i;
struct parallels_header ph;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &ph, sizeof(ph));
if (ret < 0) {
goto fail;
}
if (memcmp(ph.magic, HEADER_MAGIC, 16) ||
(le32_to_cpu(ph.version) != HEADER_VERSION)) {
error_setg(errp, "Image not in Parallels format");
ret = -EINVAL;
goto fail;
}
bs->total_sectors = le32_to_cpu(ph.nb_sectors);
s->tracks = le32_to_cpu(ph.tracks);
s->catalog_size = le32_to_cpu(ph.catalog_entries);
if (s->catalog_size > INT_MAX / 4) {
error_setg(errp, "Catalog too large");
ret = -EFBIG;
goto fail;
}
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, 64, s->catalog_bitmap, s->catalog_size * 4);
if (ret < 0) {
goto fail;
}
for (i = 0; i < s->catalog_size; i++)
le32_to_cpus(&s->catalog_bitmap[i]);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
g_free(s->catalog_bitmap);
return ret;
}
| null | null | 202,677
|
205025634348399765258629432852861604866
| 49
|
parallels: Sanity check for s->tracks (CVE-2014-0142)
This avoids a possible division by zero.
Convert s->tracks to unsigned as well because it feels better than
surviving just because the results of calculations with s->tracks are
converted to unsigned anyway.
Signed-off-by: Kevin Wolf <[email protected]>
Reviewed-by: Max Reitz <[email protected]>
Signed-off-by: Stefan Hajnoczi <[email protected]>
|
other
|
spice
|
ca5bbc5692e052159bce1a75f55dc60b36078749
| 1
|
static int reds_init_ssl(RedsState *reds)
{
const SSL_METHOD *ssl_method;
int return_code;
/* Limit connection to TLSv1.1 or newer.
* When some other SSL/TLS version becomes obsolete, add it to this
* variable. */
long ssl_options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION | SSL_OP_NO_TLSv1;
/* Global system initialization*/
openssl_global_init();
/* Create our context*/
/* SSLv23_method() handles TLSv1.x in addition to SSLv2/v3 */
ssl_method = SSLv23_method();
reds->ctx = SSL_CTX_new(ssl_method);
if (!reds->ctx) {
spice_warning("Could not allocate new SSL context");
red_dump_openssl_errors();
return -1;
}
SSL_CTX_set_options(reds->ctx, ssl_options);
#if HAVE_DECL_SSL_CTX_SET_ECDH_AUTO || defined(SSL_CTX_set_ecdh_auto)
SSL_CTX_set_ecdh_auto(reds->ctx, 1);
#endif
/* Load our keys and certificates*/
return_code = SSL_CTX_use_certificate_chain_file(reds->ctx, reds->config->ssl_parameters.certs_file);
if (return_code == 1) {
spice_debug("Loaded certificates from %s", reds->config->ssl_parameters.certs_file);
} else {
spice_warning("Could not load certificates from %s", reds->config->ssl_parameters.certs_file);
red_dump_openssl_errors();
return -1;
}
SSL_CTX_set_default_passwd_cb(reds->ctx, ssl_password_cb);
SSL_CTX_set_default_passwd_cb_userdata(reds->ctx, reds);
return_code = SSL_CTX_use_PrivateKey_file(reds->ctx, reds->config->ssl_parameters.private_key_file,
SSL_FILETYPE_PEM);
if (return_code == 1) {
spice_debug("Using private key from %s", reds->config->ssl_parameters.private_key_file);
} else {
spice_warning("Could not use private key file");
return -1;
}
/* Load the CAs we trust*/
return_code = SSL_CTX_load_verify_locations(reds->ctx, reds->config->ssl_parameters.ca_certificate_file, 0);
if (return_code == 1) {
spice_debug("Loaded CA certificates from %s", reds->config->ssl_parameters.ca_certificate_file);
} else {
spice_warning("Could not use CA file %s", reds->config->ssl_parameters.ca_certificate_file);
red_dump_openssl_errors();
return -1;
}
if (strlen(reds->config->ssl_parameters.dh_key_file) > 0) {
if (load_dh_params(reds->ctx, reds->config->ssl_parameters.dh_key_file) < 0) {
return -1;
}
}
SSL_CTX_set_session_id_context(reds->ctx, (const unsigned char *)"SPICE", 5);
if (strlen(reds->config->ssl_parameters.ciphersuite) > 0) {
if (!SSL_CTX_set_cipher_list(reds->ctx, reds->config->ssl_parameters.ciphersuite)) {
return -1;
}
}
return 0;
}
| null | null | 202,678
|
122101275279986190714681083473068742276
| 74
|
With OpenSSL 1.1: Disable client-initiated renegotiation.
Fixes issue #49
Fixes BZ#1904459
Signed-off-by: Julien Ropé <[email protected]>
Reported-by: BlackKD
Acked-by: Frediano Ziglio <[email protected]>
|
other
|
ghostpdl
|
450da26a76286a8342ec0864b3d113856709f8f6
| 1
|
lprn_is_black(gx_device_printer * pdev, int r, int h, int bx)
{
gx_device_lprn *const lprn = (gx_device_lprn *) pdev;
int bh = lprn->nBh;
int bpl = gdev_mem_bytes_per_scan_line(pdev);
int x, y, y0;
byte *p;
int maxY = lprn->BlockLine / lprn->nBh * lprn->nBh;
y0 = (r + h - bh) % maxY;
for (y = 0; y < bh; y++) {
p = &lprn->ImageBuf[(y0 + y) * bpl + bx * lprn->nBw];
for (x = 0; x < lprn->nBw; x++)
if (p[x] != 0)
return 1;
}
return 0;
}
| null | null | 202,688
|
319515655489925208859904763653214097371
| 19
|
Bug 701785: fixed sanitizer heap-buffer-overflow in lprn_is_black().
In contrib/lips4/gdevlprn.c:lprn_is_black(), it seems that bpl is not
necessarily a multiple of lprn->nBw, so we need to explicitly avoid straying
into the next line's data.
This also avoids accessing beyond our buffer if we are already on the last
line, and so fixes the sanitizer error.
Fixes:
./sanbin/gs -sOutputFile=tmp -sDEVICE=lips2p ../bug-701785.pdf
|
other
|
vim
|
8e4b76da1d7e987d43ca960dfbc372d1c617466f
| 1
|
fname_match(
regmatch_T *rmp,
char_u *name,
int ignore_case) // when TRUE ignore case, when FALSE use 'fic'
{
char_u *match = NULL;
char_u *p;
if (name != NULL)
{
// Ignore case when 'fileignorecase' or the argument is set.
rmp->rm_ic = p_fic || ignore_case;
if (vim_regexec(rmp, name, (colnr_T)0))
match = name;
else
{
// Replace $(HOME) with '~' and try matching again.
p = home_replace_save(NULL, name);
if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))
match = name;
vim_free(p);
}
}
return match;
}
| null | null | 202,708
|
330045075802093277169152303499913071625
| 26
|
patch 8.2.4901: NULL pointer access when using invalid pattern
Problem: NULL pointer access when using invalid pattern.
Solution: Check for failed regexp program.
|
other
|
linux
|
a2d859e3fc97e79d907761550dbc03ff1b36479c
| 1
|
struct sctp_chunk *sctp_make_strreset_req(
const struct sctp_association *asoc,
__u16 stream_num, __be16 *stream_list,
bool out, bool in)
{
__u16 stream_len = stream_num * sizeof(__u16);
struct sctp_strreset_outreq outreq;
struct sctp_strreset_inreq inreq;
struct sctp_chunk *retval;
__u16 outlen, inlen;
outlen = (sizeof(outreq) + stream_len) * out;
inlen = (sizeof(inreq) + stream_len) * in;
retval = sctp_make_reconf(asoc, outlen + inlen);
if (!retval)
return NULL;
if (outlen) {
outreq.param_hdr.type = SCTP_PARAM_RESET_OUT_REQUEST;
outreq.param_hdr.length = htons(outlen);
outreq.request_seq = htonl(asoc->strreset_outseq);
outreq.response_seq = htonl(asoc->strreset_inseq - 1);
outreq.send_reset_at_tsn = htonl(asoc->next_tsn - 1);
sctp_addto_chunk(retval, sizeof(outreq), &outreq);
if (stream_len)
sctp_addto_chunk(retval, stream_len, stream_list);
}
if (inlen) {
inreq.param_hdr.type = SCTP_PARAM_RESET_IN_REQUEST;
inreq.param_hdr.length = htons(inlen);
inreq.request_seq = htonl(asoc->strreset_outseq + out);
sctp_addto_chunk(retval, sizeof(inreq), &inreq);
if (stream_len)
sctp_addto_chunk(retval, stream_len, stream_list);
}
return retval;
}
| null | null | 202,719
|
58452041186560383274474518388153367104
| 44
|
sctp: account stream padding length for reconf chunk
sctp_make_strreset_req() makes repeated calls to sctp_addto_chunk()
which will automatically account for padding on each call. inreq and
outreq are already 4 bytes aligned, but the payload is not and doing
SCTP_PAD4(a + b) (which _sctp_make_chunk() did implicitly here) is
different from SCTP_PAD4(a) + SCTP_PAD4(b) and not enough. It led to
possible attempt to use more buffer than it was allocated and triggered
a BUG_ON.
Cc: Vlad Yasevich <[email protected]>
Cc: Neil Horman <[email protected]>
Cc: Greg KH <[email protected]>
Fixes: cc16f00f6529 ("sctp: add support for generating stream reconf ssn reset request chunk")
Reported-by: Eiichi Tsukata <[email protected]>
Signed-off-by: Eiichi Tsukata <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Signed-off-by: Marcelo Ricardo Leitner <[email protected]>
Reviewed-by: Xin Long <[email protected]>
Link: https://lore.kernel.org/r/b97c1f8b0c7ff79ac4ed206fc2c49d3612e0850c.1634156849.git.mleitner@redhat.com
Signed-off-by: Jakub Kicinski <[email protected]>
|
other
|
binaryen
|
6f599272c66f65472f5e4c8d759d5bca77e47da6
| 1
|
void WasmBinaryBuilder::visitRethrow(Rethrow* curr) {
BYN_TRACE("zz node: Rethrow\n");
curr->target = getExceptionTargetName(getU32LEB());
// This special target is valid only for delegates
assert(curr->target != DELEGATE_CALLER_TARGET);
curr->finalize();
}
| null | null | 202,734
|
209177550826884079893421252076067255380
| 7
|
Turn an assertion on not colliding with an internal name into an error (#4422)
Without this, the result in a build without assertions might be quite
confusing. See #4410
Also make the internal names more obviously internal names.
|
other
|
ImageMagick
|
fbb5e1c8211c4e88ecc367e784b79d457c300d6d
| 1
|
static Image *ReadTGAImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status;
PixelInfo
pixel;
Quantum
index;
register Quantum
*q;
register ssize_t
i,
x;
size_t
base,
flag,
offset,
real,
skip;
ssize_t
count,
y;
TGAInfo
tga_info;
unsigned char
j,
k,
pixels[4],
runlength;
unsigned int
alpha_bits;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read TGA header information.
*/
count=ReadBlob(image,1,&tga_info.id_length);
tga_info.colormap_type=(unsigned char) ReadBlobByte(image);
tga_info.image_type=(TGAImageType) ReadBlobByte(image);
if ((count != 1) ||
((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARGB) &&
(tga_info.image_type != TGAMonochrome) &&
(tga_info.image_type != TGARLEColormap) &&
(tga_info.image_type != TGARLERGB) &&
(tga_info.image_type != TGARLEMonochrome)) ||
(((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGARLEColormap)) &&
(tga_info.colormap_type == 0)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
tga_info.colormap_index=ReadBlobLSBShort(image);
tga_info.colormap_length=ReadBlobLSBShort(image);
tga_info.colormap_size=(unsigned char) ReadBlobByte(image);
tga_info.x_origin=ReadBlobLSBShort(image);
tga_info.y_origin=ReadBlobLSBShort(image);
tga_info.width=(unsigned short) ReadBlobLSBShort(image);
tga_info.height=(unsigned short) ReadBlobLSBShort(image);
tga_info.bits_per_pixel=(unsigned char) ReadBlobByte(image);
tga_info.attributes=(unsigned char) ReadBlobByte(image);
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if ((((tga_info.bits_per_pixel <= 1) || (tga_info.bits_per_pixel >= 17)) &&
(tga_info.bits_per_pixel != 24) && (tga_info.bits_per_pixel != 32)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Initialize image structure.
*/
image->columns=tga_info.width;
image->rows=tga_info.height;
alpha_bits=(tga_info.attributes & 0x0FU);
image->alpha_trait=(alpha_bits > 0) || (tga_info.bits_per_pixel == 32) ||
(tga_info.colormap_size == 32) ? BlendPixelTrait : UndefinedPixelTrait;
if ((tga_info.image_type != TGAColormap) &&
(tga_info.image_type != TGARLEColormap))
image->depth=(size_t) ((tga_info.bits_per_pixel <= 8) ? 8 :
(tga_info.bits_per_pixel <= 16) ? 5 : 8);
else
image->depth=(size_t) ((tga_info.colormap_size <= 8) ? 8 :
(tga_info.colormap_size <= 16) ? 5 : 8);
if ((tga_info.image_type == TGAColormap) ||
(tga_info.image_type == TGAMonochrome) ||
(tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome))
image->storage_class=PseudoClass;
image->compression=NoCompression;
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLEMonochrome) ||
(tga_info.image_type == TGARLERGB))
image->compression=RLECompression;
if (image->storage_class == PseudoClass)
{
if (tga_info.colormap_type != 0)
image->colors=tga_info.colormap_index+tga_info.colormap_length;
else
{
size_t
one;
one=1;
image->colors=one << tga_info.bits_per_pixel;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
}
if (tga_info.id_length != 0)
{
char
*comment;
size_t
length;
/*
TGA image comment.
*/
length=(size_t) tga_info.id_length;
comment=(char *) NULL;
if (~length >= (MagickPathExtent-1))
comment=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*comment));
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,tga_info.id_length,(unsigned char *) comment);
comment[tga_info.id_length]='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
}
if (tga_info.attributes & (1UL << 4))
{
if (tga_info.attributes & (1UL << 5))
SetImageArtifact(image,"tga:image-origin","TopRight");
else
SetImageArtifact(image,"tga:image-origin","BottomRight");
}
else
{
if (tga_info.attributes & (1UL << 5))
SetImageArtifact(image,"tga:image-origin","TopLeft");
else
SetImageArtifact(image,"tga:image-origin","BottomLeft");
}
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(image);
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
pixel.alpha=(MagickRealType) OpaqueAlpha;
if (tga_info.colormap_type != 0)
{
/*
Read TGA raster colormap.
*/
if (image->colors < tga_info.colormap_index)
image->colors=tga_info.colormap_index;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) tga_info.colormap_index; i++)
image->colormap[i]=pixel;
for ( ; i < (ssize_t) image->colors; i++)
{
switch (tga_info.colormap_size)
{
case 8:
default:
{
/*
Gray scale.
*/
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.green=pixel.red;
pixel.blue=pixel.red;
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of red green and blue.
*/
j=(unsigned char) ReadBlobByte(image);
k=(unsigned char) ReadBlobByte(image);
range=GetQuantumRange(5UL);
pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*(k & 0x03)
<< 3)+(1UL*(j & 0xe0) >> 5),range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
break;
}
case 24:
{
/*
8 bits each of blue, green and red.
*/
pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
break;
}
case 32:
{
/*
8 bits each of blue, green, red, and alpha.
*/
pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
pixel.alpha=(MagickRealType) ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
break;
}
}
image->colormap[i]=pixel;
}
}
/*
Convert TGA pixels to pixel packets.
*/
base=0;
flag=0;
skip=MagickFalse;
real=0;
index=0;
runlength=0;
offset=0;
for (y=0; y < (ssize_t) image->rows; y++)
{
real=offset;
if (((unsigned char) (tga_info.attributes & 0x20) >> 5) == 0)
real=image->rows-real-1;
q=QueueAuthenticPixels(image,0,(ssize_t) real,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((tga_info.image_type == TGARLEColormap) ||
(tga_info.image_type == TGARLERGB) ||
(tga_info.image_type == TGARLEMonochrome))
{
if (runlength != 0)
{
runlength--;
skip=flag != 0;
}
else
{
count=ReadBlob(image,1,&runlength);
if (count != 1)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
flag=runlength & 0x80;
if (flag != 0)
runlength-=128;
skip=MagickFalse;
}
}
if (skip == MagickFalse)
switch (tga_info.bits_per_pixel)
{
case 8:
default:
{
/*
Gray scale.
*/
index=(Quantum) ReadBlobByte(image);
if (tga_info.colormap_type != 0)
pixel=image->colormap[(ssize_t) ConstrainColormapIndex(image,
(ssize_t) index,exception)];
else
{
pixel.red=(MagickRealType) ScaleCharToQuantum((unsigned char)
index);
pixel.green=(MagickRealType) ScaleCharToQuantum((unsigned char)
index);
pixel.blue=(MagickRealType) ScaleCharToQuantum((unsigned char)
index);
}
break;
}
case 15:
case 16:
{
QuantumAny
range;
/*
5 bits each of RGB.
*/
if (ReadBlob(image,2,pixels) != 2)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
j=pixels[0];
k=pixels[1];
range=GetQuantumRange(5UL);
pixel.red=(MagickRealType) ScaleAnyToQuantum(1UL*(k & 0x7c) >> 2,
range);
pixel.green=(MagickRealType) ScaleAnyToQuantum((1UL*
(k & 0x03) << 3)+(1UL*(j & 0xe0) >> 5),range);
pixel.blue=(MagickRealType) ScaleAnyToQuantum(1UL*(j & 0x1f),range);
if (image->alpha_trait != UndefinedPixelTrait)
pixel.alpha=(MagickRealType) ((k & 0x80) == 0 ? (Quantum)
TransparentAlpha : (Quantum) OpaqueAlpha);
if (image->storage_class == PseudoClass)
index=(Quantum) ConstrainColormapIndex(image,((ssize_t) (k << 8))+
j,exception);
break;
}
case 24:
{
/*
BGR pixels.
*/
if (ReadBlob(image,3,pixels) != 3)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
break;
}
case 32:
{
/*
BGRA pixels.
*/
if (ReadBlob(image,4,pixels) != 4)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
pixel.blue=(MagickRealType) ScaleCharToQuantum(pixels[0]);
pixel.green=(MagickRealType) ScaleCharToQuantum(pixels[1]);
pixel.red=(MagickRealType) ScaleCharToQuantum(pixels[2]);
pixel.alpha=(MagickRealType) ScaleCharToQuantum(pixels[3]);
break;
}
}
if (status == MagickFalse)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
if (image->storage_class == PseudoClass)
SetPixelIndex(image,index,q);
SetPixelRed(image,ClampToQuantum(pixel.red),q);
SetPixelGreen(image,ClampToQuantum(pixel.green),q);
SetPixelBlue(image,ClampToQuantum(pixel.blue),q);
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
/*
if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 4)
offset+=4;
else
*/
if (((unsigned char) (tga_info.attributes & 0xc0) >> 6) == 2)
offset+=2;
else
offset++;
if (offset >= image->rows)
{
base++;
offset=base;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| null | null | 202,748
|
281511796005500442391013181972918965488
| 416
|
...
|
other
|
php-src
|
37da90248deb2188e8ee50e4753ad6340679b425
| 1
|
static Bigint * Balloc(int k)
{
int x;
Bigint *rv;
_THREAD_PRIVATE_MUTEX_LOCK(dtoa_mutex);
if ((rv = freelist[k])) {
freelist[k] = rv->next;
} else {
x = 1 << k;
rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(Long));
rv->k = k;
rv->maxwds = x;
}
_THREAD_PRIVATE_MUTEX_UNLOCK(dtoa_mutex);
rv->sign = rv->wds = 0;
return rv;
}
| null | null | 202,783
|
231009551542821617823615060778329779561
| 18
|
Added missing allocation checks
|
other
|
libgcrypt
|
9010d1576e278a4274ad3f4aa15776c28f6ba965
| 1
|
_gcry_ecc_ecdsa_sign (gcry_mpi_t input, ECC_secret_key *skey,
gcry_mpi_t r, gcry_mpi_t s,
int flags, int hashalgo)
{
gpg_err_code_t rc = 0;
int extraloops = 0;
gcry_mpi_t k, dr, sum, k_1, x;
mpi_point_struct I;
gcry_mpi_t hash;
const void *abuf;
unsigned int abits, qbits;
mpi_ec_t ctx;
if (DBG_CIPHER)
log_mpidump ("ecdsa sign hash ", input );
qbits = mpi_get_nbits (skey->E.n);
/* Convert the INPUT into an MPI if needed. */
rc = _gcry_dsa_normalize_hash (input, &hash, qbits);
if (rc)
return rc;
k = NULL;
dr = mpi_alloc (0);
sum = mpi_alloc (0);
k_1 = mpi_alloc (0);
x = mpi_alloc (0);
point_init (&I);
ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0,
skey->E.p, skey->E.a, skey->E.b);
/* Two loops to avoid R or S are zero. This is more of a joke than
a real demand because the probability of them being zero is less
than any hardware failure. Some specs however require it. */
do
{
do
{
mpi_free (k);
k = NULL;
if ((flags & PUBKEY_FLAG_RFC6979) && hashalgo)
{
/* Use Pornin's method for deterministic DSA. If this
flag is set, it is expected that HASH is an opaque
MPI with the to be signed hash. That hash is also
used as h1 from 3.2.a. */
if (!mpi_is_opaque (input))
{
rc = GPG_ERR_CONFLICT;
goto leave;
}
abuf = mpi_get_opaque (input, &abits);
rc = _gcry_dsa_gen_rfc6979_k (&k, skey->E.n, skey->d,
abuf, (abits+7)/8,
hashalgo, extraloops);
if (rc)
goto leave;
extraloops++;
}
else
k = _gcry_dsa_gen_k (skey->E.n, GCRY_STRONG_RANDOM);
_gcry_mpi_ec_mul_point (&I, k, &skey->E.G, ctx);
if (_gcry_mpi_ec_get_affine (x, NULL, &I, ctx))
{
if (DBG_CIPHER)
log_debug ("ecc sign: Failed to get affine coordinates\n");
rc = GPG_ERR_BAD_SIGNATURE;
goto leave;
}
mpi_mod (r, x, skey->E.n); /* r = x mod n */
}
while (!mpi_cmp_ui (r, 0));
mpi_mulm (dr, skey->d, r, skey->E.n); /* dr = d*r mod n */
mpi_addm (sum, hash, dr, skey->E.n); /* sum = hash + (d*r) mod n */
mpi_invm (k_1, k, skey->E.n); /* k_1 = k^(-1) mod n */
mpi_mulm (s, k_1, sum, skey->E.n); /* s = k^(-1)*(hash+(d*r)) mod n */
}
while (!mpi_cmp_ui (s, 0));
if (DBG_CIPHER)
{
log_mpidump ("ecdsa sign result r ", r);
log_mpidump ("ecdsa sign result s ", s);
}
leave:
_gcry_mpi_ec_free (ctx);
point_free (&I);
mpi_free (x);
mpi_free (k_1);
mpi_free (sum);
mpi_free (dr);
mpi_free (k);
if (hash != input)
mpi_free (hash);
return rc;
}
| null | null | 202,810
|
327910537146800834594419330554438042950
| 104
|
ecc: Add blinding for ECDSA.
* cipher/ecc-ecdsa.c (_gcry_ecc_ecdsa_sign): Blind secret D with
randomized nonce B.
--
Reported-by: Keegan Ryan <[email protected]>
CVE-id: CVE-2018-0495
Signed-off-by: NIIBE Yutaka <[email protected]>
|
other
|
ghostpdl
|
5d499272b95a6b890a1397e11d20937de000d31b
| 1
|
search_impl(i_ctx_t *i_ctx_p, bool forward)
{
os_ptr op = osp;
os_ptr op1 = op - 1;
uint size = r_size(op);
uint count;
byte *pat;
byte *ptr;
byte ch;
int incr = forward ? 1 : -1;
check_read_type(*op1, t_string);
check_read_type(*op, t_string);
if (size > r_size(op1)) { /* can't match */
make_false(op);
return 0;
}
count = r_size(op1) - size;
ptr = op1->value.bytes;
if (size == 0)
goto found;
if (!forward)
ptr += count;
pat = op->value.bytes;
ch = pat[0];
do {
if (*ptr == ch && (size == 1 || !memcmp(ptr, pat, size)))
goto found;
ptr += incr;
}
while (count--);
/* No match */
make_false(op);
return 0;
found:
op->tas.type_attrs = op1->tas.type_attrs;
op->value.bytes = ptr;
r_set_size(op, size);
push(2);
op[-1] = *op1;
r_set_size(op - 1, ptr - op[-1].value.bytes);
op1->value.bytes = ptr + size;
r_set_size(op1, count + (!forward ? (size - 1) : 0));
make_true(op);
return 0;
}
| null | null | 202,822
|
249132726675055919779887509398809507782
| 46
|
Bug 702582, CVE 2020-15900 Memory Corruption in Ghostscript 9.52
Fix the 'rsearch' calculation for the 'post' size to give the correct
size. Previous calculation would result in a size that was too large,
and could underflow to max uint32_t. Also fix 'rsearch' to return the
correct 'pre' string with empty string match.
A future change may 'undefine' this undocumented, non-standard operator
during initialization as we do with the many other non-standard internal
PostScript operators and procedures.
|
other
|
linux
|
ebe48d368e97d007bfeb76fcb065d6cfc4c96645
| 1
|
int esp_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)
{
u8 *tail;
int nfrags;
int esph_offset;
struct page *page;
struct sk_buff *trailer;
int tailen = esp->tailen;
/* this is non-NULL only with TCP/UDP Encapsulation */
if (x->encap) {
int err = esp_output_encap(x, skb, esp);
if (err < 0)
return err;
}
if (!skb_cloned(skb)) {
if (tailen <= skb_tailroom(skb)) {
nfrags = 1;
trailer = skb;
tail = skb_tail_pointer(trailer);
goto skip_cow;
} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)
&& !skb_has_frag_list(skb)) {
int allocsize;
struct sock *sk = skb->sk;
struct page_frag *pfrag = &x->xfrag;
esp->inplace = false;
allocsize = ALIGN(tailen, L1_CACHE_BYTES);
spin_lock_bh(&x->lock);
if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
spin_unlock_bh(&x->lock);
goto cow;
}
page = pfrag->page;
get_page(page);
tail = page_address(page) + pfrag->offset;
esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
nfrags = skb_shinfo(skb)->nr_frags;
__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,
tailen);
skb_shinfo(skb)->nr_frags = ++nfrags;
pfrag->offset = pfrag->offset + allocsize;
spin_unlock_bh(&x->lock);
nfrags++;
skb->len += tailen;
skb->data_len += tailen;
skb->truesize += tailen;
if (sk && sk_fullsock(sk))
refcount_add(tailen, &sk->sk_wmem_alloc);
goto out;
}
}
cow:
esph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);
nfrags = skb_cow_data(skb, tailen, &trailer);
if (nfrags < 0)
goto out;
tail = skb_tail_pointer(trailer);
esp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);
skip_cow:
esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
pskb_put(skb, trailer, tailen);
out:
return nfrags;
}
| null | null | 202,888
|
270266096297619480530305818103826612108
| 86
|
esp: Fix possible buffer overflow in ESP transformation
The maximum message size that can be send is bigger than
the maximum site that skb_page_frag_refill can allocate.
So it is possible to write beyond the allocated buffer.
Fix this by doing a fallback to COW in that case.
v2:
Avoid get get_order() costs as suggested by Linus Torvalds.
Fixes: cac2661c53f3 ("esp4: Avoid skb_cow_data whenever possible")
Fixes: 03e2a30f6a27 ("esp6: Avoid skb_cow_data whenever possible")
Reported-by: valis <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
|
other
|
linux
|
ebe48d368e97d007bfeb76fcb065d6cfc4c96645
| 1
|
int esp6_output_head(struct xfrm_state *x, struct sk_buff *skb, struct esp_info *esp)
{
u8 *tail;
int nfrags;
int esph_offset;
struct page *page;
struct sk_buff *trailer;
int tailen = esp->tailen;
if (x->encap) {
int err = esp6_output_encap(x, skb, esp);
if (err < 0)
return err;
}
if (!skb_cloned(skb)) {
if (tailen <= skb_tailroom(skb)) {
nfrags = 1;
trailer = skb;
tail = skb_tail_pointer(trailer);
goto skip_cow;
} else if ((skb_shinfo(skb)->nr_frags < MAX_SKB_FRAGS)
&& !skb_has_frag_list(skb)) {
int allocsize;
struct sock *sk = skb->sk;
struct page_frag *pfrag = &x->xfrag;
esp->inplace = false;
allocsize = ALIGN(tailen, L1_CACHE_BYTES);
spin_lock_bh(&x->lock);
if (unlikely(!skb_page_frag_refill(allocsize, pfrag, GFP_ATOMIC))) {
spin_unlock_bh(&x->lock);
goto cow;
}
page = pfrag->page;
get_page(page);
tail = page_address(page) + pfrag->offset;
esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
nfrags = skb_shinfo(skb)->nr_frags;
__skb_fill_page_desc(skb, nfrags, page, pfrag->offset,
tailen);
skb_shinfo(skb)->nr_frags = ++nfrags;
pfrag->offset = pfrag->offset + allocsize;
spin_unlock_bh(&x->lock);
nfrags++;
skb->len += tailen;
skb->data_len += tailen;
skb->truesize += tailen;
if (sk && sk_fullsock(sk))
refcount_add(tailen, &sk->sk_wmem_alloc);
goto out;
}
}
cow:
esph_offset = (unsigned char *)esp->esph - skb_transport_header(skb);
nfrags = skb_cow_data(skb, tailen, &trailer);
if (nfrags < 0)
goto out;
tail = skb_tail_pointer(trailer);
esp->esph = (struct ip_esp_hdr *)(skb_transport_header(skb) + esph_offset);
skip_cow:
esp_output_fill_trailer(tail, esp->tfclen, esp->plen, esp->proto);
pskb_put(skb, trailer, tailen);
out:
return nfrags;
}
| null | null | 202,889
|
47880340213960570743612166400075138826
| 85
|
esp: Fix possible buffer overflow in ESP transformation
The maximum message size that can be send is bigger than
the maximum site that skb_page_frag_refill can allocate.
So it is possible to write beyond the allocated buffer.
Fix this by doing a fallback to COW in that case.
v2:
Avoid get get_order() costs as suggested by Linus Torvalds.
Fixes: cac2661c53f3 ("esp4: Avoid skb_cow_data whenever possible")
Fixes: 03e2a30f6a27 ("esp6: Avoid skb_cow_data whenever possible")
Reported-by: valis <[email protected]>
Signed-off-by: Steffen Klassert <[email protected]>
|
other
|
pure-ftpd
|
37ad222868e52271905b94afea4fc780d83294b4
| 1
|
void dostor(char *name, const int append, const int autorename)
{
ULHandler ulhandler;
int f;
const char *ul_name = NULL;
const char *atomic_file = NULL;
off_t filesize = (off_t) 0U;
struct stat st;
double started = 0.0;
signed char overwrite = 0;
int overflow = 0;
int ret = -1;
off_t max_filesize = (off_t) -1;
#ifdef QUOTAS
Quota quota;
#endif
const char *name2 = NULL;
if (type < 1 || (type == 1 && restartat > (off_t) 1)) {
addreply_noformat(503, MSG_NO_ASCII_RESUME);
goto end;
}
#ifndef ANON_CAN_RESUME
if (guest != 0 && anon_noupload != 0) {
addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);
goto end;
}
#endif
if (ul_check_free_space(name, -1.0) == 0) {
addreply_noformat(552, MSG_NO_DISK_SPACE);
goto end;
}
if (checknamesanity(name, dot_write_ok) != 0) {
addreply(553, MSG_SANITY_FILE_FAILURE, name);
goto end;
}
if (autorename != 0) {
no_truncate = 1;
}
if (restartat > (off_t) 0 || no_truncate != 0) {
if ((atomic_file = get_atomic_file(name)) == NULL) {
addreply(553, MSG_SANITY_FILE_FAILURE, name);
goto end;
}
if (restartat > (off_t) 0 &&
rename(name, atomic_file) != 0 && errno != ENOENT) {
error(553, MSG_RENAME_FAILURE);
atomic_file = NULL;
goto end;
}
}
if (atomic_file != NULL) {
ul_name = atomic_file;
} else {
ul_name = name;
}
if (atomic_file == NULL &&
(f = open(ul_name, O_WRONLY | O_NOFOLLOW)) != -1) {
overwrite++;
} else if ((f = open(ul_name, O_CREAT | O_WRONLY | O_NOFOLLOW,
(mode_t) 0777 & ~u_mask)) == -1) {
error(553, MSG_OPEN_FAILURE2);
goto end;
}
if (fstat(f, &st) < 0) {
(void) close(f);
error(553, MSG_STAT_FAILURE2);
goto end;
}
if (!S_ISREG(st.st_mode)) {
(void) close(f);
addreply_noformat(550, MSG_NOT_REGULAR_FILE);
goto end;
}
alarm(MAX_SESSION_XFER_IDLE);
/* Anonymous users *CAN* overwrite 0-bytes files - This is the right behavior */
if (st.st_size > (off_t) 0) {
#ifndef ANON_CAN_RESUME
if (guest != 0) {
addreply_noformat(550, MSG_ANON_CANT_OVERWRITE);
(void) close(f);
goto end;
}
#endif
if (append != 0) {
restartat = st.st_size;
}
} else {
restartat = (off_t) 0;
}
if (restartat > st.st_size) {
restartat = st.st_size;
}
if (restartat > (off_t) 0 && lseek(f, restartat, SEEK_SET) < (off_t) 0) {
(void) close(f);
error(451, "seek");
goto end;
}
if (restartat < st.st_size) {
if (ftruncate(f, restartat) < 0) {
(void) close(f);
error(451, "ftruncate");
goto end;
}
#ifdef QUOTAS
if (restartat != st.st_size) {
(void) quota_update(NULL, 0LL,
(long long) (restartat - st.st_size),
&overflow);
}
#endif
}
#ifdef QUOTAS
if (quota_update("a, 0LL, 0LL, &overflow) == 0 &&
(overflow > 0 || quota.files >= user_quota_files ||
quota.size > user_quota_size ||
(max_filesize >= (off_t) 0 &&
(max_filesize = user_quota_size - quota.size) < (off_t) 0))) {
overflow = 1;
(void) close(f);
goto afterquota;
}
#endif
opendata();
if (xferfd == -1) {
(void) close(f);
goto end;
}
doreply();
# ifdef WITH_TLS
if (data_protection_level == CPL_PRIVATE) {
tls_init_data_session(xferfd, passive);
}
# endif
state_needs_update = 1;
setprocessname("pure-ftpd (UPLOAD)");
filesize = restartat;
#ifdef FTPWHO
if (shm_data_cur != NULL) {
const size_t sl = strlen(name);
ftpwho_lock();
shm_data_cur->state = FTPWHO_STATE_UPLOAD;
shm_data_cur->download_total_size = (off_t) 0U;
shm_data_cur->download_current_size = (off_t) filesize;
shm_data_cur->restartat = restartat;
(void) time(&shm_data_cur->xfer_date);
if (sl < sizeof shm_data_cur->filename) {
memcpy(shm_data_cur->filename, name, sl);
shm_data_cur->filename[sl] = 0;
} else {
memcpy(shm_data_cur->filename,
&name[sl - sizeof shm_data_cur->filename - 1U],
sizeof shm_data_cur->filename);
}
ftpwho_unlock();
}
#endif
/* Here starts the real upload code */
started = get_usec_time();
if (ul_init(&ulhandler, clientfd, tls_cnx, xferfd, name, f, tls_data_cnx,
restartat, type == 1, throttling_bandwidth_ul,
max_filesize) == 0) {
ret = ul_send(&ulhandler);
ul_exit(&ulhandler);
} else {
ret = -1;
}
(void) close(f);
closedata();
/* Here ends the real upload code */
#ifdef SHOW_REAL_DISK_SPACE
if (FSTATFS(f, &statfsbuf) == 0) {
double space;
space = (double) STATFS_BAVAIL(statfsbuf) *
(double) STATFS_FRSIZE(statfsbuf);
if (space > 524288.0) {
addreply(0, MSG_SPACE_FREE_M, space / 1048576.0);
} else {
addreply(0, MSG_SPACE_FREE_K, space / 1024.0);
}
}
#endif
uploaded += (unsigned long long) ulhandler.total_uploaded;
{
off_t atomic_file_size;
off_t original_file_size;
int files_count;
if (overwrite == 0) {
files_count = 1;
} else {
files_count = 0;
}
if (autorename != 0 && restartat == (off_t) 0) {
if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {
goto afterquota;
}
if (tryautorename(atomic_file, name, &name2) != 0) {
error(553, MSG_RENAME_FAILURE);
goto afterquota;
} else {
#ifdef QUOTAS
ul_quota_update(name2 ? name2 : name, 1, atomic_file_size);
#endif
atomic_file = NULL;
}
} else if (atomic_file != NULL) {
if ((atomic_file_size = get_file_size(atomic_file)) < (off_t) 0) {
goto afterquota;
}
if ((original_file_size = get_file_size(name)) < (off_t) 0 ||
restartat > original_file_size) {
original_file_size = restartat;
}
if (rename(atomic_file, name) != 0) {
error(553, MSG_RENAME_FAILURE);
goto afterquota;
} else {
#ifdef QUOTAS
overflow = ul_quota_update
(name, files_count, atomic_file_size - original_file_size);
#endif
atomic_file = NULL;
}
} else {
#ifdef QUOTAS
overflow = ul_quota_update
(name, files_count, ulhandler.total_uploaded);
#endif
}
}
afterquota:
if (overflow > 0) {
addreply(552, MSG_QUOTA_EXCEEDED, name);
} else {
if (ret == 0) {
addreply_noformat(226, MSG_TRANSFER_SUCCESSFUL);
} else {
addreply_noformat(451, MSG_ABORTED);
}
displayrate(MSG_UPLOADED, ulhandler.total_uploaded, started,
name2 ? name2 : name, 1);
}
end:
restartat = (off_t) 0;
if (atomic_file != NULL) {
unlink(atomic_file);
atomic_file = NULL;
}
}
| null | null | 202,892
|
113967088182698550414121557184153731623
| 260
|
Initialize the max upload file size when quotas are enabled
Due to an unwanted check, files causing the quota to be exceeded
were deleted after the upload, but not during the upload.
The bug was introduced in 2009 in version 1.0.23
Spotted by @DroidTest, thanks!
|
other
|
lua
|
42d40581dd919fb134c07027ca1ce0844c670daf
| 1
|
l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
CallInfo *ci = L->ci;
const char *msg;
va_list argp;
luaC_checkGC(L); /* error message uses memory */
va_start(argp, fmt);
msg = luaO_pushvfstring(L, fmt, argp); /* format message */
va_end(argp);
if (isLua(ci)) /* if Lua function, add source:line information */
luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
luaG_errormsg(L);
}
| null | null | 202,943
|
23560794294652279455191112369836796333
| 12
|
Save stack space while handling errors
Because error handling (luaG_errormsg) uses slots from EXTRA_STACK,
and some errors can recur (e.g., string overflow while creating an
error message in 'luaG_runerror', or a C-stack overflow before calling
the message handler), the code should use stack slots with parsimony.
This commit fixes the bug "Lua-stack overflow when C stack overflows
while handling an error".
|
other
|
openssh-portable
|
f3cbe43e28fe71427d41cfe3a17125b972710455
| 1
|
subprocess(const char *tag, const char *command,
int ac, char **av, FILE **child, u_int flags,
struct passwd *pw, privdrop_fn *drop_privs, privrestore_fn *restore_privs)
{
FILE *f = NULL;
struct stat st;
int fd, devnull, p[2], i;
pid_t pid;
char *cp, errmsg[512];
u_int nenv = 0;
char **env = NULL;
/* If dropping privs, then must specify user and restore function */
if (drop_privs != NULL && (pw == NULL || restore_privs == NULL)) {
error("%s: inconsistent arguments", tag); /* XXX fatal? */
return 0;
}
if (pw == NULL && (pw = getpwuid(getuid())) == NULL) {
error("%s: no user for current uid", tag);
return 0;
}
if (child != NULL)
*child = NULL;
debug3_f("%s command \"%s\" running as %s (flags 0x%x)",
tag, command, pw->pw_name, flags);
/* Check consistency */
if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
(flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0) {
error_f("inconsistent flags");
return 0;
}
if (((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0) != (child == NULL)) {
error_f("inconsistent flags/output");
return 0;
}
/*
* If executing an explicit binary, then verify the it exists
* and appears safe-ish to execute
*/
if (!path_absolute(av[0])) {
error("%s path is not absolute", tag);
return 0;
}
if (drop_privs != NULL)
drop_privs(pw);
if (stat(av[0], &st) == -1) {
error("Could not stat %s \"%s\": %s", tag,
av[0], strerror(errno));
goto restore_return;
}
if ((flags & SSH_SUBPROCESS_UNSAFE_PATH) == 0 &&
safe_path(av[0], &st, NULL, 0, errmsg, sizeof(errmsg)) != 0) {
error("Unsafe %s \"%s\": %s", tag, av[0], errmsg);
goto restore_return;
}
/* Prepare to keep the child's stdout if requested */
if (pipe(p) == -1) {
error("%s: pipe: %s", tag, strerror(errno));
restore_return:
if (restore_privs != NULL)
restore_privs();
return 0;
}
if (restore_privs != NULL)
restore_privs();
switch ((pid = fork())) {
case -1: /* error */
error("%s: fork: %s", tag, strerror(errno));
close(p[0]);
close(p[1]);
return 0;
case 0: /* child */
/* Prepare a minimal environment for the child. */
if ((flags & SSH_SUBPROCESS_PRESERVE_ENV) == 0) {
nenv = 5;
env = xcalloc(sizeof(*env), nenv);
child_set_env(&env, &nenv, "PATH", _PATH_STDPATH);
child_set_env(&env, &nenv, "USER", pw->pw_name);
child_set_env(&env, &nenv, "LOGNAME", pw->pw_name);
child_set_env(&env, &nenv, "HOME", pw->pw_dir);
if ((cp = getenv("LANG")) != NULL)
child_set_env(&env, &nenv, "LANG", cp);
}
for (i = 1; i < NSIG; i++)
ssh_signal(i, SIG_DFL);
if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) {
error("%s: open %s: %s", tag, _PATH_DEVNULL,
strerror(errno));
_exit(1);
}
if (dup2(devnull, STDIN_FILENO) == -1) {
error("%s: dup2: %s", tag, strerror(errno));
_exit(1);
}
/* Set up stdout as requested; leave stderr in place for now. */
fd = -1;
if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) != 0)
fd = p[1];
else if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0)
fd = devnull;
if (fd != -1 && dup2(fd, STDOUT_FILENO) == -1) {
error("%s: dup2: %s", tag, strerror(errno));
_exit(1);
}
closefrom(STDERR_FILENO + 1);
if (setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) == -1) {
error("%s: setresgid %u: %s", tag, (u_int)pw->pw_gid,
strerror(errno));
_exit(1);
}
if (setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid) == -1) {
error("%s: setresuid %u: %s", tag, (u_int)pw->pw_uid,
strerror(errno));
_exit(1);
}
/* stdin is pointed to /dev/null at this point */
if ((flags & SSH_SUBPROCESS_STDOUT_DISCARD) != 0 &&
dup2(STDIN_FILENO, STDERR_FILENO) == -1) {
error("%s: dup2: %s", tag, strerror(errno));
_exit(1);
}
if (env != NULL)
execve(av[0], av, env);
else
execv(av[0], av);
error("%s %s \"%s\": %s", tag, env == NULL ? "execv" : "execve",
command, strerror(errno));
_exit(127);
default: /* parent */
break;
}
close(p[1]);
if ((flags & SSH_SUBPROCESS_STDOUT_CAPTURE) == 0)
close(p[0]);
else if ((f = fdopen(p[0], "r")) == NULL) {
error("%s: fdopen: %s", tag, strerror(errno));
close(p[0]);
/* Don't leave zombie child */
kill(pid, SIGTERM);
while (waitpid(pid, NULL, 0) == -1 && errno == EINTR)
;
return 0;
}
/* Success */
debug3_f("%s pid %ld", tag, (long)pid);
if (child != NULL)
*child = f;
return pid;
}
| null | null | 203,380
|
350016600644455653818986768745545464
| 158
|
upstream: need initgroups() before setresgid(); reported by anton@,
ok deraadt@
OpenBSD-Commit-ID: 6aa003ee658b316960d94078f2a16edbc25087ce
|
other
|
linux
|
a09d2d00af53b43c6f11e6ab3cb58443c2cac8a7
| 1
|
pxa3xx_gcu_write(struct file *file, const char *buff,
size_t count, loff_t *offp)
{
int ret;
unsigned long flags;
struct pxa3xx_gcu_batch *buffer;
struct pxa3xx_gcu_priv *priv = to_pxa3xx_gcu_priv(file);
int words = count / 4;
/* Does not need to be atomic. There's a lock in user space,
* but anyhow, this is just for statistics. */
priv->shared->num_writes++;
priv->shared->num_words += words;
/* Last word reserved for batch buffer end command */
if (words >= PXA3XX_GCU_BATCH_WORDS)
return -E2BIG;
/* Wait for a free buffer */
if (!priv->free) {
ret = pxa3xx_gcu_wait_free(priv);
if (ret < 0)
return ret;
}
/*
* Get buffer from free list
*/
spin_lock_irqsave(&priv->spinlock, flags);
buffer = priv->free;
priv->free = buffer->next;
spin_unlock_irqrestore(&priv->spinlock, flags);
/* Copy data from user into buffer */
ret = copy_from_user(buffer->ptr, buff, words * 4);
if (ret) {
spin_lock_irqsave(&priv->spinlock, flags);
buffer->next = priv->free;
priv->free = buffer;
spin_unlock_irqrestore(&priv->spinlock, flags);
return -EFAULT;
}
buffer->length = words;
/* Append batch buffer end command */
buffer->ptr[words] = 0x01000000;
/*
* Add buffer to ready list
*/
spin_lock_irqsave(&priv->spinlock, flags);
buffer->next = NULL;
if (priv->ready) {
BUG_ON(priv->ready_last == NULL);
priv->ready_last->next = buffer;
} else
priv->ready = buffer;
priv->ready_last = buffer;
if (!priv->shared->hw_running)
run_ready(priv);
spin_unlock_irqrestore(&priv->spinlock, flags);
return words * 4;
}
| null | null | 203,614
|
55183858501831120025410413636884805377
| 73
|
video: fbdev: pxa3xx-gcu: Fix integer overflow in pxa3xx_gcu_write
In pxa3xx_gcu_write, a count parameter of type size_t is passed to words of
type int. Then, copy_from_user() may cause a heap overflow because it is used
as the third argument of copy_from_user().
Signed-off-by: Hyunwoo Kim <[email protected]>
Signed-off-by: Helge Deller <[email protected]>
|
other
|
tty
|
15b3cd8ef46ad1b100e0d3c7e38774f330726820
| 1
|
con_insert_unipair(struct uni_pagedir *p, u_short unicode, u_short fontpos)
{
int i, n;
u16 **p1, *p2;
p1 = p->uni_pgdir[n = unicode >> 11];
if (!p1) {
p1 = p->uni_pgdir[n] = kmalloc_array(32, sizeof(u16 *),
GFP_KERNEL);
if (!p1) return -ENOMEM;
for (i = 0; i < 32; i++)
p1[i] = NULL;
}
p2 = p1[n = (unicode >> 6) & 0x1f];
if (!p2) {
p2 = p1[n] = kmalloc_array(64, sizeof(u16), GFP_KERNEL);
if (!p2) {
kfree(p1);
p->uni_pgdir[n] = NULL;
return -ENOMEM;
}
memset(p2, 0xff, 64*sizeof(u16)); /* No glyphs for the characters (yet) */
}
p2[unicode & 0x3f] = fontpos;
p->sum += (fontpos << 20) + unicode;
return 0;
}
| null | null | 203,622
|
61670946817080732094550256808909248342
| 31
|
Revert "consolemap: Fix a memory leaking bug in drivers/tty/vt/consolemap.c"
This reverts commit 84ecc2f6eb1cb12e6d44818f94fa49b50f06e6ac.
con_insert_unipair() is working with a sparse 3-dimensional array:
- p->uni_pgdir[] is the top layer
- p1 points to a middle layer
- p2 points to a bottom layer
If it needs to allocate a new middle layer, and then fails to allocate
a new bottom layer, it would previously free only p2, and now it frees
both p1 and p2. But since the new middle layer was already registered
in the top layer, it was not leaked.
However, if it looks up an *existing* middle layer and then fails to
allocate a bottom layer, it now frees both p1 and p2 but does *not*
free any other bottom layers under p1. So it *introduces* a memory
leak.
The error path also cleared the wrong index in p->uni_pgdir[],
introducing a use-after-free.
Signed-off-by: Ben Hutchings <[email protected]>
Fixes: 84ecc2f6eb1c ("consolemap: Fix a memory leaking bug in drivers/tty/vt/consolemap.c")
Signed-off-by: Greg Kroah-Hartman <[email protected]>
|
other
|
vim
|
4748c4bd64610cf943a431d215bb1aad51f8d0b4
| 1
|
get_one_sourceline(source_cookie_T *sp)
{
garray_T ga;
int len;
int c;
char_u *buf;
#ifdef USE_CRNL
int has_cr; // CR-LF found
#endif
int have_read = FALSE;
// use a growarray to store the sourced line
ga_init2(&ga, 1, 250);
// Loop until there is a finished line (or end-of-file).
++sp->sourcing_lnum;
for (;;)
{
// make room to read at least 120 (more) characters
if (ga_grow(&ga, 120) == FAIL)
break;
if (sp->source_from_buf)
{
if (sp->buf_lnum >= sp->buflines.ga_len)
break; // all the lines are processed
ga_concat(&ga, ((char_u **)sp->buflines.ga_data)[sp->buf_lnum]);
sp->buf_lnum++;
if (ga_grow(&ga, 1) == FAIL)
break;
buf = (char_u *)ga.ga_data;
buf[ga.ga_len++] = NUL;
}
else
{
buf = (char_u *)ga.ga_data;
if (fgets((char *)buf + ga.ga_len, ga.ga_maxlen - ga.ga_len,
sp->fp) == NULL)
break;
}
len = ga.ga_len + (int)STRLEN(buf + ga.ga_len);
#ifdef USE_CRNL
// Ignore a trailing CTRL-Z, when in Dos mode. Only recognize the
// CTRL-Z by its own, or after a NL.
if ( (len == 1 || (len >= 2 && buf[len - 2] == '\n'))
&& sp->fileformat == EOL_DOS
&& buf[len - 1] == Ctrl_Z)
{
buf[len - 1] = NUL;
break;
}
#endif
have_read = TRUE;
ga.ga_len = len;
// If the line was longer than the buffer, read more.
if (ga.ga_maxlen - ga.ga_len == 1 && buf[len - 1] != '\n')
continue;
if (len >= 1 && buf[len - 1] == '\n') // remove trailing NL
{
#ifdef USE_CRNL
has_cr = (len >= 2 && buf[len - 2] == '\r');
if (sp->fileformat == EOL_UNKNOWN)
{
if (has_cr)
sp->fileformat = EOL_DOS;
else
sp->fileformat = EOL_UNIX;
}
if (sp->fileformat == EOL_DOS)
{
if (has_cr) // replace trailing CR
{
buf[len - 2] = '\n';
--len;
--ga.ga_len;
}
else // lines like ":map xx yy^M" will have failed
{
if (!sp->error)
{
msg_source(HL_ATTR(HLF_W));
emsg(_("W15: Warning: Wrong line separator, ^M may be missing"));
}
sp->error = TRUE;
sp->fileformat = EOL_UNIX;
}
}
#endif
// The '\n' is escaped if there is an odd number of ^V's just
// before it, first set "c" just before the 'V's and then check
// len&c parities (is faster than ((len-c)%2 == 0)) -- Acevedo
for (c = len - 2; c >= 0 && buf[c] == Ctrl_V; c--)
;
if ((len & 1) != (c & 1)) // escaped NL, read more
{
++sp->sourcing_lnum;
continue;
}
buf[len - 1] = NUL; // remove the NL
}
// Check for ^C here now and then, so recursive :so can be broken.
line_breakcheck();
break;
}
if (have_read)
return (char_u *)ga.ga_data;
vim_free(ga.ga_data);
return NULL;
}
| null | null | 203,902
|
72171374327891008265530338722299232546
| 116
|
patch 8.2.4974: ":so" command may read after end of buffer
Problem: ":so" command may read after end of buffer.
Solution: Compute length of text properly.
|
other
|
linux
|
3e0588c291d6ce225f2b891753ca41d45ba42469
| 1
|
static void mkiss_close(struct tty_struct *tty)
{
struct mkiss *ax;
write_lock_irq(&disc_data_lock);
ax = tty->disc_data;
tty->disc_data = NULL;
write_unlock_irq(&disc_data_lock);
if (!ax)
return;
/*
* We have now ensured that nobody can start using ap from now on, but
* we have to wait for all existing users to finish.
*/
if (!refcount_dec_and_test(&ax->refcnt))
wait_for_completion(&ax->dead);
/*
* Halt the transmit queue so that a new transmit cannot scribble
* on our buffers
*/
netif_stop_queue(ax->dev);
/* Free all AX25 frame buffers. */
kfree(ax->rbuff);
kfree(ax->xbuff);
ax->tty = NULL;
unregister_netdev(ax->dev);
free_netdev(ax->dev);
}
| null | null | 203,980
|
109440345853446194360273736668132912271
| 33
|
hamradio: defer ax25 kfree after unregister_netdev
There is a possible race condition (use-after-free) like below
(USE) | (FREE)
ax25_sendmsg |
ax25_queue_xmit |
dev_queue_xmit |
__dev_queue_xmit |
__dev_xmit_skb |
sch_direct_xmit | ...
xmit_one |
netdev_start_xmit | tty_ldisc_kill
__netdev_start_xmit | mkiss_close
ax_xmit | kfree
ax_encaps |
|
Even though there are two synchronization primitives before the kfree:
1. wait_for_completion(&ax->dead). This can prevent the race with
routines from mkiss_ioctl. However, it cannot stop the routine coming
from upper layer, i.e., the ax25_sendmsg.
2. netif_stop_queue(ax->dev). It seems that this line of code aims to
halt the transmit queue but it fails to stop the routine that already
being xmit.
This patch reorder the kfree after the unregister_netdev to avoid the
possible UAF as the unregister_netdev() is well synchronized and won't
return if there is a running routine.
Signed-off-by: Lin Ma <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
squashfs-tools
|
e0485802ec72996c20026da320650d8362f555bd
| 1
|
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,
struct inode **i)
{
squashfs_dir_header_2 dirh;
char buffer[sizeof(squashfs_dir_entry_2) + SQUASHFS_NAME_LEN + 1]
__attribute__((aligned));
squashfs_dir_entry_2 *dire = (squashfs_dir_entry_2 *) buffer;
long long start;
int bytes = 0;
int dir_count, size, res;
struct dir_ent *ent, *cur_ent = NULL;
struct dir *dir;
TRACE("squashfs_opendir: inode start block %d, offset %d\n",
block_start, offset);
*i = read_inode(block_start, offset);
dir = malloc(sizeof(struct dir));
if(dir == NULL)
MEM_ERROR();
dir->dir_count = 0;
dir->cur_entry = NULL;
dir->mode = (*i)->mode;
dir->uid = (*i)->uid;
dir->guid = (*i)->gid;
dir->mtime = (*i)->time;
dir->xattr = (*i)->xattr;
dir->dirs = NULL;
if ((*i)->data == 0)
/*
* if the directory is empty, skip the unnecessary
* lookup_entry, this fixes the corner case with
* completely empty filesystems where lookup_entry correctly
* returning -1 is incorrectly treated as an error
*/
return dir;
start = sBlk.s.directory_table_start + (*i)->start;
offset = (*i)->offset;
size = (*i)->data + bytes;
while(bytes < size) {
if(swap) {
squashfs_dir_header_2 sdirh;
res = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh));
if(res)
SQUASHFS_SWAP_DIR_HEADER_2(&dirh, &sdirh);
} else
res = read_directory_data(&dirh, &start, &offset, sizeof(dirh));
if(res == FALSE)
goto corrupted;
dir_count = dirh.count + 1;
TRACE("squashfs_opendir: Read directory header @ byte position "
"%d, %d directory entries\n", bytes, dir_count);
bytes += sizeof(dirh);
/* dir_count should never be larger than SQUASHFS_DIR_COUNT */
if(dir_count > SQUASHFS_DIR_COUNT) {
ERROR("File system corrupted: too many entries in directory\n");
goto corrupted;
}
while(dir_count--) {
if(swap) {
squashfs_dir_entry_2 sdire;
res = read_directory_data(&sdire, &start,
&offset, sizeof(sdire));
if(res)
SQUASHFS_SWAP_DIR_ENTRY_2(dire, &sdire);
} else
res = read_directory_data(dire, &start,
&offset, sizeof(*dire));
if(res == FALSE)
goto corrupted;
bytes += sizeof(*dire);
/* size should never be SQUASHFS_NAME_LEN or larger */
if(dire->size >= SQUASHFS_NAME_LEN) {
ERROR("File system corrupted: filename too long\n");
goto corrupted;
}
res = read_directory_data(dire->name, &start, &offset,
dire->size + 1);
if(res == FALSE)
goto corrupted;
dire->name[dire->size + 1] = '\0';
/* check name for invalid characters (i.e /, ., ..) */
if(check_name(dire->name, dire->size + 1) == FALSE) {
ERROR("File system corrupted: invalid characters in name\n");
goto corrupted;
}
TRACE("squashfs_opendir: directory entry %s, inode "
"%d:%d, type %d\n", dire->name,
dirh.start_block, dire->offset, dire->type);
ent = malloc(sizeof(struct dir_ent));
if(ent == NULL)
MEM_ERROR();
ent->name = strdup(dire->name);
ent->start_block = dirh.start_block;
ent->offset = dire->offset;
ent->type = dire->type;
ent->next = NULL;
if(cur_ent == NULL)
dir->dirs = ent;
else
cur_ent->next = ent;
cur_ent = ent;
dir->dir_count ++;
bytes += dire->size + 1;
}
}
return dir;
corrupted:
squashfs_closedir(dir);
return NULL;
}
| null | null | 204,016
|
249889825501558863333296997095090562806
| 132
|
Unsquashfs: additional write outside destination directory exploit fix
An issue on github (https://github.com/plougher/squashfs-tools/issues/72)
showed how some specially crafted Squashfs filesystems containing
invalid file names (with '/' and '..') can cause Unsquashfs to write
files outside of the destination directory.
Since then it has been shown that specially crafted Squashfs filesystems
that contain a symbolic link pointing outside of the destination directory,
coupled with an identically named file within the same directory, can
cause Unsquashfs to write files outside of the destination directory.
Specifically the symbolic link produces a pathname pointing outside
of the destination directory, which is then followed when writing the
duplicate identically named file within the directory.
This commit fixes this exploit by explictly checking for duplicate
filenames within a directory. As directories in v2.1, v3.x, and v4.0
filesystems are sorted, this is achieved by checking for consecutively
identical filenames. Additionally directories are checked to
ensure they are sorted, to avoid attempts to evade the duplicate
check.
Version 1.x and 2.0 filesystems (where the directories were unsorted)
are sorted and then the above duplicate filename check is applied.
Signed-off-by: Phillip Lougher <[email protected]>
|
other
|
squashfs-tools
|
e0485802ec72996c20026da320650d8362f555bd
| 1
|
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,
struct inode **i)
{
squashfs_dir_header_3 dirh;
char buffer[sizeof(squashfs_dir_entry_3) + SQUASHFS_NAME_LEN + 1]
__attribute__((aligned));
squashfs_dir_entry_3 *dire = (squashfs_dir_entry_3 *) buffer;
long long start;
int bytes = 0;
int dir_count, size, res;
struct dir_ent *ent, *cur_ent = NULL;
struct dir *dir;
TRACE("squashfs_opendir: inode start block %d, offset %d\n",
block_start, offset);
*i = read_inode(block_start, offset);
dir = malloc(sizeof(struct dir));
if(dir == NULL)
MEM_ERROR();
dir->dir_count = 0;
dir->cur_entry = NULL;
dir->mode = (*i)->mode;
dir->uid = (*i)->uid;
dir->guid = (*i)->gid;
dir->mtime = (*i)->time;
dir->xattr = (*i)->xattr;
dir->dirs = NULL;
if ((*i)->data == 3)
/*
* if the directory is empty, skip the unnecessary
* lookup_entry, this fixes the corner case with
* completely empty filesystems where lookup_entry correctly
* returning -1 is incorrectly treated as an error
*/
return dir;
start = sBlk.s.directory_table_start + (*i)->start;
offset = (*i)->offset;
size = (*i)->data + bytes - 3;
while(bytes < size) {
if(swap) {
squashfs_dir_header_3 sdirh;
res = read_directory_data(&sdirh, &start, &offset, sizeof(sdirh));
if(res)
SQUASHFS_SWAP_DIR_HEADER_3(&dirh, &sdirh);
} else
res = read_directory_data(&dirh, &start, &offset, sizeof(dirh));
if(res == FALSE)
goto corrupted;
dir_count = dirh.count + 1;
TRACE("squashfs_opendir: Read directory header @ byte position "
"%d, %d directory entries\n", bytes, dir_count);
bytes += sizeof(dirh);
/* dir_count should never be larger than SQUASHFS_DIR_COUNT */
if(dir_count > SQUASHFS_DIR_COUNT) {
ERROR("File system corrupted: too many entries in directory\n");
goto corrupted;
}
while(dir_count--) {
if(swap) {
squashfs_dir_entry_3 sdire;
res = read_directory_data(&sdire, &start,
&offset, sizeof(sdire));
if(res)
SQUASHFS_SWAP_DIR_ENTRY_3(dire, &sdire);
} else
res = read_directory_data(dire, &start,
&offset, sizeof(*dire));
if(res == FALSE)
goto corrupted;
bytes += sizeof(*dire);
/* size should never be SQUASHFS_NAME_LEN or larger */
if(dire->size >= SQUASHFS_NAME_LEN) {
ERROR("File system corrupted: filename too long\n");
goto corrupted;
}
res = read_directory_data(dire->name, &start, &offset,
dire->size + 1);
if(res == FALSE)
goto corrupted;
dire->name[dire->size + 1] = '\0';
/* check name for invalid characters (i.e /, ., ..) */
if(check_name(dire->name, dire->size + 1) == FALSE) {
ERROR("File system corrupted: invalid characters in name\n");
goto corrupted;
}
TRACE("squashfs_opendir: directory entry %s, inode "
"%d:%d, type %d\n", dire->name,
dirh.start_block, dire->offset, dire->type);
ent = malloc(sizeof(struct dir_ent));
if(ent == NULL)
MEM_ERROR();
ent->name = strdup(dire->name);
ent->start_block = dirh.start_block;
ent->offset = dire->offset;
ent->type = dire->type;
ent->next = NULL;
if(cur_ent == NULL)
dir->dirs = ent;
else
cur_ent->next = ent;
cur_ent = ent;
dir->dir_count ++;
bytes += dire->size + 1;
}
}
return dir;
corrupted:
squashfs_closedir(dir);
return NULL;
}
| null | null | 204,017
|
65180591611652100911872766047415284947
| 132
|
Unsquashfs: additional write outside destination directory exploit fix
An issue on github (https://github.com/plougher/squashfs-tools/issues/72)
showed how some specially crafted Squashfs filesystems containing
invalid file names (with '/' and '..') can cause Unsquashfs to write
files outside of the destination directory.
Since then it has been shown that specially crafted Squashfs filesystems
that contain a symbolic link pointing outside of the destination directory,
coupled with an identically named file within the same directory, can
cause Unsquashfs to write files outside of the destination directory.
Specifically the symbolic link produces a pathname pointing outside
of the destination directory, which is then followed when writing the
duplicate identically named file within the directory.
This commit fixes this exploit by explictly checking for duplicate
filenames within a directory. As directories in v2.1, v3.x, and v4.0
filesystems are sorted, this is achieved by checking for consecutively
identical filenames. Additionally directories are checked to
ensure they are sorted, to avoid attempts to evade the duplicate
check.
Version 1.x and 2.0 filesystems (where the directories were unsorted)
are sorted and then the above duplicate filename check is applied.
Signed-off-by: Phillip Lougher <[email protected]>
|
other
|
squashfs-tools
|
e0485802ec72996c20026da320650d8362f555bd
| 1
|
static struct dir *squashfs_opendir(unsigned int block_start, unsigned int offset,
struct inode **i)
{
struct squashfs_dir_header dirh;
char buffer[sizeof(struct squashfs_dir_entry) + SQUASHFS_NAME_LEN + 1]
__attribute__((aligned));
struct squashfs_dir_entry *dire = (struct squashfs_dir_entry *) buffer;
long long start;
int bytes = 0, dir_count, size, res;
struct dir_ent *ent, *cur_ent = NULL;
struct dir *dir;
TRACE("squashfs_opendir: inode start block %d, offset %d\n",
block_start, offset);
*i = read_inode(block_start, offset);
dir = malloc(sizeof(struct dir));
if(dir == NULL)
MEM_ERROR();
dir->dir_count = 0;
dir->cur_entry = NULL;
dir->mode = (*i)->mode;
dir->uid = (*i)->uid;
dir->guid = (*i)->gid;
dir->mtime = (*i)->time;
dir->xattr = (*i)->xattr;
dir->dirs = NULL;
if ((*i)->data == 3)
/*
* if the directory is empty, skip the unnecessary
* lookup_entry, this fixes the corner case with
* completely empty filesystems where lookup_entry correctly
* returning -1 is incorrectly treated as an error
*/
return dir;
start = sBlk.s.directory_table_start + (*i)->start;
offset = (*i)->offset;
size = (*i)->data + bytes - 3;
while(bytes < size) {
res = read_directory_data(&dirh, &start, &offset, sizeof(dirh));
if(res == FALSE)
goto corrupted;
SQUASHFS_INSWAP_DIR_HEADER(&dirh);
dir_count = dirh.count + 1;
TRACE("squashfs_opendir: Read directory header @ byte position "
"%d, %d directory entries\n", bytes, dir_count);
bytes += sizeof(dirh);
/* dir_count should never be larger than SQUASHFS_DIR_COUNT */
if(dir_count > SQUASHFS_DIR_COUNT) {
ERROR("File system corrupted: too many entries in directory\n");
goto corrupted;
}
while(dir_count--) {
res = read_directory_data(dire, &start, &offset, sizeof(*dire));
if(res == FALSE)
goto corrupted;
SQUASHFS_INSWAP_DIR_ENTRY(dire);
bytes += sizeof(*dire);
/* size should never be SQUASHFS_NAME_LEN or larger */
if(dire->size >= SQUASHFS_NAME_LEN) {
ERROR("File system corrupted: filename too long\n");
goto corrupted;
}
res = read_directory_data(dire->name, &start, &offset,
dire->size + 1);
if(res == FALSE)
goto corrupted;
dire->name[dire->size + 1] = '\0';
/* check name for invalid characters (i.e /, ., ..) */
if(check_name(dire->name, dire->size + 1) == FALSE) {
ERROR("File system corrupted: invalid characters in name\n");
goto corrupted;
}
TRACE("squashfs_opendir: directory entry %s, inode "
"%d:%d, type %d\n", dire->name,
dirh.start_block, dire->offset, dire->type);
ent = malloc(sizeof(struct dir_ent));
if(ent == NULL)
MEM_ERROR();
ent->name = strdup(dire->name);
ent->start_block = dirh.start_block;
ent->offset = dire->offset;
ent->type = dire->type;
ent->next = NULL;
if(cur_ent == NULL)
dir->dirs = ent;
else
cur_ent->next = ent;
cur_ent = ent;
dir->dir_count ++;
bytes += dire->size + 1;
}
}
return dir;
corrupted:
squashfs_closedir(dir);
return NULL;
}
| null | null | 204,019
|
203023810028621610367352788556875280124
| 118
|
Unsquashfs: additional write outside destination directory exploit fix
An issue on github (https://github.com/plougher/squashfs-tools/issues/72)
showed how some specially crafted Squashfs filesystems containing
invalid file names (with '/' and '..') can cause Unsquashfs to write
files outside of the destination directory.
Since then it has been shown that specially crafted Squashfs filesystems
that contain a symbolic link pointing outside of the destination directory,
coupled with an identically named file within the same directory, can
cause Unsquashfs to write files outside of the destination directory.
Specifically the symbolic link produces a pathname pointing outside
of the destination directory, which is then followed when writing the
duplicate identically named file within the directory.
This commit fixes this exploit by explictly checking for duplicate
filenames within a directory. As directories in v2.1, v3.x, and v4.0
filesystems are sorted, this is achieved by checking for consecutively
identical filenames. Additionally directories are checked to
ensure they are sorted, to avoid attempts to evade the duplicate
check.
Version 1.x and 2.0 filesystems (where the directories were unsorted)
are sorted and then the above duplicate filename check is applied.
Signed-off-by: Phillip Lougher <[email protected]>
|
other
|
linux
|
1d0688421449718c6c5f46e458a378c9b530ba18
| 1
|
static void virtbt_rx_handle(struct virtio_bluetooth *vbt, struct sk_buff *skb)
{
__u8 pkt_type;
pkt_type = *((__u8 *) skb->data);
skb_pull(skb, 1);
switch (pkt_type) {
case HCI_EVENT_PKT:
case HCI_ACLDATA_PKT:
case HCI_SCODATA_PKT:
case HCI_ISODATA_PKT:
hci_skb_pkt_type(skb) = pkt_type;
hci_recv_frame(vbt->hdev, skb);
break;
}
}
| null | null | 204,032
|
199763378789109669708686623689433331973
| 17
|
Bluetooth: virtio_bt: fix memory leak in virtbt_rx_handle()
On the reception of packets with an invalid packet type, the memory of
the allocated socket buffers is never freed. Add a default case that frees
these to avoid a memory leak.
Fixes: afd2daa26c7a ("Bluetooth: Add support for virtio transport driver")
Signed-off-by: Soenke Huster <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
|
other
|
net
|
b922f622592af76b57cbc566eaeccda0b31a3496
| 1
|
int hw_atl_utils_fw_rpc_wait(struct aq_hw_s *self,
struct hw_atl_utils_fw_rpc **rpc)
{
struct aq_hw_atl_utils_fw_rpc_tid_s sw;
struct aq_hw_atl_utils_fw_rpc_tid_s fw;
int err = 0;
do {
sw.val = aq_hw_read_reg(self, HW_ATL_RPC_CONTROL_ADR);
self->rpc_tid = sw.tid;
err = readx_poll_timeout_atomic(hw_atl_utils_rpc_state_get,
self, fw.val,
sw.tid == fw.tid,
1000U, 100000U);
if (err < 0)
goto err_exit;
err = aq_hw_err_from_flags(self);
if (err < 0)
goto err_exit;
if (fw.len == 0xFFFFU) {
err = hw_atl_utils_fw_rpc_call(self, sw.len);
if (err < 0)
goto err_exit;
}
} while (sw.tid != fw.tid || 0xFFFFU == fw.len);
if (rpc) {
if (fw.len) {
err =
hw_atl_utils_fw_downld_dwords(self,
self->rpc_addr,
(u32 *)(void *)
&self->rpc,
(fw.len + sizeof(u32) -
sizeof(u8)) /
sizeof(u32));
if (err < 0)
goto err_exit;
}
*rpc = &self->rpc;
}
err_exit:
return err;
}
| null | null | 204,036
|
333285247274795199491324595400087928983
| 50
|
atlantic: Fix OOB read and write in hw_atl_utils_fw_rpc_wait
This bug report shows up when running our research tools. The
reports is SOOB read, but it seems SOOB write is also possible
a few lines below.
In details, fw.len and sw.len are inputs coming from io. A len
over the size of self->rpc triggers SOOB. The patch fixes the
bugs by adding sanity checks.
The bugs are triggerable with compromised/malfunctioning devices.
They are potentially exploitable given they first leak up to
0xffff bytes and able to overwrite the region later.
The patch is tested with QEMU emulater.
This is NOT tested with a real device.
Attached is the log we found by fuzzing.
BUG: KASAN: slab-out-of-bounds in
hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]
Read of size 4 at addr ffff888016260b08 by task modprobe/213
CPU: 0 PID: 213 Comm: modprobe Not tainted 5.6.0 #1
Call Trace:
dump_stack+0x76/0xa0
print_address_description.constprop.0+0x16/0x200
? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]
? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]
__kasan_report.cold+0x37/0x7c
? aq_hw_read_reg_bit+0x60/0x70 [atlantic]
? hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]
kasan_report+0xe/0x20
hw_atl_utils_fw_upload_dwords+0x393/0x3c0 [atlantic]
hw_atl_utils_fw_rpc_call+0x95/0x130 [atlantic]
hw_atl_utils_fw_rpc_wait+0x176/0x210 [atlantic]
hw_atl_utils_mpi_create+0x229/0x2e0 [atlantic]
? hw_atl_utils_fw_rpc_wait+0x210/0x210 [atlantic]
? hw_atl_utils_initfw+0x9f/0x1c8 [atlantic]
hw_atl_utils_initfw+0x12a/0x1c8 [atlantic]
aq_nic_ndev_register+0x88/0x650 [atlantic]
? aq_nic_ndev_init+0x235/0x3c0 [atlantic]
aq_pci_probe+0x731/0x9b0 [atlantic]
? aq_pci_func_init+0xc0/0xc0 [atlantic]
local_pci_probe+0xd3/0x160
pci_device_probe+0x23f/0x3e0
Reported-by: Brendan Dolan-Gavitt <[email protected]>
Signed-off-by: Zekun Shen <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
|
other
|
vim
|
28d032cc688ccfda18c5bbcab8b50aba6e18cde5
| 1
|
do_window(
int nchar,
long Prenum,
int xchar) // extra char from ":wincmd gx" or NUL
{
long Prenum1;
win_T *wp;
#if defined(FEAT_SEARCHPATH) || defined(FEAT_FIND_ID)
char_u *ptr;
linenr_T lnum = -1;
#endif
#ifdef FEAT_FIND_ID
int type = FIND_DEFINE;
int len;
#endif
char_u cbuf[40];
if (ERROR_IF_ANY_POPUP_WINDOW)
return;
#ifdef FEAT_CMDWIN
# define CHECK_CMDWIN \
do { \
if (cmdwin_type != 0) \
{ \
emsg(_(e_invalid_in_cmdline_window)); \
return; \
} \
} while (0)
#else
# define CHECK_CMDWIN do { /**/ } while (0)
#endif
Prenum1 = Prenum == 0 ? 1 : Prenum;
switch (nchar)
{
// split current window in two parts, horizontally
case 'S':
case Ctrl_S:
case 's':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
#ifdef FEAT_QUICKFIX
// When splitting the quickfix window open a new buffer in it,
// don't replicate the quickfix buffer.
if (bt_quickfix(curbuf))
goto newwindow;
#endif
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
(void)win_split((int)Prenum, 0);
break;
// split current window in two parts, vertically
case Ctrl_V:
case 'v':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
#ifdef FEAT_QUICKFIX
// When splitting the quickfix window open a new buffer in it,
// don't replicate the quickfix buffer.
if (bt_quickfix(curbuf))
goto newwindow;
#endif
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
(void)win_split((int)Prenum, WSP_VERT);
break;
// split current window and edit alternate file
case Ctrl_HAT:
case '^':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
if (buflist_findnr(Prenum == 0
? curwin->w_alt_fnum : Prenum) == NULL)
{
if (Prenum == 0)
emsg(_(e_no_alternate_file));
else
semsg(_(e_buffer_nr_not_found), Prenum);
break;
}
if (!curbuf_locked() && win_split(0, 0) == OK)
(void)buflist_getfile(
Prenum == 0 ? curwin->w_alt_fnum : Prenum,
(linenr_T)0, GETF_ALT, FALSE);
break;
// open new window
case Ctrl_N:
case 'n':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
#ifdef FEAT_QUICKFIX
newwindow:
#endif
if (Prenum)
// window height
vim_snprintf((char *)cbuf, sizeof(cbuf) - 5, "%ld", Prenum);
else
cbuf[0] = NUL;
#if defined(FEAT_QUICKFIX)
if (nchar == 'v' || nchar == Ctrl_V)
STRCAT(cbuf, "v");
#endif
STRCAT(cbuf, "new");
do_cmdline_cmd(cbuf);
break;
// quit current window
case Ctrl_Q:
case 'q':
reset_VIsual_and_resel(); // stop Visual mode
cmd_with_count("quit", cbuf, sizeof(cbuf), Prenum);
do_cmdline_cmd(cbuf);
break;
// close current window
case Ctrl_C:
case 'c':
reset_VIsual_and_resel(); // stop Visual mode
cmd_with_count("close", cbuf, sizeof(cbuf), Prenum);
do_cmdline_cmd(cbuf);
break;
#if defined(FEAT_QUICKFIX)
// close preview window
case Ctrl_Z:
case 'z':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
do_cmdline_cmd((char_u *)"pclose");
break;
// cursor to preview window
case 'P':
FOR_ALL_WINDOWS(wp)
if (wp->w_p_pvw)
break;
if (wp == NULL)
emsg(_(e_there_is_no_preview_window));
else
win_goto(wp);
break;
#endif
// close all but current window
case Ctrl_O:
case 'o':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
cmd_with_count("only", cbuf, sizeof(cbuf), Prenum);
do_cmdline_cmd(cbuf);
break;
// cursor to next window with wrap around
case Ctrl_W:
case 'w':
// cursor to previous window with wrap around
case 'W':
CHECK_CMDWIN;
if (ONE_WINDOW && Prenum != 1) // just one window
beep_flush();
else
{
if (Prenum) // go to specified window
{
for (wp = firstwin; --Prenum > 0; )
{
if (wp->w_next == NULL)
break;
else
wp = wp->w_next;
}
}
else
{
if (nchar == 'W') // go to previous window
{
wp = curwin->w_prev;
if (wp == NULL)
wp = lastwin; // wrap around
}
else // go to next window
{
wp = curwin->w_next;
if (wp == NULL)
wp = firstwin; // wrap around
}
}
win_goto(wp);
}
break;
// cursor to window below
case 'j':
case K_DOWN:
case Ctrl_J:
CHECK_CMDWIN;
win_goto_ver(FALSE, Prenum1);
break;
// cursor to window above
case 'k':
case K_UP:
case Ctrl_K:
CHECK_CMDWIN;
win_goto_ver(TRUE, Prenum1);
break;
// cursor to left window
case 'h':
case K_LEFT:
case Ctrl_H:
case K_BS:
CHECK_CMDWIN;
win_goto_hor(TRUE, Prenum1);
break;
// cursor to right window
case 'l':
case K_RIGHT:
case Ctrl_L:
CHECK_CMDWIN;
win_goto_hor(FALSE, Prenum1);
break;
// move window to new tab page
case 'T':
CHECK_CMDWIN;
if (one_window())
msg(_(m_onlyone));
else
{
tabpage_T *oldtab = curtab;
tabpage_T *newtab;
// First create a new tab with the window, then go back to
// the old tab and close the window there.
wp = curwin;
if (win_new_tabpage((int)Prenum) == OK
&& valid_tabpage(oldtab))
{
newtab = curtab;
goto_tabpage_tp(oldtab, TRUE, TRUE);
if (curwin == wp)
win_close(curwin, FALSE);
if (valid_tabpage(newtab))
goto_tabpage_tp(newtab, TRUE, TRUE);
}
}
break;
// cursor to top-left window
case 't':
case Ctrl_T:
win_goto(firstwin);
break;
// cursor to bottom-right window
case 'b':
case Ctrl_B:
win_goto(lastwin);
break;
// cursor to last accessed (previous) window
case 'p':
case Ctrl_P:
if (!win_valid(prevwin))
beep_flush();
else
win_goto(prevwin);
break;
// exchange current and next window
case 'x':
case Ctrl_X:
CHECK_CMDWIN;
win_exchange(Prenum);
break;
// rotate windows downwards
case Ctrl_R:
case 'r':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
win_rotate(FALSE, (int)Prenum1); // downwards
break;
// rotate windows upwards
case 'R':
CHECK_CMDWIN;
reset_VIsual_and_resel(); // stop Visual mode
win_rotate(TRUE, (int)Prenum1); // upwards
break;
// move window to the very top/bottom/left/right
case 'K':
case 'J':
case 'H':
case 'L':
CHECK_CMDWIN;
win_totop((int)Prenum,
((nchar == 'H' || nchar == 'L') ? WSP_VERT : 0)
| ((nchar == 'H' || nchar == 'K') ? WSP_TOP : WSP_BOT));
break;
// make all windows the same height
case '=':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_equal(NULL, FALSE, 'b');
break;
// increase current window height
case '+':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setheight(curwin->w_height + (int)Prenum1);
break;
// decrease current window height
case '-':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setheight(curwin->w_height - (int)Prenum1);
break;
// set current window height
case Ctrl__:
case '_':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setheight(Prenum ? (int)Prenum : 9999);
break;
// increase current window width
case '>':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setwidth(curwin->w_width + (int)Prenum1);
break;
// decrease current window width
case '<':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setwidth(curwin->w_width - (int)Prenum1);
break;
// set current window width
case '|':
#ifdef FEAT_GUI
need_mouse_correct = TRUE;
#endif
win_setwidth(Prenum != 0 ? (int)Prenum : 9999);
break;
// jump to tag and split window if tag exists (in preview window)
#if defined(FEAT_QUICKFIX)
case '}':
CHECK_CMDWIN;
if (Prenum)
g_do_tagpreview = Prenum;
else
g_do_tagpreview = p_pvh;
#endif
// FALLTHROUGH
case ']':
case Ctrl_RSB:
CHECK_CMDWIN;
// keep Visual mode, can select words to use as a tag
if (Prenum)
postponed_split = Prenum;
else
postponed_split = -1;
#ifdef FEAT_QUICKFIX
if (nchar != '}')
g_do_tagpreview = 0;
#endif
// Execute the command right here, required when "wincmd ]"
// was used in a function.
do_nv_ident(Ctrl_RSB, NUL);
break;
#ifdef FEAT_SEARCHPATH
// edit file name under cursor in a new window
case 'f':
case 'F':
case Ctrl_F:
wingotofile:
CHECK_CMDWIN;
ptr = grab_file_name(Prenum1, &lnum);
if (ptr != NULL)
{
tabpage_T *oldtab = curtab;
win_T *oldwin = curwin;
# ifdef FEAT_GUI
need_mouse_correct = TRUE;
# endif
setpcmark();
if (win_split(0, 0) == OK)
{
RESET_BINDING(curwin);
if (do_ecmd(0, ptr, NULL, NULL, ECMD_LASTL,
ECMD_HIDE, NULL) == FAIL)
{
// Failed to open the file, close the window
// opened for it.
win_close(curwin, FALSE);
goto_tabpage_win(oldtab, oldwin);
}
else if (nchar == 'F' && lnum >= 0)
{
curwin->w_cursor.lnum = lnum;
check_cursor_lnum();
beginline(BL_SOL | BL_FIX);
}
}
vim_free(ptr);
}
break;
#endif
#ifdef FEAT_FIND_ID
// Go to the first occurrence of the identifier under cursor along path in a
// new window -- webb
case 'i': // Go to any match
case Ctrl_I:
type = FIND_ANY;
// FALLTHROUGH
case 'd': // Go to definition, using 'define'
case Ctrl_D:
CHECK_CMDWIN;
if ((len = find_ident_under_cursor(&ptr, FIND_IDENT)) == 0)
break;
find_pattern_in_path(ptr, 0, len, TRUE,
Prenum == 0 ? TRUE : FALSE, type,
Prenum1, ACTION_SPLIT, (linenr_T)1, (linenr_T)MAXLNUM);
curwin->w_set_curswant = TRUE;
break;
#endif
// Quickfix window only: view the result under the cursor in a new split.
#if defined(FEAT_QUICKFIX)
case K_KENTER:
case CAR:
if (bt_quickfix(curbuf))
qf_view_result(TRUE);
break;
#endif
// CTRL-W g extended commands
case 'g':
case Ctrl_G:
CHECK_CMDWIN;
#ifdef USE_ON_FLY_SCROLL
dont_scroll = TRUE; // disallow scrolling here
#endif
++no_mapping;
++allow_keys; // no mapping for xchar, but allow key codes
if (xchar == NUL)
xchar = plain_vgetc();
LANGMAP_ADJUST(xchar, TRUE);
--no_mapping;
--allow_keys;
#ifdef FEAT_CMDL_INFO
(void)add_to_showcmd(xchar);
#endif
switch (xchar)
{
#if defined(FEAT_QUICKFIX)
case '}':
xchar = Ctrl_RSB;
if (Prenum)
g_do_tagpreview = Prenum;
else
g_do_tagpreview = p_pvh;
#endif
// FALLTHROUGH
case ']':
case Ctrl_RSB:
// keep Visual mode, can select words to use as a tag
if (Prenum)
postponed_split = Prenum;
else
postponed_split = -1;
// Execute the command right here, required when
// "wincmd g}" was used in a function.
do_nv_ident('g', xchar);
break;
#ifdef FEAT_SEARCHPATH
case 'f': // CTRL-W gf: "gf" in a new tab page
case 'F': // CTRL-W gF: "gF" in a new tab page
cmdmod.cmod_tab = tabpage_index(curtab) + 1;
nchar = xchar;
goto wingotofile;
#endif
case 't': // CTRL-W gt: go to next tab page
goto_tabpage((int)Prenum);
break;
case 'T': // CTRL-W gT: go to previous tab page
goto_tabpage(-(int)Prenum1);
break;
case TAB: // CTRL-W g<Tab>: go to last used tab page
if (goto_tabpage_lastused() == FAIL)
beep_flush();
break;
default:
beep_flush();
break;
}
break;
default: beep_flush();
break;
}
}
| null | null | 204,069
|
40601062791344847116382130508151483298
| 537
|
patch 8.2.4979: accessing freed memory when line is flushed
Problem: Accessing freed memory when line is flushed.
Solution: Make a copy of the pattern to search for.
|
other
|
shapelib
|
c75b9281a5b9452d92e1682bdfe6019a13ed819f
| 1
|
static char ** split(const char *arg, const char *delim) {
char *copy = dupstr(arg);
char **result = NULL;
int i = 0;
for (char *cptr = strtok(copy, delim); cptr; cptr = strtok(NULL, delim)) {
char **tmp = realloc (result, sizeof *result * (i + 1));
if (!tmp && result) {
while (i > 0) {
free(result[--i]);
}
free(result);
free(copy);
return NULL;
}
result = tmp;
result[i++] = dupstr(cptr);
}
free(copy);
if (i) {
char **tmp = realloc(result, sizeof *result * (i + 1));
if (!tmp) {
while (i > 0) {
free(result[--i]);
}
free(result);
free(copy);
return NULL;
}
result = tmp;
result[i++] = NULL;
}
return result;
}
| null | null | 204,073
|
182337637342849165093115926589945004498
| 37
|
Remove double free() in contrib/shpsrt, issue #39
This fixes issue #39
|
other
|
radare2
|
0927ed3ae99444e7b47b84e43118deb10fe37529
| 1
|
R_API RBinJavaAttrInfo *r_bin_java_constant_value_attr_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (bin, buffer, sz, buf_offset);
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_CONST_VALUE_ATTR;
attr->info.constant_value_attr.constantvalue_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->size = offset;
}
// IFDBG r_bin_java_print_constant_value_attr_summary(attr);
return attr;
}
| null | null | 204,101
|
286090092326334811667741061466311011765
| 12
|
Fix oobread crash in java parser ##crash
* Reported by @bet4it via @huntrdev
* BountyID: 229a2e0d-9e5c-402f-9a24-57fa2eb1aaa7
* Reproducer: poc4java
|
other
|
openldap
|
3539fc33212b528c56b716584f2c2994af7c30b0
| 1
|
issuerAndThisUpdateCheck(
struct berval *in,
struct berval *is,
struct berval *tu,
void *ctx )
{
int numdquotes = 0;
struct berval x = *in;
struct berval ni = BER_BVNULL;
/* Parse GSER format */
enum {
HAVE_NONE = 0x0,
HAVE_ISSUER = 0x1,
HAVE_THISUPDATE = 0x2,
HAVE_ALL = ( HAVE_ISSUER | HAVE_THISUPDATE )
} have = HAVE_NONE;
if ( in->bv_len < STRLENOF( "{issuer \"\",thisUpdate \"YYMMDDhhmmssZ\"}" ) ) return LDAP_INVALID_SYNTAX;
if ( in->bv_val[0] != '{' || in->bv_val[in->bv_len-1] != '}' ) {
return LDAP_INVALID_SYNTAX;
}
x.bv_val++;
x.bv_len -= STRLENOF("{}");
do {
/* eat leading spaces */
for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {
/* empty */;
}
/* should be at issuer or thisUpdate */
if ( strncasecmp( x.bv_val, "issuer", STRLENOF("issuer") ) == 0 ) {
if ( have & HAVE_ISSUER ) return LDAP_INVALID_SYNTAX;
/* parse issuer */
x.bv_val += STRLENOF("issuer");
x.bv_len -= STRLENOF("issuer");
if ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;
x.bv_val++;
x.bv_len--;
/* eat leading spaces */
for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {
/* empty */;
}
/* For backward compatibility, this part is optional */
if ( strncasecmp( x.bv_val, "rdnSequence:", STRLENOF("rdnSequence:") ) != 0 ) {
return LDAP_INVALID_SYNTAX;
}
x.bv_val += STRLENOF("rdnSequence:");
x.bv_len -= STRLENOF("rdnSequence:");
if ( x.bv_val[0] != '"' ) return LDAP_INVALID_SYNTAX;
x.bv_val++;
x.bv_len--;
is->bv_val = x.bv_val;
is->bv_len = 0;
for ( ; is->bv_len < x.bv_len; ) {
if ( is->bv_val[is->bv_len] != '"' ) {
is->bv_len++;
continue;
}
if ( is->bv_val[is->bv_len+1] == '"' ) {
/* double dquote */
numdquotes++;
is->bv_len += 2;
continue;
}
break;
}
x.bv_val += is->bv_len + 1;
x.bv_len -= is->bv_len + 1;
have |= HAVE_ISSUER;
} else if ( strncasecmp( x.bv_val, "thisUpdate", STRLENOF("thisUpdate") ) == 0 )
{
if ( have & HAVE_THISUPDATE ) return LDAP_INVALID_SYNTAX;
/* parse thisUpdate */
x.bv_val += STRLENOF("thisUpdate");
x.bv_len -= STRLENOF("thisUpdate");
if ( x.bv_val[0] != ' ' ) return LDAP_INVALID_SYNTAX;
x.bv_val++;
x.bv_len--;
/* eat leading spaces */
for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {
/* empty */;
}
if ( !x.bv_len || x.bv_val[0] != '"' ) return LDAP_INVALID_SYNTAX;
x.bv_val++;
x.bv_len--;
tu->bv_val = x.bv_val;
tu->bv_len = 0;
for ( ; tu->bv_len < x.bv_len; tu->bv_len++ ) {
if ( tu->bv_val[tu->bv_len] == '"' ) {
break;
}
}
x.bv_val += tu->bv_len + 1;
x.bv_len -= tu->bv_len + 1;
have |= HAVE_THISUPDATE;
} else {
return LDAP_INVALID_SYNTAX;
}
/* eat leading spaces */
for ( ; (x.bv_val[0] == ' ') && x.bv_len; x.bv_val++, x.bv_len-- ) {
/* empty */;
}
if ( have == HAVE_ALL ) {
break;
}
if ( x.bv_val[0] != ',' ) {
return LDAP_INVALID_SYNTAX;
}
x.bv_val++;
x.bv_len--;
} while ( 1 );
/* should have no characters left... */
if ( x.bv_len ) return LDAP_INVALID_SYNTAX;
if ( numdquotes == 0 ) {
ber_dupbv_x( &ni, is, ctx );
} else {
ber_len_t src, dst;
ni.bv_len = is->bv_len - numdquotes;
ni.bv_val = slap_sl_malloc( ni.bv_len + 1, ctx );
for ( src = 0, dst = 0; src < is->bv_len; src++, dst++ ) {
if ( is->bv_val[src] == '"' ) {
src++;
}
ni.bv_val[dst] = is->bv_val[src];
}
ni.bv_val[dst] = '\0';
}
*is = ni;
return 0;
}
| null | null | 204,115
|
296580747977289517542159030414767300564
| 161
|
ITS#9454 fix issuerAndThisUpdateCheck
|
other
|
poppler
|
b224e2f5739fe61de9fa69955d016725b2a4b78d
| 1
|
bool SplashOutputDev::tilingPatternFill(GfxState *state, Gfx *gfxA, Catalog *catalog, Object *str,
const double *ptm, int paintType, int /*tilingType*/, Dict *resDict,
const double *mat, const double *bbox,
int x0, int y0, int x1, int y1,
double xStep, double yStep)
{
PDFRectangle box;
Gfx *gfx;
Splash *formerSplash = splash;
SplashBitmap *formerBitmap = bitmap;
double width, height;
int surface_width, surface_height, result_width, result_height, i;
int repeatX, repeatY;
SplashCoord matc[6];
Matrix m1;
const double *ctm;
double savedCTM[6];
double kx, ky, sx, sy;
bool retValue = false;
width = bbox[2] - bbox[0];
height = bbox[3] - bbox[1];
if (xStep != width || yStep != height)
return false;
// calculate offsets
ctm = state->getCTM();
for (i = 0; i < 6; ++i) {
savedCTM[i] = ctm[i];
}
state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
state->concatCTM(1, 0, 0, 1, bbox[0], bbox[1]);
ctm = state->getCTM();
for (i = 0; i < 6; ++i) {
if (!std::isfinite(ctm[i])) {
state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);
return false;
}
}
matc[4] = x0 * xStep * ctm[0] + y0 * yStep * ctm[2] + ctm[4];
matc[5] = x0 * xStep * ctm[1] + y0 * yStep * ctm[3] + ctm[5];
if (splashAbs(ctm[1]) > splashAbs(ctm[0])) {
kx = -ctm[1];
ky = ctm[2] - (ctm[0] * ctm[3]) / ctm[1];
} else {
kx = ctm[0];
ky = ctm[3] - (ctm[1] * ctm[2]) / ctm[0];
}
result_width = (int) ceil(fabs(kx * width * (x1 - x0)));
result_height = (int) ceil(fabs(ky * height * (y1 - y0)));
kx = state->getHDPI() / 72.0;
ky = state->getVDPI() / 72.0;
m1.m[0] = (ptm[0] == 0) ? fabs(ptm[2]) * kx : fabs(ptm[0]) * kx;
m1.m[1] = 0;
m1.m[2] = 0;
m1.m[3] = (ptm[3] == 0) ? fabs(ptm[1]) * ky : fabs(ptm[3]) * ky;
m1.m[4] = 0;
m1.m[5] = 0;
m1.transform(width, height, &kx, &ky);
surface_width = (int) ceil (fabs(kx));
surface_height = (int) ceil (fabs(ky));
sx = (double) result_width / (surface_width * (x1 - x0));
sy = (double) result_height / (surface_height * (y1 - y0));
m1.m[0] *= sx;
m1.m[3] *= sy;
m1.transform(width, height, &kx, &ky);
if(fabs(kx) < 1 && fabs(ky) < 1) {
kx = std::min<double>(kx, ky);
ky = 2 / kx;
m1.m[0] *= ky;
m1.m[3] *= ky;
m1.transform(width, height, &kx, &ky);
surface_width = (int) ceil (fabs(kx));
surface_height = (int) ceil (fabs(ky));
repeatX = x1 - x0;
repeatY = y1 - y0;
} else {
if ((unsigned long) surface_width * surface_height > 0x800000L) {
state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);
return false;
}
while(fabs(kx) > 16384 || fabs(ky) > 16384) {
// limit pattern bitmap size
m1.m[0] /= 2;
m1.m[3] /= 2;
m1.transform(width, height, &kx, &ky);
}
surface_width = (int) ceil (fabs(kx));
surface_height = (int) ceil (fabs(ky));
// adjust repeat values to completely fill region
repeatX = result_width / surface_width;
repeatY = result_height / surface_height;
if (surface_width * repeatX < result_width)
repeatX++;
if (surface_height * repeatY < result_height)
repeatY++;
if (x1 - x0 > repeatX)
repeatX = x1 - x0;
if (y1 - y0 > repeatY)
repeatY = y1 - y0;
}
// restore CTM and calculate rotate and scale with rounded matrix
state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);
state->concatCTM(mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
state->concatCTM(width * repeatX, 0, 0, height * repeatY, bbox[0], bbox[1]);
ctm = state->getCTM();
matc[0] = ctm[0];
matc[1] = ctm[1];
matc[2] = ctm[2];
matc[3] = ctm[3];
if (surface_width == 0 || surface_height == 0 || repeatX * repeatY <= 4) {
state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);
return false;
}
m1.transform(bbox[0], bbox[1], &kx, &ky);
m1.m[4] = -kx;
m1.m[5] = -ky;
bitmap = new SplashBitmap(surface_width, surface_height, 1,
(paintType == 1) ? colorMode : splashModeMono8, true);
if (bitmap->getDataPtr() == nullptr) {
SplashBitmap *tBitmap = bitmap;
bitmap = formerBitmap;
delete tBitmap;
state->setCTM(savedCTM[0], savedCTM[1], savedCTM[2], savedCTM[3], savedCTM[4], savedCTM[5]);
return false;
}
splash = new Splash(bitmap, true);
if (paintType == 2) {
SplashColor clearColor;
#ifdef SPLASH_CMYK
clearColor[0] = (colorMode == splashModeCMYK8 || colorMode == splashModeDeviceN8) ? 0x00 : 0xFF;
#else
clearColor[0] = 0xFF;
#endif
splash->clear(clearColor, 0);
} else {
splash->clear(paperColor, 0);
}
splash->setThinLineMode(formerSplash->getThinLineMode());
splash->setMinLineWidth(s_minLineWidth);
box.x1 = bbox[0]; box.y1 = bbox[1];
box.x2 = bbox[2]; box.y2 = bbox[3];
gfx = new Gfx(doc, this, resDict, &box, nullptr, nullptr, nullptr, gfxA);
// set pattern transformation matrix
gfx->getState()->setCTM(m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);
updateCTM(gfx->getState(), m1.m[0], m1.m[1], m1.m[2], m1.m[3], m1.m[4], m1.m[5]);
gfx->display(str);
delete splash;
splash = formerSplash;
TilingSplashOutBitmap imgData;
imgData.bitmap = bitmap;
imgData.paintType = paintType;
imgData.pattern = splash->getFillPattern();
imgData.colorMode = colorMode;
imgData.y = 0;
imgData.repeatX = repeatX;
imgData.repeatY = repeatY;
SplashBitmap *tBitmap = bitmap;
bitmap = formerBitmap;
result_width = tBitmap->getWidth() * imgData.repeatX;
result_height = tBitmap->getHeight() * imgData.repeatY;
if (splashAbs(matc[1]) > splashAbs(matc[0])) {
kx = -matc[1];
ky = matc[2] - (matc[0] * matc[3]) / matc[1];
} else {
kx = matc[0];
ky = matc[3] - (matc[1] * matc[2]) / matc[0];
}
kx = result_width / (fabs(kx) + 1);
ky = result_height / (fabs(ky) + 1);
state->concatCTM(kx, 0, 0, ky, 0, 0);
ctm = state->getCTM();
matc[0] = ctm[0];
matc[1] = ctm[1];
matc[2] = ctm[2];
matc[3] = ctm[3];
bool minorAxisZero = matc[1] == 0 && matc[2] == 0;
if (matc[0] > 0 && minorAxisZero && matc[3] > 0) {
// draw the tiles
for (int y = 0; y < imgData.repeatY; ++y) {
for (int x = 0; x < imgData.repeatX; ++x) {
x0 = splashFloor(matc[4]) + x * tBitmap->getWidth();
y0 = splashFloor(matc[5]) + y * tBitmap->getHeight();
splash->blitImage(tBitmap, true, x0, y0);
}
}
retValue = true;
} else {
retValue = splash->drawImage(&tilingBitmapSrc, nullptr, &imgData, colorMode, true, result_width, result_height, matc, false, true) == splashOk;
}
delete tBitmap;
delete gfx;
return retValue;
}
| null | null | 204,137
|
133098112260413624043013297002027022744
| 201
|
SplashOutputDev::tilingPatternFill: Fix crash on broken file
Issue #802
|
other
|
qemu
|
e392255766071c8cac480da3a9ae4f94e56d7cbc
| 1
|
static void write_response(ESPState *s)
{
uint32_t n;
trace_esp_write_response(s->status);
fifo8_reset(&s->fifo);
esp_fifo_push(s, s->status);
esp_fifo_push(s, 0);
if (s->dma) {
if (s->dma_memory_write) {
s->dma_memory_write(s->dma_opaque,
(uint8_t *)fifo8_pop_buf(&s->fifo, 2, &n), 2);
s->rregs[ESP_RSTAT] = STAT_TC | STAT_ST;
s->rregs[ESP_RINTR] |= INTR_BS | INTR_FC;
s->rregs[ESP_RSEQ] = SEQ_CD;
} else {
s->pdma_cb = write_response_pdma_cb;
esp_raise_drq(s);
return;
}
} else {
s->ti_size = 2;
s->rregs[ESP_RFLAGS] = 2;
}
esp_raise_irq(s);
}
| null | null | 204,138
|
49024678101170277298678525746898400757
| 28
|
esp: rework write_response() to avoid using the FIFO for DMA transactions
The code for write_response() has always used the FIFO to store the data for
the status/message in phases, even for DMA transactions. Switch to using a
separate buffer that can be used directly for DMA transactions and restrict
the FIFO use to the non-DMA case.
Signed-off-by: Mark Cave-Ayland <[email protected]>
Tested-by: Alexander Bulekov <[email protected]>
Reviewed-by: Philippe Mathieu-Daudé <[email protected]>
Message-Id: <[email protected]>
|
other
|
pjproject
|
8b621f192cae14456ee0b0ade52ce6c6f258af1e
| 1
|
static void parse_rtcp_bye(pjmedia_rtcp_session *sess,
const void *pkt,
pj_size_t size)
{
pj_str_t reason = {"-", 1};
/* Check and get BYE reason */
if (size > 8) {
reason.slen = PJ_MIN(sizeof(sess->stat.peer_sdes_buf_),
*((pj_uint8_t*)pkt+8));
pj_memcpy(sess->stat.peer_sdes_buf_, ((pj_uint8_t*)pkt+9),
reason.slen);
reason.ptr = sess->stat.peer_sdes_buf_;
}
/* Just print RTCP BYE log */
PJ_LOG(5, (sess->name, "Received RTCP BYE, reason: %.*s",
reason.slen, reason.ptr));
}
| null | null | 204,195
|
116381620827139969116334270652816885980
| 19
|
Merge pull request from GHSA-3qx3-cg72-wrh9
|
other
|
vim
|
fe6fb267e6ee5c5da2f41889e4e0e0ac5bf4b89d
| 1
|
eval7(
char_u **arg,
typval_T *rettv,
evalarg_T *evalarg,
int want_string) // after "." operator
{
int evaluate = evalarg != NULL
&& (evalarg->eval_flags & EVAL_EVALUATE);
int len;
char_u *s;
char_u *name_start = NULL;
char_u *start_leader, *end_leader;
int ret = OK;
char_u *alias;
/*
* Initialise variable so that clear_tv() can't mistake this for a
* string and free a string that isn't there.
*/
rettv->v_type = VAR_UNKNOWN;
/*
* Skip '!', '-' and '+' characters. They are handled later.
*/
start_leader = *arg;
if (eval_leader(arg, in_vim9script()) == FAIL)
return FAIL;
end_leader = *arg;
if (**arg == '.' && (!isdigit(*(*arg + 1))
#ifdef FEAT_FLOAT
|| in_old_script(2)
#endif
))
{
semsg(_(e_invalid_expression_str), *arg);
++*arg;
return FAIL;
}
switch (**arg)
{
/*
* Number constant.
*/
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.': ret = eval_number(arg, rettv, evaluate, want_string);
// Apply prefixed "-" and "+" now. Matters especially when
// "->" follows.
if (ret == OK && evaluate && end_leader > start_leader
&& rettv->v_type != VAR_BLOB)
ret = eval7_leader(rettv, TRUE, start_leader, &end_leader);
break;
/*
* String constant: "string".
*/
case '"': ret = eval_string(arg, rettv, evaluate);
break;
/*
* Literal string constant: 'str''ing'.
*/
case '\'': ret = eval_lit_string(arg, rettv, evaluate);
break;
/*
* List: [expr, expr]
*/
case '[': ret = eval_list(arg, rettv, evalarg, TRUE);
break;
/*
* Dictionary: #{key: val, key: val}
*/
case '#': if (in_vim9script())
{
ret = vim9_bad_comment(*arg) ? FAIL : NOTDONE;
}
else if ((*arg)[1] == '{')
{
++*arg;
ret = eval_dict(arg, rettv, evalarg, TRUE);
}
else
ret = NOTDONE;
break;
/*
* Lambda: {arg, arg -> expr}
* Dictionary: {'key': val, 'key': val}
*/
case '{': if (in_vim9script())
ret = NOTDONE;
else
ret = get_lambda_tv(arg, rettv, in_vim9script(), evalarg);
if (ret == NOTDONE)
ret = eval_dict(arg, rettv, evalarg, FALSE);
break;
/*
* Option value: &name
*/
case '&': ret = eval_option(arg, rettv, evaluate);
break;
/*
* Environment variable: $VAR.
*/
case '$': ret = eval_env_var(arg, rettv, evaluate);
break;
/*
* Register contents: @r.
*/
case '@': ++*arg;
if (evaluate)
{
if (in_vim9script() && IS_WHITE_OR_NUL(**arg))
semsg(_(e_syntax_error_at_str), *arg);
else if (in_vim9script() && !valid_yank_reg(**arg, FALSE))
emsg_invreg(**arg);
else
{
rettv->v_type = VAR_STRING;
rettv->vval.v_string = get_reg_contents(**arg,
GREG_EXPR_SRC);
}
}
if (**arg != NUL)
++*arg;
break;
/*
* nested expression: (expression).
* or lambda: (arg) => expr
*/
case '(': ret = NOTDONE;
if (in_vim9script())
{
ret = get_lambda_tv(arg, rettv, TRUE, evalarg);
if (ret == OK && evaluate)
{
ufunc_T *ufunc = rettv->vval.v_partial->pt_func;
// Compile it here to get the return type. The return
// type is optional, when it's missing use t_unknown.
// This is recognized in compile_return().
if (ufunc->uf_ret_type->tt_type == VAR_VOID)
ufunc->uf_ret_type = &t_unknown;
if (compile_def_function(ufunc,
FALSE, COMPILE_TYPE(ufunc), NULL) == FAIL)
{
clear_tv(rettv);
ret = FAIL;
}
}
}
if (ret == NOTDONE)
{
*arg = skipwhite_and_linebreak(*arg + 1, evalarg);
ret = eval1(arg, rettv, evalarg); // recursive!
*arg = skipwhite_and_linebreak(*arg, evalarg);
if (**arg == ')')
++*arg;
else if (ret == OK)
{
emsg(_(e_missing_closing_paren));
clear_tv(rettv);
ret = FAIL;
}
}
break;
default: ret = NOTDONE;
break;
}
if (ret == NOTDONE)
{
/*
* Must be a variable or function name.
* Can also be a curly-braces kind of name: {expr}.
*/
s = *arg;
len = get_name_len(arg, &alias, evaluate, TRUE);
if (alias != NULL)
s = alias;
if (len <= 0)
ret = FAIL;
else
{
int flags = evalarg == NULL ? 0 : evalarg->eval_flags;
if (evaluate && in_vim9script() && len == 1 && *s == '_')
{
emsg(_(e_cannot_use_underscore_here));
ret = FAIL;
}
else if ((in_vim9script() ? **arg : *skipwhite(*arg)) == '(')
{
// "name(..." recursive!
*arg = skipwhite(*arg);
ret = eval_func(arg, evalarg, s, len, rettv, flags, NULL);
}
else if (flags & EVAL_CONSTANT)
ret = FAIL;
else if (evaluate)
{
// get the value of "true", "false" or a variable
if (len == 4 && in_vim9script() && STRNCMP(s, "true", 4) == 0)
{
rettv->v_type = VAR_BOOL;
rettv->vval.v_number = VVAL_TRUE;
ret = OK;
}
else if (len == 5 && in_vim9script()
&& STRNCMP(s, "false", 5) == 0)
{
rettv->v_type = VAR_BOOL;
rettv->vval.v_number = VVAL_FALSE;
ret = OK;
}
else if (len == 4 && in_vim9script()
&& STRNCMP(s, "null", 4) == 0)
{
rettv->v_type = VAR_SPECIAL;
rettv->vval.v_number = VVAL_NULL;
ret = OK;
}
else
{
name_start = s;
ret = eval_variable(s, len, 0, rettv, NULL,
EVAL_VAR_VERBOSE + EVAL_VAR_IMPORT);
}
}
else
{
// skip the name
check_vars(s, len);
ret = OK;
}
}
vim_free(alias);
}
// Handle following '[', '(' and '.' for expr[expr], expr.name,
// expr(expr), expr->name(expr)
if (ret == OK)
ret = handle_subscript(arg, name_start, rettv, evalarg, TRUE);
/*
* Apply logical NOT and unary '-', from right to left, ignore '+'.
*/
if (ret == OK && evaluate && end_leader > start_leader)
ret = eval7_leader(rettv, FALSE, start_leader, &end_leader);
return ret;
}
| null | null | 204,243
|
232244475812066827928465028874364534335
| 271
|
patch 8.2.4206: condition with many "(" causes a crash
Problem: Condition with many "(" causes a crash.
Solution: Limit recursion to 1000.
|
other
|
firejail
|
1884ea22a90d225950d81c804f1771b42ae55f54
| 1
|
static void build_dirs(char *src, char *dst, size_t src_prefix_len, size_t dst_prefix_len) {
char *p = src + src_prefix_len + 1;
char *q = dst + dst_prefix_len + 1;
char *r = dst + dst_prefix_len;
struct stat s;
bool last = false;
*r = '\0';
for (; !last; p++, q++) {
if (*p == '\0') {
last = true;
}
if (*p == '\0' || (*p == '/' && *(p - 1) != '/')) {
// We found a new component of our src path.
// Null-terminate it temporarily here so that we can work
// with it.
*p = '\0';
if (stat(src, &s) == 0 && S_ISDIR(s.st_mode)) {
// Null-terminate the dst path and undo its previous
// termination.
*q = '\0';
*r = '/';
r = q;
mkdir_attr(dst, s.st_mode, 0, 0);
}
if (!last) {
// If we're not at the final terminating null, restore
// the slash so that we can continue our traversal.
*p = '/';
}
}
}
}
| null | null | 204,278
|
202858840369022100976840325755647707434
| 32
|
CVE-2022-31214: fixing the fix, one more time
the previous commit "CVE-2022-31214: fixing the fix"
made private-etc=fonts,fonts and similar commands
fail with an error
fix that regression by tolerating already existing
directories
|
other
|
node-sqlite3
|
593c9d498be2510d286349134537e3bf89401c4a
| 1
|
Statement::BindParameter(const Napi::Value source, T pos) {
if (source.IsString()) {
std::string val = source.As<Napi::String>().Utf8Value();
return new Values::Text(pos, val.length(), val.c_str());
}
else if (OtherInstanceOf(source.As<Object>(), "RegExp")) {
std::string val = source.ToString().Utf8Value();
return new Values::Text(pos, val.length(), val.c_str());
}
else if (source.IsNumber()) {
if (OtherIsInt(source.As<Napi::Number>())) {
return new Values::Integer(pos, source.As<Napi::Number>().Int32Value());
} else {
return new Values::Float(pos, source.As<Napi::Number>().DoubleValue());
}
}
else if (source.IsBoolean()) {
return new Values::Integer(pos, source.As<Napi::Boolean>().Value() ? 1 : 0);
}
else if (source.IsNull()) {
return new Values::Null(pos);
}
else if (source.IsBuffer()) {
Napi::Buffer<char> buffer = source.As<Napi::Buffer<char>>();
return new Values::Blob(pos, buffer.Length(), buffer.Data());
}
else if (OtherInstanceOf(source.As<Object>(), "Date")) {
return new Values::Float(pos, source.ToNumber().DoubleValue());
}
else if (source.IsObject()) {
std::string val = source.ToString().Utf8Value();
return new Values::Text(pos, val.length(), val.c_str());
}
else {
return NULL;
}
}
| null | null | 204,322
|
144963976907476877879205773154137404855
| 37
|
bug: fix segfault of invalid toString() object (#1450)
* bug: verify toString() returns valid data
* test: faulty toString test
|
other
|
squirrel
|
23a0620658714b996d20da3d4dd1a0dcf9b0bd98
| 1
|
bool SQClass::NewSlot(SQSharedState *ss,const SQObjectPtr &key,const SQObjectPtr &val,bool bstatic)
{
SQObjectPtr temp;
bool belongs_to_static_table = sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE || bstatic;
if(_locked && !belongs_to_static_table)
return false; //the class already has an instance so cannot be modified
if(_members->Get(key,temp) && _isfield(temp)) //overrides the default value
{
_defaultvalues[_member_idx(temp)].val = val;
return true;
}
if(belongs_to_static_table) {
SQInteger mmidx;
if((sq_type(val) == OT_CLOSURE || sq_type(val) == OT_NATIVECLOSURE) &&
(mmidx = ss->GetMetaMethodIdxByName(key)) != -1) {
_metamethods[mmidx] = val;
}
else {
SQObjectPtr theval = val;
if(_base && sq_type(val) == OT_CLOSURE) {
theval = _closure(val)->Clone();
_closure(theval)->_base = _base;
__ObjAddRef(_base); //ref for the closure
}
if(sq_type(temp) == OT_NULL) {
bool isconstructor;
SQVM::IsEqual(ss->_constructoridx, key, isconstructor);
if(isconstructor) {
_constructoridx = (SQInteger)_methods.size();
}
SQClassMember m;
m.val = theval;
_members->NewSlot(key,SQObjectPtr(_make_method_idx(_methods.size())));
_methods.push_back(m);
}
else {
_methods[_member_idx(temp)].val = theval;
}
}
return true;
}
SQClassMember m;
m.val = val;
_members->NewSlot(key,SQObjectPtr(_make_field_idx(_defaultvalues.size())));
_defaultvalues.push_back(m);
return true;
}
| null | null | 204,351
|
199509684587999841325880819130767395401
| 47
|
check max member count in class
|
other
|
binaryen
|
1beec37f483505db0c5152be9118b28e45b77316
| 1
|
void WasmBinaryBuilder::readImports() {
BYN_TRACE("== readImports\n");
size_t num = getU32LEB();
BYN_TRACE("num: " << num << std::endl);
Builder builder(wasm);
size_t tableCounter = 0;
size_t memoryCounter = 0;
size_t functionCounter = 0;
size_t globalCounter = 0;
size_t tagCounter = 0;
for (size_t i = 0; i < num; i++) {
BYN_TRACE("read one\n");
auto module = getInlineString();
auto base = getInlineString();
auto kind = (ExternalKind)getU32LEB();
// We set a unique prefix for the name based on the kind. This ensures no
// collisions between them, which can't occur here (due to the index i) but
// could occur later due to the names section.
switch (kind) {
case ExternalKind::Function: {
Name name(std::string("fimport$") + std::to_string(functionCounter++));
auto index = getU32LEB();
functionTypes.push_back(getTypeByIndex(index));
auto curr = builder.makeFunction(name, getTypeByIndex(index), {});
curr->module = module;
curr->base = base;
functionImports.push_back(curr.get());
wasm.addFunction(std::move(curr));
break;
}
case ExternalKind::Table: {
Name name(std::string("timport$") + std::to_string(tableCounter++));
auto table = builder.makeTable(name);
table->module = module;
table->base = base;
table->type = getType();
bool is_shared;
Type indexType;
getResizableLimits(table->initial,
table->max,
is_shared,
indexType,
Table::kUnlimitedSize);
if (is_shared) {
throwError("Tables may not be shared");
}
if (indexType == Type::i64) {
throwError("Tables may not be 64-bit");
}
tableImports.push_back(table.get());
wasm.addTable(std::move(table));
break;
}
case ExternalKind::Memory: {
Name name(std::string("mimport$") + std::to_string(memoryCounter++));
wasm.memory.module = module;
wasm.memory.base = base;
wasm.memory.name = name;
wasm.memory.exists = true;
getResizableLimits(wasm.memory.initial,
wasm.memory.max,
wasm.memory.shared,
wasm.memory.indexType,
Memory::kUnlimitedSize);
break;
}
case ExternalKind::Global: {
Name name(std::string("gimport$") + std::to_string(globalCounter++));
auto type = getConcreteType();
auto mutable_ = getU32LEB();
auto curr =
builder.makeGlobal(name,
type,
nullptr,
mutable_ ? Builder::Mutable : Builder::Immutable);
curr->module = module;
curr->base = base;
globalImports.push_back(curr.get());
wasm.addGlobal(std::move(curr));
break;
}
case ExternalKind::Tag: {
Name name(std::string("eimport$") + std::to_string(tagCounter++));
getInt8(); // Reserved 'attribute' field
auto index = getU32LEB();
auto curr = builder.makeTag(name, getSignatureByTypeIndex(index));
curr->module = module;
curr->base = base;
wasm.addTag(std::move(curr));
break;
}
default: {
throwError("bad import kind");
}
}
}
}
| null | null | 204,373
|
115979870756146746665097212315595844646
| 99
|
Add binary format parse check for imported function types (#4423)
Without this we hit an assertion later, which is less clear.
See #4413
|
other
|
lldpd
|
73d42680fce8598324364dbb31b9bc3b8320adf7
| 1
|
sonmp_decode(struct lldpd *cfg, char *frame, int s,
struct lldpd_hardware *hardware,
struct lldpd_chassis **newchassis, struct lldpd_port **newport)
{
const u_int8_t mcastaddr[] = SONMP_MULTICAST_ADDR;
struct lldpd_chassis *chassis;
struct lldpd_port *port;
struct lldpd_mgmt *mgmt;
int length, i;
u_int8_t *pos;
u_int8_t seg[3], rchassis;
struct in_addr address;
log_debug("sonmp", "decode SONMP PDU from %s",
hardware->h_ifname);
if ((chassis = calloc(1, sizeof(struct lldpd_chassis))) == NULL) {
log_warn("sonmp", "failed to allocate remote chassis");
return -1;
}
TAILQ_INIT(&chassis->c_mgmt);
if ((port = calloc(1, sizeof(struct lldpd_port))) == NULL) {
log_warn("sonmp", "failed to allocate remote port");
free(chassis);
return -1;
}
#ifdef ENABLE_DOT1
TAILQ_INIT(&port->p_vlans);
#endif
length = s;
pos = (u_int8_t*)frame;
if (length < SONMP_SIZE) {
log_warnx("sonmp", "too short SONMP frame received on %s", hardware->h_ifname);
goto malformed;
}
if (PEEK_CMP(mcastaddr, sizeof(mcastaddr)) != 0)
/* There is two multicast address. We just handle only one of
* them. */
goto malformed;
/* We skip to LLC PID */
PEEK_DISCARD(ETHER_ADDR_LEN); PEEK_DISCARD_UINT16;
PEEK_DISCARD(6);
if (PEEK_UINT16 != LLC_PID_SONMP_HELLO) {
log_debug("sonmp", "incorrect LLC protocol ID received for SONMP on %s",
hardware->h_ifname);
goto malformed;
}
chassis->c_id_subtype = LLDP_CHASSISID_SUBTYPE_ADDR;
if ((chassis->c_id = calloc(1, sizeof(struct in_addr) + 1)) == NULL) {
log_warn("sonmp", "unable to allocate memory for chassis id on %s",
hardware->h_ifname);
goto malformed;
}
chassis->c_id_len = sizeof(struct in_addr) + 1;
chassis->c_id[0] = 1;
PEEK_BYTES(&address, sizeof(struct in_addr));
memcpy(chassis->c_id + 1, &address, sizeof(struct in_addr));
if (asprintf(&chassis->c_name, "%s", inet_ntoa(address)) == -1) {
log_warnx("sonmp", "unable to write chassis name for %s",
hardware->h_ifname);
goto malformed;
}
PEEK_BYTES(seg, sizeof(seg));
rchassis = PEEK_UINT8;
for (i=0; sonmp_chassis_types[i].type != 0; i++) {
if (sonmp_chassis_types[i].type == rchassis)
break;
}
if (asprintf(&chassis->c_descr, "%s",
sonmp_chassis_types[i].description) == -1) {
log_warnx("sonmp", "unable to write chassis description for %s",
hardware->h_ifname);
goto malformed;
}
mgmt = lldpd_alloc_mgmt(LLDPD_AF_IPV4, &address, sizeof(struct in_addr), 0);
if (mgmt == NULL) {
if (errno == ENOMEM)
log_warn("sonmp", "unable to allocate memory for management address");
else
log_warn("sonmp", "too large management address received on %s",
hardware->h_ifname);
goto malformed;
}
TAILQ_INSERT_TAIL(&chassis->c_mgmt, mgmt, m_entries);
port->p_ttl = cfg?(cfg->g_config.c_tx_interval * cfg->g_config.c_tx_hold):
LLDPD_TTL;
port->p_ttl = (port->p_ttl + 999) / 1000;
port->p_id_subtype = LLDP_PORTID_SUBTYPE_LOCAL;
if (asprintf(&port->p_id, "%02x-%02x-%02x",
seg[0], seg[1], seg[2]) == -1) {
log_warn("sonmp", "unable to allocate memory for port id on %s",
hardware->h_ifname);
goto malformed;
}
port->p_id_len = strlen(port->p_id);
/* Port description depend on the number of segments */
if ((seg[0] == 0) && (seg[1] == 0)) {
if (asprintf(&port->p_descr, "port %d",
seg[2]) == -1) {
log_warnx("sonmp", "unable to write port description for %s",
hardware->h_ifname);
goto malformed;
}
} else if (seg[0] == 0) {
if (asprintf(&port->p_descr, "port %d/%d",
seg[1], seg[2]) == -1) {
log_warnx("sonmp", "unable to write port description for %s",
hardware->h_ifname);
goto malformed;
}
} else {
if (asprintf(&port->p_descr, "port %x:%x:%x",
seg[0], seg[1], seg[2]) == -1) {
log_warnx("sonmp", "unable to write port description for %s",
hardware->h_ifname);
goto malformed;
}
}
*newchassis = chassis;
*newport = port;
return 1;
malformed:
lldpd_chassis_cleanup(chassis, 1);
lldpd_port_cleanup(port, 1);
free(port);
return -1;
}
| null | null | 204,378
|
433540116442967903483329906084914417
| 132
|
sonmp: fix heap overflow when reading SONMP packets
By sending short SONMP packets, an attacker can make the decoder crash
by reading too much data on the heap. SONMP packets are fixed in size,
just ensure we get the enough bytes to contain a SONMP packet.
CVE-2021-43612
|
other
|
bpf
|
4b81ccebaeee885ab1aa1438133f2991e3a2b6ea
| 1
|
static void *__bpf_ringbuf_reserve(struct bpf_ringbuf *rb, u64 size)
{
unsigned long cons_pos, prod_pos, new_prod_pos, flags;
u32 len, pg_off;
struct bpf_ringbuf_hdr *hdr;
if (unlikely(size > RINGBUF_MAX_RECORD_SZ))
return NULL;
len = round_up(size + BPF_RINGBUF_HDR_SZ, 8);
cons_pos = smp_load_acquire(&rb->consumer_pos);
if (in_nmi()) {
if (!spin_trylock_irqsave(&rb->spinlock, flags))
return NULL;
} else {
spin_lock_irqsave(&rb->spinlock, flags);
}
prod_pos = rb->producer_pos;
new_prod_pos = prod_pos + len;
/* check for out of ringbuf space by ensuring producer position
* doesn't advance more than (ringbuf_size - 1) ahead
*/
if (new_prod_pos - cons_pos > rb->mask) {
spin_unlock_irqrestore(&rb->spinlock, flags);
return NULL;
}
hdr = (void *)rb->data + (prod_pos & rb->mask);
pg_off = bpf_ringbuf_rec_pg_off(rb, hdr);
hdr->len = size | BPF_RINGBUF_BUSY_BIT;
hdr->pg_off = pg_off;
/* pairs with consumer's smp_load_acquire() */
smp_store_release(&rb->producer_pos, new_prod_pos);
spin_unlock_irqrestore(&rb->spinlock, flags);
return (void *)hdr + BPF_RINGBUF_HDR_SZ;
}
| null | null | 204,412
|
131038937033707206587172217520477415099
| 42
|
bpf, ringbuf: Deny reserve of buffers larger than ringbuf
A BPF program might try to reserve a buffer larger than the ringbuf size.
If the consumer pointer is way ahead of the producer, that would be
successfully reserved, allowing the BPF program to read or write out of
the ringbuf allocated area.
Reported-by: Ryota Shiga (Flatt Security)
Fixes: 457f44363a88 ("bpf: Implement BPF ring buffer and verifier support for it")
Signed-off-by: Thadeu Lima de Souza Cascardo <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Acked-by: Andrii Nakryiko <[email protected]>
Acked-by: Alexei Starovoitov <[email protected]>
|
other
|
frr
|
6d58272b4cf96f0daa846210dd2104877900f921
| 1
|
bgp_capability_msg_parse (struct peer *peer, u_char *pnt, bgp_size_t length)
{
u_char *end;
struct capability cap;
u_char action;
struct bgp *bgp;
afi_t afi;
safi_t safi;
bgp = peer->bgp;
end = pnt + length;
while (pnt < end)
{
/* We need at least action, capability code and capability length. */
if (pnt + 3 > end)
{
zlog_info ("%s Capability length error", peer->host);
bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
return -1;
}
action = *pnt;
/* Fetch structure to the byte stream. */
memcpy (&cap, pnt + 1, sizeof (struct capability));
/* Action value check. */
if (action != CAPABILITY_ACTION_SET
&& action != CAPABILITY_ACTION_UNSET)
{
zlog_info ("%s Capability Action Value error %d",
peer->host, action);
bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
return -1;
}
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s CAPABILITY has action: %d, code: %u, length %u",
peer->host, action, cap.code, cap.length);
/* Capability length check. */
if (pnt + (cap.length + 3) > end)
{
zlog_info ("%s Capability length error", peer->host);
bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
return -1;
}
/* We know MP Capability Code. */
if (cap.code == CAPABILITY_CODE_MP)
{
afi = ntohs (cap.mpc.afi);
safi = cap.mpc.safi;
/* Ignore capability when override-capability is set. */
if (CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))
continue;
/* Address family check. */
if ((afi == AFI_IP
|| afi == AFI_IP6)
&& (safi == SAFI_UNICAST
|| safi == SAFI_MULTICAST
|| safi == BGP_SAFI_VPNV4))
{
if (BGP_DEBUG (normal, NORMAL))
zlog_debug ("%s CAPABILITY has %s MP_EXT CAP for afi/safi: %u/%u",
peer->host,
action == CAPABILITY_ACTION_SET
? "Advertising" : "Removing",
ntohs(cap.mpc.afi) , cap.mpc.safi);
/* Adjust safi code. */
if (safi == BGP_SAFI_VPNV4)
safi = SAFI_MPLS_VPN;
if (action == CAPABILITY_ACTION_SET)
{
peer->afc_recv[afi][safi] = 1;
if (peer->afc[afi][safi])
{
peer->afc_nego[afi][safi] = 1;
bgp_announce_route (peer, afi, safi);
}
}
else
{
peer->afc_recv[afi][safi] = 0;
peer->afc_nego[afi][safi] = 0;
if (peer_active_nego (peer))
bgp_clear_route (peer, afi, safi);
else
BGP_EVENT_ADD (peer, BGP_Stop);
}
}
}
else
{
zlog_warn ("%s unrecognized capability code: %d - ignored",
peer->host, cap.code);
}
pnt += cap.length + 3;
}
return 0;
}
| null | null | 204,425
|
68687368830087044406531459207369590186
| 107
|
[bgpd] cleanup, compact and consolidate capability parsing code
2007-07-26 Paul Jakma <[email protected]>
* (general) Clean up and compact capability parsing slightly.
Consolidate validation of length and logging of generic TLV, and
memcpy of capability data, thus removing such from cap specifc
code (not always present or correct).
* bgp_open.h: Add structures for the generic capability TLV header
and for the data formats of the various specific capabilities we
support. Hence remove the badly named, or else misdefined, struct
capability.
* bgp_open.c: (bgp_capability_vty_out) Use struct capability_mp_data.
Do the length checks *before* memcpy()'ing based on that length
(stored capability - should have been validated anyway on input,
but..).
(bgp_afi_safi_valid_indices) new function to validate (afi,safi)
which is about to be used as index into arrays, consolidates
several instances of same, at least one of which appeared to be
incomplete..
(bgp_capability_mp) Much condensed.
(bgp_capability_orf_entry) New, process one ORF entry
(bgp_capability_orf) Condensed. Fixed to process all ORF entries.
(bgp_capability_restart) Condensed, and fixed to use a
cap-specific type, rather than abusing capability_mp.
(struct message capcode_str) added to aid generic logging.
(size_t cap_minsizes[]) added to aid generic validation of
capability length field.
(bgp_capability_parse) Generic logging and validation of TLV
consolidated here. Code compacted as much as possible.
* bgp_packet.c: (bgp_open_receive) Capability parsers now use
streams, so no more need here to manually fudge the input stream
getp.
(bgp_capability_msg_parse) use struct capability_mp_data. Validate
lengths /before/ memcpy. Use bgp_afi_safi_valid_indices.
(bgp_capability_receive) Exported for use by test harness.
* bgp_vty.c: (bgp_show_summary) fix conversion warning
(bgp_show_peer) ditto
* bgp_debug.h: Fix storage 'extern' after type 'const'.
* lib/log.c: (mes_lookup) warning about code not being in
same-number array slot should be debug, not warning. E.g. BGP
has several discontigious number spaces, allocating from
different parts of a space is not uncommon (e.g. IANA
assigned versus vendor-assigned code points in some number
space).
|
other
|
ImageMagick
|
716496e6df0add89e9679d6da9c0afca814cfe49
| 1
|
WandPrivate void CLINoImageOperator(MagickCLI *cli_wand,
const char *option,const char *arg1n,const char *arg2n)
{
const char /* percent escaped versions of the args */
*arg1,
*arg2;
#define _image_info (cli_wand->wand.image_info)
#define _images (cli_wand->wand.images)
#define _exception (cli_wand->wand.exception)
#define _process_flags (cli_wand->process_flags)
#define _option_type ((CommandOptionFlags) cli_wand->command->flags)
#define IfNormalOp (*option=='-')
#define IfPlusOp (*option!='-')
assert(cli_wand != (MagickCLI *) NULL);
assert(cli_wand->signature == MagickWandSignature);
assert(cli_wand->wand.signature == MagickWandSignature);
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- NoImage Operator: %s \"%s\" \"%s\"", option,
arg1n != (char *) NULL ? arg1n : "",
arg2n != (char *) NULL ? arg2n : "");
arg1 = arg1n;
arg2 = arg2n;
/* Interpret Percent Escapes in Arguments - using first image */
if ( (((_process_flags & ProcessInterpretProperities) != 0 )
|| ((_option_type & AlwaysInterpretArgsFlag) != 0)
) && ((_option_type & NeverInterpretArgsFlag) == 0) ) {
/* Interpret Percent escapes in argument 1 */
if (arg1n != (char *) NULL) {
arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);
if (arg1 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg1=arg1n; /* use the given argument as is */
}
}
if (arg2n != (char *) NULL) {
arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);
if (arg2 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg2=arg2n; /* use the given argument as is */
}
}
}
#undef _process_flags
#undef _option_type
do { /* break to exit code */
/*
No-op options (ignore these)
*/
if (LocaleCompare("noop",option+1) == 0) /* zero argument */
break;
if (LocaleCompare("sans",option+1) == 0) /* one argument */
break;
if (LocaleCompare("sans0",option+1) == 0) /* zero argument */
break;
if (LocaleCompare("sans1",option+1) == 0) /* one argument */
break;
if (LocaleCompare("sans2",option+1) == 0) /* two arguments */
break;
/*
Image Reading
*/
if ( ( LocaleCompare("read",option+1) == 0 ) ||
( LocaleCompare("--",option) == 0 ) ) {
/* Do Glob filename Expansion for 'arg1' then read all images.
*
* Expansion handles '@', '~', '*', and '?' meta-characters while ignoring
* (but attaching to the filenames in the generated argument list) any
* [...] read modifiers that may be present.
*
* For example: It will expand '*.gif[20x20]' into a list such as
* 'abc.gif[20x20]', 'foobar.gif[20x20]', 'xyzzy.gif[20x20]'
*
* NOTE: In IMv6 this was done globally across all images. This
* meant you could include IM options in '@filename' lists, but you
* could not include comments. Doing it only for image read makes
* it far more secure.
*
* Note: arguments do not have percent escapes expanded for security
* reasons.
*/
int argc;
char **argv;
ssize_t i;
argc = 1;
argv = (char **) &arg1;
/* Expand 'glob' expressions in the given filename.
Expansion handles any 'coder:' prefix, or read modifiers attached
to the filename, including them in the resulting expanded list.
*/
if (ExpandFilenames(&argc,&argv) == MagickFalse)
CLIWandExceptArgBreak(ResourceLimitError,"MemoryAllocationFailed",
option,GetExceptionMessage(errno));
/* loop over expanded filename list, and read then all in */
for (i=0; i < (ssize_t) argc; i++) {
Image *
new_images;
if (_image_info->ping != MagickFalse)
new_images=PingImages(_image_info,argv[i],_exception);
else
new_images=ReadImages(_image_info,argv[i],_exception);
AppendImageToList(&_images, new_images);
argv[i]=DestroyString(argv[i]);
}
argv=(char **) RelinquishMagickMemory(argv);
break;
}
/*
Image Writing
Note: Writing a empty image list is valid in specific cases
*/
if (LocaleCompare("write",option+1) == 0) {
/* Note: arguments do not have percent escapes expanded */
char
key[MagickPathExtent];
Image
*write_images;
ImageInfo
*write_info;
/* Need images, unless a "null:" output coder is used */
if ( _images == (Image *) NULL ) {
if ( LocaleCompare(arg1,"null:") == 0 )
break;
CLIWandExceptArgBreak(OptionError,"NoImagesForWrite",option,arg1);
}
(void) FormatLocaleString(key,MagickPathExtent,"cache:%s",arg1);
(void) DeleteImageRegistry(key);
write_images=CloneImageList(_images,_exception);
write_info=CloneImageInfo(_image_info);
(void) WriteImages(write_info,write_images,arg1,_exception);
write_info=DestroyImageInfo(write_info);
write_images=DestroyImageList(write_images);
break;
}
/*
Parenthesis and Brace operations
*/
if (LocaleCompare("(",option) == 0) {
/* stack 'push' images */
Stack
*node;
size_t
size;
size=0;
node=cli_wand->image_list_stack;
for ( ; node != (Stack *) NULL; node=node->next)
size++;
if ( size >= MAX_STACK_DEPTH )
CLIWandExceptionBreak(OptionError,"ParenthesisNestedTooDeeply",option);
node=(Stack *) AcquireMagickMemory(sizeof(*node));
if (node == (Stack *) NULL)
CLIWandExceptionBreak(ResourceLimitFatalError,
"MemoryAllocationFailed",option);
node->data = (void *)cli_wand->wand.images;
node->next = cli_wand->image_list_stack;
cli_wand->image_list_stack = node;
cli_wand->wand.images = NewImageList();
/* handle respect-parenthesis */
if (IsStringTrue(GetImageOption(cli_wand->wand.image_info,
"respect-parenthesis")) != MagickFalse)
option="{"; /* fall-thru so as to push image settings too */
else
break;
/* fall thru to operation */
}
if (LocaleCompare("{",option) == 0) {
/* stack 'push' of image_info settings */
Stack
*node;
size_t
size;
size=0;
node=cli_wand->image_info_stack;
for ( ; node != (Stack *) NULL; node=node->next)
size++;
if ( size >= MAX_STACK_DEPTH )
CLIWandExceptionBreak(OptionError,"CurlyBracesNestedTooDeeply",option);
node=(Stack *) AcquireMagickMemory(sizeof(*node));
if (node == (Stack *) NULL)
CLIWandExceptionBreak(ResourceLimitFatalError,
"MemoryAllocationFailed",option);
node->data = (void *)cli_wand->wand.image_info;
node->next = cli_wand->image_info_stack;
cli_wand->image_info_stack = node;
cli_wand->wand.image_info = CloneImageInfo(cli_wand->wand.image_info);
if (cli_wand->wand.image_info == (ImageInfo *) NULL) {
CLIWandException(ResourceLimitFatalError,"MemoryAllocationFailed",
option);
cli_wand->wand.image_info = (ImageInfo *)node->data;
node = (Stack *)RelinquishMagickMemory(node);
break;
}
break;
}
if (LocaleCompare(")",option) == 0) {
/* pop images from stack */
Stack
*node;
node = (Stack *)cli_wand->image_list_stack;
if ( node == (Stack *) NULL)
CLIWandExceptionBreak(OptionError,"UnbalancedParenthesis",option);
cli_wand->image_list_stack = node->next;
AppendImageToList((Image **)&node->data,cli_wand->wand.images);
cli_wand->wand.images= (Image *)node->data;
node = (Stack *)RelinquishMagickMemory(node);
/* handle respect-parenthesis - of the previous 'pushed' settings */
node = cli_wand->image_info_stack;
if ( node != (Stack *) NULL)
{
if (IsStringTrue(GetImageOption(
cli_wand->wand.image_info,"respect-parenthesis")) != MagickFalse)
option="}"; /* fall-thru so as to pop image settings too */
else
break;
}
else
break;
/* fall thru to next if */
}
if (LocaleCompare("}",option) == 0) {
/* pop image_info settings from stack */
Stack
*node;
node = (Stack *)cli_wand->image_info_stack;
if ( node == (Stack *) NULL)
CLIWandExceptionBreak(OptionError,"UnbalancedCurlyBraces",option);
cli_wand->image_info_stack = node->next;
(void) DestroyImageInfo(cli_wand->wand.image_info);
cli_wand->wand.image_info = (ImageInfo *)node->data;
node = (Stack *)RelinquishMagickMemory(node);
GetDrawInfo(cli_wand->wand.image_info, cli_wand->draw_info);
cli_wand->quantize_info=DestroyQuantizeInfo(cli_wand->quantize_info);
cli_wand->quantize_info=AcquireQuantizeInfo(cli_wand->wand.image_info);
break;
}
if (LocaleCompare("print",option+1) == 0)
{
(void) FormatLocaleFile(stdout,"%s",arg1);
break;
}
if (LocaleCompare("set",option+1) == 0)
{
/* Settings are applied to each image in memory in turn (if any).
While a option: only need to be applied once globally.
NOTE: rguments have not been automatically percent expaneded
*/
/* escape the 'key' once only, using first image. */
arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);
if (arg1 == (char *) NULL)
CLIWandExceptionBreak(OptionWarning,"InterpretPropertyFailure",
option);
if (LocaleNCompare(arg1,"registry:",9) == 0)
{
if (IfPlusOp)
{
(void) DeleteImageRegistry(arg1+9);
arg1=DestroyString((char *)arg1);
break;
}
arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);
if (arg2 == (char *) NULL) {
arg1=DestroyString((char *)arg1);
CLIWandExceptionBreak(OptionWarning,"InterpretPropertyFailure",
option);
}
(void) SetImageRegistry(StringRegistryType,arg1+9,arg2,_exception);
arg1=DestroyString((char *)arg1);
arg2=DestroyString((char *)arg2);
break;
}
if (LocaleNCompare(arg1,"option:",7) == 0)
{
/* delete equivelent artifact from all images (if any) */
if (_images != (Image *) NULL)
{
MagickResetIterator(&cli_wand->wand);
while (MagickNextImage(&cli_wand->wand) != MagickFalse)
(void) DeleteImageArtifact(_images,arg1+7);
MagickResetIterator(&cli_wand->wand);
}
/* now set/delete the global option as needed */
/* FUTURE: make escapes in a global 'option:' delayed */
arg2=(char *) NULL;
if (IfNormalOp)
{
arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);
if (arg2 == (char *) NULL)
CLIWandExceptionBreak(OptionWarning,
"InterpretPropertyFailure",option);
}
(void) SetImageOption(_image_info,arg1+7,arg2);
arg1=DestroyString((char *)arg1);
arg2=DestroyString((char *)arg2);
break;
}
/* Set Artifacts/Properties/Attributes all images (required) */
if ( _images == (Image *) NULL )
CLIWandExceptArgBreak(OptionWarning,"NoImageForProperty",option,arg1);
MagickResetIterator(&cli_wand->wand);
while (MagickNextImage(&cli_wand->wand) != MagickFalse)
{
arg2=(char *) NULL;
if (IfNormalOp)
{
arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);
if (arg2 == (char *) NULL)
CLIWandExceptionBreak(OptionWarning,
"InterpretPropertyFailure",option);
}
if (LocaleNCompare(arg1,"artifact:",9) == 0)
(void) SetImageArtifact(_images,arg1+9,arg2);
else if (LocaleNCompare(arg1,"property:",9) == 0)
(void) SetImageProperty(_images,arg1+9,arg2,_exception);
else
(void) SetImageProperty(_images,arg1,arg2,_exception);
arg2=DestroyString((char *)arg2);
}
MagickResetIterator(&cli_wand->wand);
arg1=DestroyString((char *)arg1);
break;
}
if (LocaleCompare("clone",option+1) == 0) {
Image
*new_images;
if (*option == '+')
arg1=AcquireString("-1");
if (IsSceneGeometry(arg1,MagickFalse) == MagickFalse)
CLIWandExceptionBreak(OptionError,"InvalidArgument",option);
if ( cli_wand->image_list_stack == (Stack *) NULL)
CLIWandExceptionBreak(OptionError,"UnableToCloneImage",option);
new_images = (Image *)cli_wand->image_list_stack->data;
if (new_images == (Image *) NULL)
CLIWandExceptionBreak(OptionError,"UnableToCloneImage",option);
new_images=CloneImages(new_images,arg1,_exception);
if (new_images == (Image *) NULL)
CLIWandExceptionBreak(OptionError,"NoSuchImage",option);
AppendImageToList(&_images,new_images);
break;
}
/*
Informational Operations.
Note that these do not require either a cli-wand or images!
Though currently a cli-wand much be provided regardless.
*/
if (LocaleCompare("version",option+1) == 0)
{
ListMagickVersion(stdout);
break;
}
if (LocaleCompare("list",option+1) == 0) {
/*
FUTURE: This 'switch' should really be part of MagickCore
*/
ssize_t
list;
list=ParseCommandOption(MagickListOptions,MagickFalse,arg1);
if ( list < 0 ) {
CLIWandExceptionArg(OptionError,"UnrecognizedListType",option,arg1);
break;
}
switch (list)
{
case MagickCoderOptions:
{
(void) ListCoderInfo((FILE *) NULL,_exception);
break;
}
case MagickColorOptions:
{
(void) ListColorInfo((FILE *) NULL,_exception);
break;
}
case MagickConfigureOptions:
{
(void) ListConfigureInfo((FILE *) NULL,_exception);
break;
}
case MagickDelegateOptions:
{
(void) ListDelegateInfo((FILE *) NULL,_exception);
break;
}
case MagickFontOptions:
{
(void) ListTypeInfo((FILE *) NULL,_exception);
break;
}
case MagickFormatOptions:
(void) ListMagickInfo((FILE *) NULL,_exception);
break;
case MagickLocaleOptions:
(void) ListLocaleInfo((FILE *) NULL,_exception);
break;
case MagickLogOptions:
(void) ListLogInfo((FILE *) NULL,_exception);
break;
case MagickMagicOptions:
(void) ListMagicInfo((FILE *) NULL,_exception);
break;
case MagickMimeOptions:
(void) ListMimeInfo((FILE *) NULL,_exception);
break;
case MagickModuleOptions:
(void) ListModuleInfo((FILE *) NULL,_exception);
break;
case MagickPolicyOptions:
(void) ListPolicyInfo((FILE *) NULL,_exception);
break;
case MagickResourceOptions:
(void) ListMagickResourceInfo((FILE *) NULL,_exception);
break;
case MagickThresholdOptions:
(void) ListThresholdMaps((FILE *) NULL,_exception);
break;
default:
(void) ListCommandOptions((FILE *) NULL,(CommandOption) list,
_exception);
break;
}
break;
}
CLIWandException(OptionError,"UnrecognizedOption",option);
DisableMSCWarning(4127)
} while (0); /* break to exit code. */
RestoreMSCWarning
/* clean up percent escape interpreted strings */
if (arg1 != arg1n )
arg1=DestroyString((char *)arg1);
if (arg2 != arg2n )
arg2=DestroyString((char *)arg2);
#undef _image_info
#undef _images
#undef _exception
#undef IfNormalOp
#undef IfPlusOp
}
| null | null | 204,438
|
14318001169487772637067239663580687746
| 475
|
do not attempt to write a null image list (thanks to Vinay Rohila)
|
other
|
linux
|
47abea041f897d64dbd5777f0cf7745148f85d75
| 1
|
static int __io_sync_cancel(struct io_uring_task *tctx,
struct io_cancel_data *cd, int fd)
{
struct io_ring_ctx *ctx = cd->ctx;
/* fixed must be grabbed every time since we drop the uring_lock */
if ((cd->flags & IORING_ASYNC_CANCEL_FD) &&
(cd->flags & IORING_ASYNC_CANCEL_FD_FIXED)) {
unsigned long file_ptr;
if (unlikely(fd > ctx->nr_user_files))
return -EBADF;
fd = array_index_nospec(fd, ctx->nr_user_files);
file_ptr = io_fixed_file_slot(&ctx->file_table, fd)->file_ptr;
cd->file = (struct file *) (file_ptr & FFS_MASK);
if (!cd->file)
return -EBADF;
}
return __io_async_cancel(cd, tctx, 0);
}
| null | null | 204,495
|
95819289232334994807100789689909298832
| 21
|
io_uring: fix off-by-one in sync cancelation file check
The passed in index should be validated against the number of registered
files we have, it needs to be smaller than the index value to avoid going
one beyond the end.
Fixes: 78a861b94959 ("io_uring: add sync cancelation API through io_uring_register()")
Reported-by: Luo Likang <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
|
other
|
admesh
|
e84d8353f1347e1f26f0a95770d92ba14e6ede38
| 1
|
stl_remove_degenerate(stl_file *stl, int facet) {
int edge1;
int edge2;
int edge3;
int neighbor1;
int neighbor2;
int neighbor3;
int vnot1;
int vnot2;
int vnot3;
if (stl->error) return;
if( !memcmp(&stl->facet_start[facet].vertex[0],
&stl->facet_start[facet].vertex[1], sizeof(stl_vertex))
&& !memcmp(&stl->facet_start[facet].vertex[1],
&stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {
/* all 3 vertices are equal. Just remove the facet. I don't think*/
/* this is really possible, but just in case... */
printf("removing a facet in stl_remove_degenerate\n");
stl_remove_facet(stl, facet);
return;
}
if(!memcmp(&stl->facet_start[facet].vertex[0],
&stl->facet_start[facet].vertex[1], sizeof(stl_vertex))) {
edge1 = 1;
edge2 = 2;
edge3 = 0;
} else if(!memcmp(&stl->facet_start[facet].vertex[1],
&stl->facet_start[facet].vertex[2], sizeof(stl_vertex))) {
edge1 = 0;
edge2 = 2;
edge3 = 1;
} else if(!memcmp(&stl->facet_start[facet].vertex[2],
&stl->facet_start[facet].vertex[0], sizeof(stl_vertex))) {
edge1 = 0;
edge2 = 1;
edge3 = 2;
} else {
/* No degenerate. Function shouldn't have been called. */
return;
}
neighbor1 = stl->neighbors_start[facet].neighbor[edge1];
neighbor2 = stl->neighbors_start[facet].neighbor[edge2];
if(neighbor1 == -1) {
stl_update_connects_remove_1(stl, neighbor2);
}
if(neighbor2 == -1) {
stl_update_connects_remove_1(stl, neighbor1);
}
neighbor3 = stl->neighbors_start[facet].neighbor[edge3];
vnot1 = stl->neighbors_start[facet].which_vertex_not[edge1];
vnot2 = stl->neighbors_start[facet].which_vertex_not[edge2];
vnot3 = stl->neighbors_start[facet].which_vertex_not[edge3];
if(neighbor1 != -1){
stl->neighbors_start[neighbor1].neighbor[(vnot1 + 1) % 3] = neighbor2;
stl->neighbors_start[neighbor1].which_vertex_not[(vnot1 + 1) % 3] = vnot2;
}
if(neighbor2 != -1){
stl->neighbors_start[neighbor2].neighbor[(vnot2 + 1) % 3] = neighbor1;
stl->neighbors_start[neighbor2].which_vertex_not[(vnot2 + 1) % 3] = vnot1;
}
stl_remove_facet(stl, facet);
if(neighbor3 != -1) {
stl_update_connects_remove_1(stl, neighbor3);
stl->neighbors_start[neighbor3].neighbor[(vnot3 + 1) % 3] = -1;
}
}
| null | null | 204,534
|
141682010662553061590677935382021358019
| 76
|
Fix heap buffer overflow in stl_update_connects_remove_1
- Add argument value check to the stl_update_connects_remove_1
- Add neighbor value check in stl_remove_degenerate
Fixes https://github.com/admesh/admesh/issues/28
Merges https://github.com/admesh/admesh/pull/55
|
other
|
admesh
|
e84d8353f1347e1f26f0a95770d92ba14e6ede38
| 1
|
stl_update_connects_remove_1(stl_file *stl, int facet_num) {
int j;
if (stl->error) return;
/* Update list of connected edges */
j = ((stl->neighbors_start[facet_num].neighbor[0] == -1) +
(stl->neighbors_start[facet_num].neighbor[1] == -1) +
(stl->neighbors_start[facet_num].neighbor[2] == -1));
if(j == 0) { /* Facet has 3 neighbors */
stl->stats.connected_facets_3_edge -= 1;
} else if(j == 1) { /* Facet has 2 neighbors */
stl->stats.connected_facets_2_edge -= 1;
} else if(j == 2) { /* Facet has 1 neighbor */
stl->stats.connected_facets_1_edge -= 1;
}
}
| null | null | 204,535
|
269052706287886390203661040158083039292
| 16
|
Fix heap buffer overflow in stl_update_connects_remove_1
- Add argument value check to the stl_update_connects_remove_1
- Add neighbor value check in stl_remove_degenerate
Fixes https://github.com/admesh/admesh/issues/28
Merges https://github.com/admesh/admesh/pull/55
|
other
|
linux
|
c08eadca1bdfa099e20a32f8fa4b52b2f672236d
| 1
|
static int em28xx_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id)
{
struct usb_device *udev;
struct em28xx *dev = NULL;
int retval;
bool has_vendor_audio = false, has_video = false, has_dvb = false;
int i, nr, try_bulk;
const int ifnum = intf->altsetting[0].desc.bInterfaceNumber;
char *speed;
udev = usb_get_dev(interface_to_usbdev(intf));
/* Check to see next free device and mark as used */
do {
nr = find_first_zero_bit(em28xx_devused, EM28XX_MAXBOARDS);
if (nr >= EM28XX_MAXBOARDS) {
/* No free device slots */
dev_err(&intf->dev,
"Driver supports up to %i em28xx boards.\n",
EM28XX_MAXBOARDS);
retval = -ENOMEM;
goto err_no_slot;
}
} while (test_and_set_bit(nr, em28xx_devused));
/* Don't register audio interfaces */
if (intf->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
dev_info(&intf->dev,
"audio device (%04x:%04x): interface %i, class %i\n",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct),
ifnum,
intf->altsetting[0].desc.bInterfaceClass);
retval = -ENODEV;
goto err;
}
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev) {
retval = -ENOMEM;
goto err;
}
/* compute alternate max packet sizes */
dev->alt_max_pkt_size_isoc = kcalloc(intf->num_altsetting,
sizeof(dev->alt_max_pkt_size_isoc[0]),
GFP_KERNEL);
if (!dev->alt_max_pkt_size_isoc) {
kfree(dev);
retval = -ENOMEM;
goto err;
}
/* Get endpoints */
for (i = 0; i < intf->num_altsetting; i++) {
int ep;
for (ep = 0;
ep < intf->altsetting[i].desc.bNumEndpoints;
ep++)
em28xx_check_usb_descriptor(dev, udev, intf,
i, ep,
&has_vendor_audio,
&has_video,
&has_dvb);
}
if (!(has_vendor_audio || has_video || has_dvb)) {
retval = -ENODEV;
goto err_free;
}
switch (udev->speed) {
case USB_SPEED_LOW:
speed = "1.5";
break;
case USB_SPEED_UNKNOWN:
case USB_SPEED_FULL:
speed = "12";
break;
case USB_SPEED_HIGH:
speed = "480";
break;
default:
speed = "unknown";
}
dev_info(&intf->dev,
"New device %s %s @ %s Mbps (%04x:%04x, interface %d, class %d)\n",
udev->manufacturer ? udev->manufacturer : "",
udev->product ? udev->product : "",
speed,
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct),
ifnum,
intf->altsetting->desc.bInterfaceNumber);
/*
* Make sure we have 480 Mbps of bandwidth, otherwise things like
* video stream wouldn't likely work, since 12 Mbps is generally
* not enough even for most Digital TV streams.
*/
if (udev->speed != USB_SPEED_HIGH && disable_usb_speed_check == 0) {
dev_err(&intf->dev, "Device initialization failed.\n");
dev_err(&intf->dev,
"Device must be connected to a high-speed USB 2.0 port.\n");
retval = -ENODEV;
goto err_free;
}
dev->devno = nr;
dev->model = id->driver_info;
dev->alt = -1;
dev->is_audio_only = has_vendor_audio && !(has_video || has_dvb);
dev->has_video = has_video;
dev->ifnum = ifnum;
dev->ts = PRIMARY_TS;
snprintf(dev->name, 28, "em28xx");
dev->dev_next = NULL;
if (has_vendor_audio) {
dev_info(&intf->dev,
"Audio interface %i found (Vendor Class)\n", ifnum);
dev->usb_audio_type = EM28XX_USB_AUDIO_VENDOR;
}
/* Checks if audio is provided by a USB Audio Class intf */
for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
struct usb_interface *uif = udev->config->interface[i];
if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
if (has_vendor_audio)
dev_err(&intf->dev,
"em28xx: device seems to have vendor AND usb audio class interfaces !\n"
"\t\tThe vendor interface will be ignored. Please contact the developers <[email protected]>\n");
dev->usb_audio_type = EM28XX_USB_AUDIO_CLASS;
break;
}
}
if (has_video)
dev_info(&intf->dev, "Video interface %i found:%s%s\n",
ifnum,
dev->analog_ep_bulk ? " bulk" : "",
dev->analog_ep_isoc ? " isoc" : "");
if (has_dvb)
dev_info(&intf->dev, "DVB interface %i found:%s%s\n",
ifnum,
dev->dvb_ep_bulk ? " bulk" : "",
dev->dvb_ep_isoc ? " isoc" : "");
dev->num_alt = intf->num_altsetting;
if ((unsigned int)card[nr] < em28xx_bcount)
dev->model = card[nr];
/* save our data pointer in this intf device */
usb_set_intfdata(intf, dev);
/* allocate device struct and check if the device is a webcam */
mutex_init(&dev->lock);
retval = em28xx_init_dev(dev, udev, intf, nr);
if (retval)
goto err_free;
if (usb_xfer_mode < 0) {
if (dev->is_webcam)
try_bulk = 1;
else
try_bulk = 0;
} else {
try_bulk = usb_xfer_mode > 0;
}
/* Disable V4L2 if the device doesn't have a decoder or image sensor */
if (has_video &&
dev->board.decoder == EM28XX_NODECODER &&
dev->em28xx_sensor == EM28XX_NOSENSOR) {
dev_err(&intf->dev,
"Currently, V4L2 is not supported on this model\n");
has_video = false;
dev->has_video = false;
}
if (dev->board.has_dual_ts &&
(dev->tuner_type != TUNER_ABSENT || INPUT(0)->type)) {
/*
* The logic with sets alternate is not ready for dual-tuners
* which analog modes.
*/
dev_err(&intf->dev,
"We currently don't support analog TV or stream capture on dual tuners.\n");
has_video = false;
}
/* Select USB transfer types to use */
if (has_video) {
if (!dev->analog_ep_isoc || (try_bulk && dev->analog_ep_bulk))
dev->analog_xfer_bulk = 1;
dev_info(&intf->dev, "analog set to %s mode.\n",
dev->analog_xfer_bulk ? "bulk" : "isoc");
}
if (has_dvb) {
if (!dev->dvb_ep_isoc || (try_bulk && dev->dvb_ep_bulk))
dev->dvb_xfer_bulk = 1;
dev_info(&intf->dev, "dvb set to %s mode.\n",
dev->dvb_xfer_bulk ? "bulk" : "isoc");
}
if (dev->board.has_dual_ts && em28xx_duplicate_dev(dev) == 0) {
dev->dev_next->ts = SECONDARY_TS;
dev->dev_next->alt = -1;
dev->dev_next->is_audio_only = has_vendor_audio &&
!(has_video || has_dvb);
dev->dev_next->has_video = false;
dev->dev_next->ifnum = ifnum;
dev->dev_next->model = id->driver_info;
mutex_init(&dev->dev_next->lock);
retval = em28xx_init_dev(dev->dev_next, udev, intf,
dev->dev_next->devno);
if (retval)
goto err_free;
dev->dev_next->board.ir_codes = NULL; /* No IR for 2nd tuner */
dev->dev_next->board.has_ir_i2c = 0; /* No IR for 2nd tuner */
if (usb_xfer_mode < 0) {
if (dev->dev_next->is_webcam)
try_bulk = 1;
else
try_bulk = 0;
} else {
try_bulk = usb_xfer_mode > 0;
}
/* Select USB transfer types to use */
if (has_dvb) {
if (!dev->dvb_ep_isoc_ts2 ||
(try_bulk && dev->dvb_ep_bulk_ts2))
dev->dev_next->dvb_xfer_bulk = 1;
dev_info(&dev->intf->dev, "dvb ts2 set to %s mode.\n",
dev->dev_next->dvb_xfer_bulk ? "bulk" : "isoc");
}
dev->dev_next->dvb_ep_isoc = dev->dvb_ep_isoc_ts2;
dev->dev_next->dvb_ep_bulk = dev->dvb_ep_bulk_ts2;
dev->dev_next->dvb_max_pkt_size_isoc = dev->dvb_max_pkt_size_isoc_ts2;
dev->dev_next->dvb_alt_isoc = dev->dvb_alt_isoc;
/* Configure hardware to support TS2*/
if (dev->dvb_xfer_bulk) {
/* The ep4 and ep5 are configured for BULK */
em28xx_write_reg(dev, 0x0b, 0x96);
mdelay(100);
em28xx_write_reg(dev, 0x0b, 0x80);
mdelay(100);
} else {
/* The ep4 and ep5 are configured for ISO */
em28xx_write_reg(dev, 0x0b, 0x96);
mdelay(100);
em28xx_write_reg(dev, 0x0b, 0x82);
mdelay(100);
}
kref_init(&dev->dev_next->ref);
}
kref_init(&dev->ref);
request_modules(dev);
/*
* Do it at the end, to reduce dynamic configuration changes during
* the device init. Yet, as request_modules() can be async, the
* topology will likely change after the load of the em28xx subdrivers.
*/
#ifdef CONFIG_MEDIA_CONTROLLER
retval = media_device_register(dev->media_dev);
#endif
return 0;
err_free:
kfree(dev->alt_max_pkt_size_isoc);
kfree(dev);
err:
clear_bit(nr, em28xx_devused);
err_no_slot:
usb_put_dev(udev);
return retval;
}
| null | null | 204,544
|
316770757437160907495396783476650960761
| 297
|
media: em28xx: initialize refcount before kref_get
The commit 47677e51e2a4("[media] em28xx: Only deallocate struct
em28xx after finishing all extensions") adds kref_get to many init
functions (e.g., em28xx_audio_init). However, kref_init is called too
late in em28xx_usb_probe, since em28xx_init_dev before will invoke
those init functions and call kref_get function. Then refcount bug
occurs in my local syzkaller instance.
Fix it by moving kref_init before em28xx_init_dev. This issue occurs
not only in dev but also dev->dev_next.
Fixes: 47677e51e2a4 ("[media] em28xx: Only deallocate struct em28xx after finishing all extensions")
Reported-by: syzkaller <[email protected]>
Signed-off-by: Dongliang Mu <[email protected]>
Signed-off-by: Hans Verkuil <[email protected]>
|
other
|
php-src
|
259057b2a484747a6c73ce54c4fa0f5acbd56179
| 1
|
SPL_METHOD(SplDoublyLinkedList, unserialize)
{
spl_dllist_object *intern = (spl_dllist_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zval *flags, *elem;
char *buf;
int buf_len;
const unsigned char *p, *s;
php_unserialize_data_t var_hash;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) {
return;
}
if (buf_len == 0) {
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Serialized string cannot be empty");
return;
}
s = p = (const unsigned char*)buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
/* flags */
ALLOC_INIT_ZVAL(flags);
if (!php_var_unserialize(&flags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(flags) != IS_LONG) {
zval_ptr_dtor(&flags);
goto error;
}
var_push_dtor(&var_hash, &flags);
intern->flags = Z_LVAL_P(flags);
zval_ptr_dtor(&flags);
/* elements */
while(*p == ':') {
++p;
ALLOC_INIT_ZVAL(elem);
if (!php_var_unserialize(&elem, &p, s + buf_len, &var_hash TSRMLS_CC)) {
zval_ptr_dtor(&elem);
goto error;
}
spl_ptr_llist_push(intern->llist, elem TSRMLS_CC);
}
if (*p != '\0') {
goto error;
}
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
return;
error:
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len);
return;
} /* }}} */
| null | null | 204,545
|
175570379904229409444093217226892836618
| 56
|
Fix bug #70366 - use-after-free vulnerability in unserialize() with SplDoublyLinkedList
|
other
|
samba
|
34383981a0c40860f71a4451ff8fd752e1b67666
| 1
|
static int ldb_wildcard_compare(struct ldb_context *ldb,
const struct ldb_parse_tree *tree,
const struct ldb_val value, bool *matched)
{
const struct ldb_schema_attribute *a;
struct ldb_val val;
struct ldb_val cnk;
struct ldb_val *chunk;
uint8_t *save_p = NULL;
unsigned int c = 0;
a = ldb_schema_attribute_by_name(ldb, tree->u.substring.attr);
if (!a) {
return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
}
if (tree->u.substring.chunks == NULL) {
*matched = false;
return LDB_SUCCESS;
}
if (a->syntax->canonicalise_fn(ldb, ldb, &value, &val) != 0) {
return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
}
save_p = val.data;
cnk.data = NULL;
if ( ! tree->u.substring.start_with_wildcard ) {
chunk = tree->u.substring.chunks[c];
if (a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;
/* This deals with wildcard prefix searches on binary attributes (eg objectGUID) */
if (cnk.length > val.length) {
goto mismatch;
}
/*
* Empty strings are returned as length 0. Ensure
* we can cope with this.
*/
if (cnk.length == 0) {
goto mismatch;
}
if (memcmp((char *)val.data, (char *)cnk.data, cnk.length) != 0) goto mismatch;
val.length -= cnk.length;
val.data += cnk.length;
c++;
talloc_free(cnk.data);
cnk.data = NULL;
}
while (tree->u.substring.chunks[c]) {
uint8_t *p;
chunk = tree->u.substring.chunks[c];
if(a->syntax->canonicalise_fn(ldb, ldb, chunk, &cnk) != 0) goto mismatch;
/*
* Empty strings are returned as length 0. Ensure
* we can cope with this.
*/
if (cnk.length == 0) {
goto mismatch;
}
/*
* Values might be binary blobs. Don't use string
* search, but memory search instead.
*/
p = memmem((const void *)val.data,val.length,
(const void *)cnk.data, cnk.length);
if (p == NULL) goto mismatch;
/*
* At this point we know cnk.length <= val.length as
* otherwise there could be no match
*/
if ( (! tree->u.substring.chunks[c + 1]) && (! tree->u.substring.end_with_wildcard) ) {
uint8_t *g;
uint8_t *end = val.data + val.length;
do { /* greedy */
/*
* haystack is a valid pointer in val
* because the memmem() can only
* succeed if the needle (cnk.length)
* is <= haystacklen
*
* p will be a pointer at least
* cnk.length from the end of haystack
*/
uint8_t *haystack
= p + cnk.length;
size_t haystacklen
= end - (haystack);
g = memmem(haystack,
haystacklen,
(const uint8_t *)cnk.data,
cnk.length);
if (g) {
p = g;
}
} while(g);
}
val.length = val.length - (p - (uint8_t *)(val.data)) - cnk.length;
val.data = (uint8_t *)(p + cnk.length);
c++;
talloc_free(cnk.data);
cnk.data = NULL;
}
/* last chunk may not have reached end of string */
if ( (! tree->u.substring.end_with_wildcard) && (*(val.data) != 0) ) goto mismatch;
talloc_free(save_p);
*matched = true;
return LDB_SUCCESS;
mismatch:
*matched = false;
talloc_free(save_p);
talloc_free(cnk.data);
return LDB_SUCCESS;
}
| null | null | 204,711
|
264293216438188529998910258908439139604
| 126
|
CVE-2019-3824 ldb: wildcard_match check tree operation
Check the operation type of the passed parse tree, and return
LDB_INAPPROPRIATE_MATCH if the operation is not LDB_OP_SUBSTRING.
A query of "attribute=*" gets parsed as LDB_OP_PRESENT, checking the
operation and failing ldb_wildcard_match should help prevent confusion
writing tests.
BUG: https://bugzilla.samba.org/show_bug.cgi?id=13773
Signed-off-by: Gary Lockyer <[email protected]>
Reviewed-by: Andrew Bartlett <[email protected]>
|
other
|
vim
|
adce965162dd89bf29ee0e5baf53652e7515762c
| 1
|
do_tag(
char_u *tag, // tag (pattern) to jump to
int type,
int count,
int forceit, // :ta with !
int verbose) // print "tag not found" message
{
taggy_T *tagstack = curwin->w_tagstack;
int tagstackidx = curwin->w_tagstackidx;
int tagstacklen = curwin->w_tagstacklen;
int cur_match = 0;
int cur_fnum = curbuf->b_fnum;
int oldtagstackidx = tagstackidx;
int prevtagstackidx = tagstackidx;
int prev_num_matches;
int new_tag = FALSE;
int i;
int ic;
int no_regexp = FALSE;
int error_cur_match = 0;
int save_pos = FALSE;
fmark_T saved_fmark;
#ifdef FEAT_CSCOPE
int jumped_to_tag = FALSE;
#endif
int new_num_matches;
char_u **new_matches;
int use_tagstack;
int skip_msg = FALSE;
char_u *buf_ffname = curbuf->b_ffname; // name to use for
// priority computation
int use_tfu = 1;
// remember the matches for the last used tag
static int num_matches = 0;
static int max_num_matches = 0; // limit used for match search
static char_u **matches = NULL;
static int flags;
#ifdef FEAT_EVAL
if (tfu_in_use)
{
emsg(_(e_cannot_modify_tag_stack_within_tagfunc));
return FALSE;
}
#endif
#ifdef EXITFREE
if (type == DT_FREE)
{
// remove the list of matches
FreeWild(num_matches, matches);
# ifdef FEAT_CSCOPE
cs_free_tags();
# endif
num_matches = 0;
return FALSE;
}
#endif
if (type == DT_HELP)
{
type = DT_TAG;
no_regexp = TRUE;
use_tfu = 0;
}
prev_num_matches = num_matches;
free_string_option(nofile_fname);
nofile_fname = NULL;
CLEAR_POS(&saved_fmark.mark); // shutup gcc 4.0
saved_fmark.fnum = 0;
/*
* Don't add a tag to the tagstack if 'tagstack' has been reset.
*/
if ((!p_tgst && *tag != NUL))
{
use_tagstack = FALSE;
new_tag = TRUE;
#if defined(FEAT_QUICKFIX)
if (g_do_tagpreview != 0)
{
tagstack_clear_entry(&ptag_entry);
if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)
goto end_do_tag;
}
#endif
}
else
{
#if defined(FEAT_QUICKFIX)
if (g_do_tagpreview != 0)
use_tagstack = FALSE;
else
#endif
use_tagstack = TRUE;
// new pattern, add to the tag stack
if (*tag != NUL
&& (type == DT_TAG || type == DT_SELECT || type == DT_JUMP
#ifdef FEAT_QUICKFIX
|| type == DT_LTAG
#endif
#ifdef FEAT_CSCOPE
|| type == DT_CSCOPE
#endif
))
{
#if defined(FEAT_QUICKFIX)
if (g_do_tagpreview != 0)
{
if (ptag_entry.tagname != NULL
&& STRCMP(ptag_entry.tagname, tag) == 0)
{
// Jumping to same tag: keep the current match, so that
// the CursorHold autocommand example works.
cur_match = ptag_entry.cur_match;
cur_fnum = ptag_entry.cur_fnum;
}
else
{
tagstack_clear_entry(&ptag_entry);
if ((ptag_entry.tagname = vim_strsave(tag)) == NULL)
goto end_do_tag;
}
}
else
#endif
{
/*
* If the last used entry is not at the top, delete all tag
* stack entries above it.
*/
while (tagstackidx < tagstacklen)
tagstack_clear_entry(&tagstack[--tagstacklen]);
// if the tagstack is full: remove oldest entry
if (++tagstacklen > TAGSTACKSIZE)
{
tagstacklen = TAGSTACKSIZE;
tagstack_clear_entry(&tagstack[0]);
for (i = 1; i < tagstacklen; ++i)
tagstack[i - 1] = tagstack[i];
--tagstackidx;
}
/*
* put the tag name in the tag stack
*/
if ((tagstack[tagstackidx].tagname = vim_strsave(tag)) == NULL)
{
curwin->w_tagstacklen = tagstacklen - 1;
goto end_do_tag;
}
curwin->w_tagstacklen = tagstacklen;
save_pos = TRUE; // save the cursor position below
}
new_tag = TRUE;
}
else
{
if (
#if defined(FEAT_QUICKFIX)
g_do_tagpreview != 0 ? ptag_entry.tagname == NULL :
#endif
tagstacklen == 0)
{
// empty stack
emsg(_(e_tag_stack_empty));
goto end_do_tag;
}
if (type == DT_POP) // go to older position
{
#ifdef FEAT_FOLDING
int old_KeyTyped = KeyTyped;
#endif
if ((tagstackidx -= count) < 0)
{
emsg(_(e_at_bottom_of_tag_stack));
if (tagstackidx + count == 0)
{
// We did [num]^T from the bottom of the stack
tagstackidx = 0;
goto end_do_tag;
}
// We weren't at the bottom of the stack, so jump all the
// way to the bottom now.
tagstackidx = 0;
}
else if (tagstackidx >= tagstacklen) // count == 0?
{
emsg(_(e_at_top_of_tag_stack));
goto end_do_tag;
}
// Make a copy of the fmark, autocommands may invalidate the
// tagstack before it's used.
saved_fmark = tagstack[tagstackidx].fmark;
if (saved_fmark.fnum != curbuf->b_fnum)
{
/*
* Jump to other file. If this fails (e.g. because the
* file was changed) keep original position in tag stack.
*/
if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,
GETF_SETMARK, forceit) == FAIL)
{
tagstackidx = oldtagstackidx; // back to old posn
goto end_do_tag;
}
// An BufReadPost autocommand may jump to the '" mark, but
// we don't what that here.
curwin->w_cursor.lnum = saved_fmark.mark.lnum;
}
else
{
setpcmark();
curwin->w_cursor.lnum = saved_fmark.mark.lnum;
}
curwin->w_cursor.col = saved_fmark.mark.col;
curwin->w_set_curswant = TRUE;
check_cursor();
#ifdef FEAT_FOLDING
if ((fdo_flags & FDO_TAG) && old_KeyTyped)
foldOpenCursor();
#endif
// remove the old list of matches
FreeWild(num_matches, matches);
#ifdef FEAT_CSCOPE
cs_free_tags();
#endif
num_matches = 0;
tag_freematch();
goto end_do_tag;
}
if (type == DT_TAG
#if defined(FEAT_QUICKFIX)
|| type == DT_LTAG
#endif
)
{
#if defined(FEAT_QUICKFIX)
if (g_do_tagpreview != 0)
{
cur_match = ptag_entry.cur_match;
cur_fnum = ptag_entry.cur_fnum;
}
else
#endif
{
// ":tag" (no argument): go to newer pattern
save_pos = TRUE; // save the cursor position below
if ((tagstackidx += count - 1) >= tagstacklen)
{
/*
* Beyond the last one, just give an error message and
* go to the last one. Don't store the cursor
* position.
*/
tagstackidx = tagstacklen - 1;
emsg(_(e_at_top_of_tag_stack));
save_pos = FALSE;
}
else if (tagstackidx < 0) // must have been count == 0
{
emsg(_(e_at_bottom_of_tag_stack));
tagstackidx = 0;
goto end_do_tag;
}
cur_match = tagstack[tagstackidx].cur_match;
cur_fnum = tagstack[tagstackidx].cur_fnum;
}
new_tag = TRUE;
}
else // go to other matching tag
{
// Save index for when selection is cancelled.
prevtagstackidx = tagstackidx;
#if defined(FEAT_QUICKFIX)
if (g_do_tagpreview != 0)
{
cur_match = ptag_entry.cur_match;
cur_fnum = ptag_entry.cur_fnum;
}
else
#endif
{
if (--tagstackidx < 0)
tagstackidx = 0;
cur_match = tagstack[tagstackidx].cur_match;
cur_fnum = tagstack[tagstackidx].cur_fnum;
}
switch (type)
{
case DT_FIRST: cur_match = count - 1; break;
case DT_SELECT:
case DT_JUMP:
#ifdef FEAT_CSCOPE
case DT_CSCOPE:
#endif
case DT_LAST: cur_match = MAXCOL - 1; break;
case DT_NEXT: cur_match += count; break;
case DT_PREV: cur_match -= count; break;
}
if (cur_match >= MAXCOL)
cur_match = MAXCOL - 1;
else if (cur_match < 0)
{
emsg(_(e_cannot_go_before_first_matching_tag));
skip_msg = TRUE;
cur_match = 0;
cur_fnum = curbuf->b_fnum;
}
}
}
#if defined(FEAT_QUICKFIX)
if (g_do_tagpreview != 0)
{
if (type != DT_SELECT && type != DT_JUMP)
{
ptag_entry.cur_match = cur_match;
ptag_entry.cur_fnum = cur_fnum;
}
}
else
#endif
{
/*
* For ":tag [arg]" or ":tselect" remember position before the jump.
*/
saved_fmark = tagstack[tagstackidx].fmark;
if (save_pos)
{
tagstack[tagstackidx].fmark.mark = curwin->w_cursor;
tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum;
}
// Curwin will change in the call to jumpto_tag() if ":stag" was
// used or an autocommand jumps to another window; store value of
// tagstackidx now.
curwin->w_tagstackidx = tagstackidx;
if (type != DT_SELECT && type != DT_JUMP)
{
curwin->w_tagstack[tagstackidx].cur_match = cur_match;
curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum;
}
}
}
// When not using the current buffer get the name of buffer "cur_fnum".
// Makes sure that the tag order doesn't change when using a remembered
// position for "cur_match".
if (cur_fnum != curbuf->b_fnum)
{
buf_T *buf = buflist_findnr(cur_fnum);
if (buf != NULL)
buf_ffname = buf->b_ffname;
}
/*
* Repeat searching for tags, when a file has not been found.
*/
for (;;)
{
int other_name;
char_u *name;
/*
* When desired match not found yet, try to find it (and others).
*/
if (use_tagstack)
name = tagstack[tagstackidx].tagname;
#if defined(FEAT_QUICKFIX)
else if (g_do_tagpreview != 0)
name = ptag_entry.tagname;
#endif
else
name = tag;
other_name = (tagmatchname == NULL || STRCMP(tagmatchname, name) != 0);
if (new_tag
|| (cur_match >= num_matches && max_num_matches != MAXCOL)
|| other_name)
{
if (other_name)
{
vim_free(tagmatchname);
tagmatchname = vim_strsave(name);
}
if (type == DT_SELECT || type == DT_JUMP
#if defined(FEAT_QUICKFIX)
|| type == DT_LTAG
#endif
)
cur_match = MAXCOL - 1;
if (type == DT_TAG)
max_num_matches = MAXCOL;
else
max_num_matches = cur_match + 1;
// when the argument starts with '/', use it as a regexp
if (!no_regexp && *name == '/')
{
flags = TAG_REGEXP;
++name;
}
else
flags = TAG_NOIC;
#ifdef FEAT_CSCOPE
if (type == DT_CSCOPE)
flags = TAG_CSCOPE;
#endif
if (verbose)
flags |= TAG_VERBOSE;
if (!use_tfu)
flags |= TAG_NO_TAGFUNC;
if (find_tags(name, &new_num_matches, &new_matches, flags,
max_num_matches, buf_ffname) == OK
&& new_num_matches < max_num_matches)
max_num_matches = MAXCOL; // If less than max_num_matches
// found: all matches found.
// If there already were some matches for the same name, move them
// to the start. Avoids that the order changes when using
// ":tnext" and jumping to another file.
if (!new_tag && !other_name)
{
int j, k;
int idx = 0;
tagptrs_T tagp, tagp2;
// Find the position of each old match in the new list. Need
// to use parse_match() to find the tag line.
for (j = 0; j < num_matches; ++j)
{
parse_match(matches[j], &tagp);
for (i = idx; i < new_num_matches; ++i)
{
parse_match(new_matches[i], &tagp2);
if (STRCMP(tagp.tagname, tagp2.tagname) == 0)
{
char_u *p = new_matches[i];
for (k = i; k > idx; --k)
new_matches[k] = new_matches[k - 1];
new_matches[idx++] = p;
break;
}
}
}
}
FreeWild(num_matches, matches);
num_matches = new_num_matches;
matches = new_matches;
}
if (num_matches <= 0)
{
if (verbose)
semsg(_(e_tag_not_found_str), name);
#if defined(FEAT_QUICKFIX)
g_do_tagpreview = 0;
#endif
}
else
{
int ask_for_selection = FALSE;
#ifdef FEAT_CSCOPE
if (type == DT_CSCOPE && num_matches > 1)
{
cs_print_tags();
ask_for_selection = TRUE;
}
else
#endif
if (type == DT_TAG && *tag != NUL)
// If a count is supplied to the ":tag <name>" command, then
// jump to count'th matching tag.
cur_match = count > 0 ? count - 1 : 0;
else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1))
{
print_tag_list(new_tag, use_tagstack, num_matches, matches);
ask_for_selection = TRUE;
}
#if defined(FEAT_QUICKFIX) && defined(FEAT_EVAL)
else if (type == DT_LTAG)
{
if (add_llist_tags(tag, num_matches, matches) == FAIL)
goto end_do_tag;
cur_match = 0; // Jump to the first tag
}
#endif
if (ask_for_selection == TRUE)
{
/*
* Ask to select a tag from the list.
*/
i = prompt_for_number(NULL);
if (i <= 0 || i > num_matches || got_int)
{
// no valid choice: don't change anything
if (use_tagstack)
{
tagstack[tagstackidx].fmark = saved_fmark;
tagstackidx = prevtagstackidx;
}
#ifdef FEAT_CSCOPE
cs_free_tags();
jumped_to_tag = TRUE;
#endif
break;
}
cur_match = i - 1;
}
if (cur_match >= num_matches)
{
// Avoid giving this error when a file wasn't found and we're
// looking for a match in another file, which wasn't found.
// There will be an emsg("file doesn't exist") below then.
if ((type == DT_NEXT || type == DT_FIRST)
&& nofile_fname == NULL)
{
if (num_matches == 1)
emsg(_(e_there_is_only_one_matching_tag));
else
emsg(_(e_cannot_go_beyond_last_matching_tag));
skip_msg = TRUE;
}
cur_match = num_matches - 1;
}
if (use_tagstack)
{
tagptrs_T tagp;
tagstack[tagstackidx].cur_match = cur_match;
tagstack[tagstackidx].cur_fnum = cur_fnum;
// store user-provided data originating from tagfunc
if (use_tfu && parse_match(matches[cur_match], &tagp) == OK
&& tagp.user_data)
{
VIM_CLEAR(tagstack[tagstackidx].user_data);
tagstack[tagstackidx].user_data = vim_strnsave(
tagp.user_data, tagp.user_data_end - tagp.user_data);
}
++tagstackidx;
}
#if defined(FEAT_QUICKFIX)
else if (g_do_tagpreview != 0)
{
ptag_entry.cur_match = cur_match;
ptag_entry.cur_fnum = cur_fnum;
}
#endif
/*
* Only when going to try the next match, report that the previous
* file didn't exist. Otherwise an emsg() is given below.
*/
if (nofile_fname != NULL && error_cur_match != cur_match)
smsg(_("File \"%s\" does not exist"), nofile_fname);
ic = (matches[cur_match][0] & MT_IC_OFF);
if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP
#ifdef FEAT_CSCOPE
&& type != DT_CSCOPE
#endif
&& (num_matches > 1 || ic)
&& !skip_msg)
{
// Give an indication of the number of matching tags
sprintf((char *)IObuff, _("tag %d of %d%s"),
cur_match + 1,
num_matches,
max_num_matches != MAXCOL ? _(" or more") : "");
if (ic)
STRCAT(IObuff, _(" Using tag with different case!"));
if ((num_matches > prev_num_matches || new_tag)
&& num_matches > 1)
{
if (ic)
msg_attr((char *)IObuff, HL_ATTR(HLF_W));
else
msg((char *)IObuff);
msg_scroll = TRUE; // don't overwrite this message
}
else
give_warning(IObuff, ic);
if (ic && !msg_scrolled && msg_silent == 0)
{
out_flush();
ui_delay(1007L, TRUE);
}
}
#if defined(FEAT_EVAL)
// Let the SwapExists event know what tag we are jumping to.
vim_snprintf((char *)IObuff, IOSIZE, ":ta %s\r", name);
set_vim_var_string(VV_SWAPCOMMAND, IObuff, -1);
#endif
/*
* Jump to the desired match.
*/
i = jumpto_tag(matches[cur_match], forceit, type != DT_CSCOPE);
#if defined(FEAT_EVAL)
set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
#endif
if (i == NOTAGFILE)
{
// File not found: try again with another matching tag
if ((type == DT_PREV && cur_match > 0)
|| ((type == DT_TAG || type == DT_NEXT
|| type == DT_FIRST)
&& (max_num_matches != MAXCOL
|| cur_match < num_matches - 1)))
{
error_cur_match = cur_match;
if (use_tagstack)
--tagstackidx;
if (type == DT_PREV)
--cur_match;
else
{
type = DT_NEXT;
++cur_match;
}
continue;
}
semsg(_(e_file_str_does_not_exist), nofile_fname);
}
else
{
// We may have jumped to another window, check that
// tagstackidx is still valid.
if (use_tagstack && tagstackidx > curwin->w_tagstacklen)
tagstackidx = curwin->w_tagstackidx;
#ifdef FEAT_CSCOPE
jumped_to_tag = TRUE;
#endif
}
}
break;
}
end_do_tag:
// Only store the new index when using the tagstack and it's valid.
if (use_tagstack && tagstackidx <= curwin->w_tagstacklen)
curwin->w_tagstackidx = tagstackidx;
postponed_split = 0; // don't split next time
# ifdef FEAT_QUICKFIX
g_do_tagpreview = 0; // don't do tag preview next time
# endif
#ifdef FEAT_CSCOPE
return jumped_to_tag;
#else
return FALSE;
#endif
}
| null | null | 204,751
|
126478621754533124439278167196869287849
| 679
|
patch 9.0.0246: using freed memory when 'tagfunc' deletes the buffer
Problem: Using freed memory when 'tagfunc' deletes the buffer.
Solution: Make a copy of the tag name.
|
other
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.