id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_5418_2 | /*
* Copyright (c) 2001-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* Image Information Program
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <assert.h>
#include <stdint.h>
#include <jasper/jasper.h>
/******************************************************************************\
*
\******************************************************************************/
typedef enum {
OPT_HELP,
OPT_VERSION,
OPT_VERBOSE,
OPT_INFILE,
OPT_DEBUG,
OPT_MAXSAMPLES,
OPT_MAXMEM
} optid_t;
/******************************************************************************\
*
\******************************************************************************/
static void usage(void);
static void cmdinfo(void);
/******************************************************************************\
*
\******************************************************************************/
static jas_opt_t opts[] = {
{OPT_HELP, "help", 0},
{OPT_VERSION, "version", 0},
{OPT_VERBOSE, "verbose", 0},
{OPT_INFILE, "f", JAS_OPT_HASARG},
{OPT_DEBUG, "debug-level", JAS_OPT_HASARG},
{OPT_MAXSAMPLES, "max-samples", JAS_OPT_HASARG},
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
{OPT_MAXMEM, "memory-limit", JAS_OPT_HASARG},
#endif
{-1, 0, 0}
};
static char *cmdname = 0;
/******************************************************************************\
* Main program.
\******************************************************************************/
int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
size_t max_mem;
size_t max_samples;
char optstr[32];
if (jas_init()) {
abort();
}
cmdname = argv[0];
max_samples = 64 * JAS_MEBI;
infile = 0;
verbose = 0;
debug = 0;
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
#endif
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_MAXSAMPLES:
max_samples = strtoull(jas_optarg, 0, 10);
break;
case OPT_MAXMEM:
max_mem = strtoull(jas_optarg, 0, 10);
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
jas_set_max_mem_usage(max_mem);
#endif
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
snprintf(optstr, sizeof(optstr), "max_samples=%-zu", max_samples);
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, optstr))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
if (!(fmtname = jas_image_fmttostr(fmtid))) {
jas_eprintf("format name lookup failed\n");
return EXIT_FAILURE;
}
if (!(numcmpts = jas_image_numcmpts(image))) {
fprintf(stderr, "warning: image has no components\n");
}
if (numcmpts) {
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
} else {
width = 0;
height = 0;
depth = 0;
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth,
JAS_CAST(long, jas_image_rawsize(image)));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
/******************************************************************************\
*
\******************************************************************************/
static void cmdinfo()
{
fprintf(stderr, "Image Information Utility (Version %s).\n",
JAS_VERSION);
fprintf(stderr,
"Copyright (c) 2001 Michael David Adams.\n"
"All rights reserved.\n"
);
}
static void usage()
{
cmdinfo();
fprintf(stderr, "usage:\n");
fprintf(stderr,"%s ", cmdname);
fprintf(stderr, "[-f image_file]\n");
exit(EXIT_FAILURE);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5418_2 |
crossvul-cpp_data_good_3722_0 | /*
* jabberd - Jabber Open Source Server
* Copyright (c) 2002 Jeremie Miller, Thomas Muldowney,
* Ryan Eatmon, Robert Norris
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307USA
*/
#define _GNU_SOURCE
#include <string.h>
#include "s2s.h"
#include <idna.h>
/*
* we handle packets going from the router to the world, and stuff
* that comes in on connections we initiated.
*
* action points:
*
* out_packet(s2s, nad) - send this packet out
* - extract to domain
* - get dbconn for this domain using out_route
* - if dbconn not available bounce packet
* - DONE
* - if conn in progress (tcp)
* - add packet to queue for this domain
* - DONE
* - if dbconn state valid for this domain, or packet is dialback
* - send packet
* - DONE
* - if dbconn state invalid for this domain
* - bounce packet (502)
* - DONE
* - add packet to queue for this domain
* - if dbconn state inprogress for this domain
* - DONE
* - out_dialback(dbconn, from, to)
*
* out_route(s2s, route, out, allow_bad)
* - if dbconn not found
* - check internal resolver cache for domain
* - if not found
* - ask resolver for name
* - DONE
* - if outgoing ip/port is to be reused
* - get dbconn for any valid ip/port
* - if dbconn not found
* - create new dbconn
* - initiate connect to ip/port
* - DONE
* - create new dbconn
* - initiate connect to ip/port
* - DONE
*
* out_dialback(dbconn, from, to) - initiate dialback
* - generate dbkey: sha1(secret+remote+stream id)
* - send auth request: <result to='them' from='us'>dbkey</result>
* - set dbconn state for this domain to inprogress
* - DONE
*
* out_resolve(s2s, query) - responses from resolver
* - store ip/port/ttl in resolver cache
* - flush domain queue -> out_packet(s2s, domain)
* - DONE
*
* event_STREAM - ip/port open
* - get dbconn for this sx
* - for each route handled by this conn, out_dialback(dbconn, from, to)
* - DONE
*
* event_PACKET: <result from='them' to='us' type='xxx'/> - response to our auth request
* - get dbconn for this sx
* - if type valid
* - set dbconn state for this domain to valid
* - flush dbconn queue for this domain -> out_packet(s2s, pkt)
* - DONE
* - set dbconn state for this domain to invalid
* - bounce dbconn queue for this domain (502)
* - DONE
*
* event_PACKET: <verify from='them' to='us' id='123' type='xxx'/> - incoming stream authenticated
* - get dbconn for given id
* - if type is valid
* - set dbconn state for this domain to valid
* - send result: <result to='them' from='us' type='xxx'/>
* - DONE
*/
/* forward decls */
static int _out_mio_callback(mio_t m, mio_action_t a, mio_fd_t fd, void *data, void *arg);
static int _out_sx_callback(sx_t s, sx_event_t e, void *data, void *arg);
static void _out_result(conn_t out, nad_t nad);
static void _out_verify(conn_t out, nad_t nad);
static void _dns_result_aaaa(struct dns_ctx *ctx, struct dns_rr_a6 *result, void *data);
static void _dns_result_a(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data);
/** queue the packet */
static void _out_packet_queue(s2s_t s2s, pkt_t pkt) {
char *rkey = s2s_route_key(NULL, pkt->from->domain, pkt->to->domain);
jqueue_t q = (jqueue_t) xhash_get(s2s->outq, rkey);
if(q == NULL) {
log_debug(ZONE, "creating new out packet queue for '%s'", rkey);
q = jqueue_new();
q->key = rkey;
xhash_put(s2s->outq, q->key, (void *) q);
} else {
free(rkey);
}
log_debug(ZONE, "queueing packet for '%s'", q->key);
jqueue_push(q, (void *) pkt, 0);
}
static void _out_dialback(conn_t out, char *rkey, int rkeylen) {
char *c, *dbkey, *tmp;
nad_t nad;
int elem, ns;
int from_len, to_len;
time_t now;
now = time(NULL);
c = memchr(rkey, '/', rkeylen);
from_len = c - rkey;
c++;
to_len = rkeylen - (c - rkey);
/* kick off the dialback */
tmp = strndup(c, to_len);
dbkey = s2s_db_key(NULL, out->s2s->local_secret, tmp, out->s->id);
free(tmp);
nad = nad_new();
/* request auth */
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
elem = nad_append_elem(nad, ns, "result", 0);
nad_set_attr(nad, elem, -1, "from", rkey, from_len);
nad_set_attr(nad, elem, -1, "to", c, to_len);
nad_append_cdata(nad, dbkey, strlen(dbkey), 1);
log_debug(ZONE, "sending auth request for %.*s (key %s)", rkeylen, rkey, dbkey);
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] sending dialback auth request for route '%.*s'", out->fd->fd, out->ip, out->port, rkeylen, rkey);
/* off it goes */
sx_nad_write(out->s, nad);
free(dbkey);
/* we're in progress now */
xhash_put(out->states, pstrdupx(xhash_pool(out->states), rkey, rkeylen), (void *) conn_INPROGRESS);
/* record the time that we set conn_INPROGRESS state */
xhash_put(out->states_time, pstrdupx(xhash_pool(out->states_time), rkey, rkeylen), (void *) now);
}
void _out_dns_mark_bad(conn_t out) {
if (out->s2s->dns_bad_timeout > 0) {
dnsres_t bad;
char *ipport;
/* mark this host as bad */
ipport = dns_make_ipport(out->ip, out->port);
bad = xhash_get(out->s2s->dns_bad, ipport);
if (bad == NULL) {
bad = (dnsres_t) calloc(1, sizeof(struct dnsres_st));
bad->key = ipport;
xhash_put(out->s2s->dns_bad, ipport, bad);
}
bad->expiry = time(NULL) + out->s2s->dns_bad_timeout;
}
}
int dns_select(s2s_t s2s, char *ip, int *port, time_t now, dnscache_t dns, int allow_bad) {
/* list of results */
dnsres_t l_reuse[DNS_MAX_RESULTS];
dnsres_t l_aaaa[DNS_MAX_RESULTS];
dnsres_t l_a[DNS_MAX_RESULTS];
dnsres_t l_bad[DNS_MAX_RESULTS];
/* running weight sums of results */
int rw_reuse[DNS_MAX_RESULTS];
int rw_aaaa[DNS_MAX_RESULTS];
int rw_a[DNS_MAX_RESULTS];
int s_reuse = 0, s_aaaa = 0, s_a = 0, s_bad = 0; /* count */
int p_reuse = 0, p_aaaa = 0, p_a = 0; /* list prio */
int wt_reuse = 0, wt_aaaa = 0, wt_a = 0; /* weight total */
int c_expired_good = 0;
union xhashv xhv;
dnsres_t res;
char *ipport;
int ipport_len;
char *c;
int c_len;
char *tmp;
/* for all results:
* - if not expired
* - put highest priority reuseable addrs into list1
* - put highest priority ipv6 addrs into list2
* - put highest priority ipv4 addrs into list3
* - put bad addrs into list4
* - pick weighted random entry from first non-empty list
*/
if (dns->results == NULL) {
log_debug(ZONE, "negative cache entry for '%s'", dns->name);
return -1;
}
log_debug(ZONE, "selecting DNS result for '%s'", dns->name);
xhv.dnsres_val = &res;
if (xhash_iter_first(dns->results)) {
dnsres_t bad = NULL;
do {
xhash_iter_get(dns->results, (const char **) &ipport, &ipport_len, xhv.val);
if (s2s->dns_bad_timeout > 0)
bad = xhash_getx(s2s->dns_bad, ipport, ipport_len);
if (now > res->expiry) {
/* good host? */
if (bad == NULL)
c_expired_good++;
log_debug(ZONE, "host '%s' expired", res->key);
continue;
} else if (bad != NULL && !(now > bad->expiry)) {
/* bad host (connection failure) */
l_bad[s_bad++] = res;
log_debug(ZONE, "host '%s' bad", res->key);
} else if (s2s->out_reuse && xhash_getx(s2s->out_host, ipport, ipport_len) != NULL) {
/* existing connection */
log_debug(ZONE, "host '%s' exists", res->key);
if (s_reuse == 0 || p_reuse > res->prio) {
p_reuse = res->prio;
s_reuse = 0;
wt_reuse = 0;
log_debug(ZONE, "reset prio list, using prio %d", res->prio);
}
if (res->prio <= p_reuse) {
l_reuse[s_reuse] = res;
wt_reuse += res->weight;
rw_reuse[s_reuse] = wt_reuse;
s_reuse++;
log_debug(ZONE, "added host with weight %d (%d), running weight %d",
(res->weight >> 8), res->weight, wt_reuse);
} else {
log_debug(ZONE, "ignored host with prio %d", res->prio);
}
} else if (memchr(ipport, ':', ipport_len) != NULL) {
/* ipv6 */
log_debug(ZONE, "host '%s' IPv6", res->key);
if (s_aaaa == 0 || p_aaaa > res->prio) {
p_aaaa = res->prio;
s_aaaa = 0;
wt_aaaa = 0;
log_debug(ZONE, "reset prio list, using prio %d", res->prio);
}
if (res->prio <= p_aaaa) {
l_aaaa[s_aaaa] = res;
wt_aaaa += res->weight;
rw_aaaa[s_aaaa] = wt_aaaa;
s_aaaa++;
log_debug(ZONE, "added host with weight %d (%d), running weight %d",
(res->weight >> 8), res->weight, wt_aaaa);
} else {
log_debug(ZONE, "ignored host with prio %d", res->prio);
}
} else {
/* ipv4 */
log_debug(ZONE, "host '%s' IPv4", res->key);
if (s_a == 0 || p_a > res->prio) {
p_a = res->prio;
s_a = 0;
wt_a = 0;
log_debug(ZONE, "reset prio list, using prio %d", res->prio);
}
if (res->prio <= p_a) {
l_a[s_a] = res;
wt_a += res->weight;
rw_a[s_a] = wt_a;
s_a++;
log_debug(ZONE, "added host with weight %d (%d), running weight %d",
(res->weight >> 8), res->weight, wt_a);
} else {
log_debug(ZONE, "ignored host with prio %d", res->prio);
}
}
} while(xhash_iter_next(dns->results));
}
/* pick a result at weighted random (RFC 2782)
* all weights are guaranteed to be >= 16 && <= 16776960
* (assuming max 50 hosts, the total/running sums won't exceed 2^31)
*/
ipport = NULL;
if (s_reuse > 0) {
int i, r;
log_debug(ZONE, "using existing hosts, total weight %d", wt_reuse);
assert((wt_reuse + 1) > 0);
r = rand() % (wt_reuse + 1);
log_debug(ZONE, "random number %d", r);
for (i = 0; i < s_reuse; i++)
if (rw_reuse[i] >= r) {
log_debug(ZONE, "selected host '%s', running weight %d",
l_reuse[i]->key, rw_reuse[i]);
ipport = l_reuse[i]->key;
break;
}
} else if (s_aaaa > 0 && (s_a == 0 || p_aaaa <= p_a)) {
int i, r;
log_debug(ZONE, "using IPv6 hosts, total weight %d", wt_aaaa);
assert((wt_aaaa + 1) > 0);
r = rand() % (wt_aaaa + 1);
log_debug(ZONE, "random number %d", r);
for (i = 0; i < s_aaaa; i++)
if (rw_aaaa[i] >= r) {
log_debug(ZONE, "selected host '%s', running weight %d",
l_aaaa[i]->key, rw_aaaa[i]);
ipport = l_aaaa[i]->key;
break;
}
} else if (s_a > 0) {
int i, r;
log_debug(ZONE, "using IPv4 hosts, total weight %d", wt_a);
assert((wt_a + 1) > 0);
r = rand() % (wt_a + 1);
log_debug(ZONE, "random number %d", r);
for (i = 0; i < s_a; i++)
if (rw_a[i] >= r) {
log_debug(ZONE, "selected host '%s', running weight %d",
l_a[i]->key, rw_a[i]);
ipport = l_a[i]->key;
break;
}
} else if (s_bad > 0) {
ipport = l_bad[rand() % s_bad]->key;
log_debug(ZONE, "using bad hosts, allow_bad=%d", allow_bad);
/* there are expired good hosts, expire cache immediately */
if (c_expired_good > 0) {
log_debug(ZONE, "expiring this DNS cache entry, %d expired hosts",
c_expired_good);
dns->expiry = 0;
}
if (!allow_bad)
return -1;
}
/* results cannot all expire before the collection does */
assert(ipport != NULL);
/* copy the ip and port to the packet */
ipport_len = strlen(ipport);
c = strchr(ipport, '/');
strncpy(ip, ipport, c-ipport);
ip[c-ipport] = '\0';
c++;
c_len = ipport_len - (c - ipport);
tmp = strndup(c, c_len);
*port = atoi(tmp);
free(tmp);
return 0;
}
/** find/make a connection for a route */
int out_route(s2s_t s2s, char *route, int routelen, conn_t *out, int allow_bad) {
dnscache_t dns;
char ipport[INET6_ADDRSTRLEN + 16], *dkey, *c;
time_t now;
int reuse = 0;
char ip[INET6_ADDRSTRLEN] = {0};
int port, c_len, from_len;
c = memchr(route, '/', routelen);
from_len = c - route;
c++;
c_len = routelen - (c - route);
dkey = strndup(c, c_len);
log_debug(ZONE, "trying to find connection for '%s'", dkey);
*out = (conn_t) xhash_get(s2s->out_dest, dkey);
if(*out == NULL) {
log_debug(ZONE, "connection for '%s' not found", dkey);
/* check resolver cache for ip/port */
dns = xhash_get(s2s->dnscache, dkey);
if(dns == NULL) {
/* new resolution */
log_debug(ZONE, "no dns for %s, preparing for resolution", dkey);
dns = (dnscache_t) calloc(1, sizeof(struct dnscache_st));
strcpy(dns->name, dkey);
xhash_put(s2s->dnscache, dns->name, (void *) dns);
#if 0
/* this is good for testing */
dns->pending = 0;
strcpy(dns->ip, "127.0.0.1");
dns->port = 3000;
dns->expiry = time(NULL) + 99999999;
#endif
}
/* resolution in progress */
if(dns->pending) {
log_debug(ZONE, "pending resolution");
free(dkey);
return 0;
}
/* has it expired (this is 0 for new cache objects, so they're always expired */
now = time(NULL); /* each entry must be expired no earlier than the collection */
if(now > dns->expiry) {
/* resolution required */
log_debug(ZONE, "requesting resolution for %s", dkey);
dns->init_time = time(NULL);
dns->pending = 1;
dns_resolve_domain(s2s, dns);
free(dkey);
return 0;
}
/* dns is valid */
if (dns_select(s2s, ip, &port, now, dns, allow_bad)) {
/* failed to find anything acceptable */
free(dkey);
return -1;
}
/* re-request resolution if dns_select expired the data */
if (now > dns->expiry) {
/* resolution required */
log_debug(ZONE, "requesting resolution for %s", dkey);
dns->init_time = time(NULL);
dns->pending = 1;
dns_resolve_domain(s2s, dns);
free(dkey);
return 0;
}
/* generate the ip/port pair, this is the hash key for the conn */
snprintf(ipport, INET6_ADDRSTRLEN + 16, "%s/%d", ip, port);
/* try to re-use an existing connection */
if (s2s->out_reuse)
*out = (conn_t) xhash_get(s2s->out_host, ipport);
if (*out != NULL) {
log_write(s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] using connection for '%s'", (*out)->fd->fd, (*out)->ip, (*out)->port, dkey);
/* associate existing connection with domain */
xhash_put(s2s->out_dest, s2s->out_reuse ? pstrdup(xhash_pool((*out)->routes), dkey) : dkey, (void *) *out);
reuse = 1;
} else{
/* no conn, create one */
*out = (conn_t) calloc(1, sizeof(struct conn_st));
(*out)->s2s = s2s;
(*out)->key = strdup(ipport);
if (s2s->out_reuse)
(*out)->dkey = NULL;
else
(*out)->dkey = dkey;
strcpy((*out)->ip, ip);
(*out)->port = port;
(*out)->states = xhash_new(101);
(*out)->states_time = xhash_new(101);
(*out)->routes = xhash_new(101);
(*out)->init_time = time(NULL);
if (s2s->out_reuse)
xhash_put(s2s->out_host, (*out)->key, (void *) *out);
xhash_put(s2s->out_dest, s2s->out_reuse ? pstrdup(xhash_pool((*out)->routes), dkey) : dkey, (void *) *out);
xhash_put((*out)->routes, pstrdupx(xhash_pool((*out)->routes), route, routelen), (void *) 1);
/* connect */
log_debug(ZONE, "initiating connection to %s", ipport);
/* APPLE: multiple origin_ips may be specified; use IPv6 if possible or otherwise IPv4 */
int ip_is_v6 = 0;
if (strchr(ip, ':') != NULL)
ip_is_v6 = 1;
int i;
for (i = 0; i < s2s->origin_nips; i++) {
// only bother with mio_connect if the src and dst IPs are of the same type
if ((ip_is_v6 && (strchr(s2s->origin_ips[i], ':') != NULL)) || // both are IPv6
(! ip_is_v6 && (strchr(s2s->origin_ips[i], ':') == NULL))) // both are IPv4
(*out)->fd = mio_connect(s2s->mio, port, ip, s2s->origin_ips[i], _out_mio_callback, (void *) *out);
if ((*out)->fd != NULL) break;
}
if ((*out)->fd == NULL) {
log_write(s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] mio_connect error: %s (%d)", -1, (*out)->ip, (*out)->port, MIO_STRERROR(MIO_ERROR), MIO_ERROR);
_out_dns_mark_bad(*out);
if (s2s->out_reuse)
xhash_zap(s2s->out_host, (*out)->key);
xhash_zap(s2s->out_dest, dkey);
xhash_free((*out)->states);
xhash_free((*out)->states_time);
xhash_free((*out)->routes);
free((*out)->key);
free((*out)->dkey);
free(*out);
*out = NULL;
/* try again without allowing bad hosts */
return out_route(s2s, route, routelen, out, 0);
} else {
log_write(s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing connection for '%s'", (*out)->fd->fd, (*out)->ip, (*out)->port, dkey);
(*out)->s = sx_new(s2s->sx_env, (*out)->fd->fd, _out_sx_callback, (void *) *out);
#ifdef HAVE_SSL
/* Send a stream version of 1.0 if we can do STARTTLS */
if(s2s->sx_ssl != NULL) {
sx_client_init((*out)->s, S2S_DB_HEADER, uri_SERVER, dkey, pstrdupx(xhash_pool((*out)->routes), route, from_len), "1.0");
} else {
sx_client_init((*out)->s, S2S_DB_HEADER, uri_SERVER, NULL, NULL, NULL);
}
#else
sx_client_init((*out)->s, S2S_DB_HEADER, uri_SERVER, NULL, NULL, NULL);
#endif
/* dkey is now used by the hash table */
return 0;
}
}
} else {
log_debug(ZONE, "connection for '%s' found (%d %s/%d)", dkey, (*out)->fd->fd, (*out)->ip, (*out)->port);
}
/* connection in progress, or re-using connection: add to routes list */
if (!(*out)->online || reuse) {
if (xhash_getx((*out)->routes, route, routelen) == NULL)
xhash_put((*out)->routes, pstrdupx(xhash_pool((*out)->routes), route, routelen), (void *) 1);
}
free(dkey);
return 0;
}
void out_pkt_free(pkt_t pkt)
{
nad_free(pkt->nad);
jid_free(pkt->from);
jid_free(pkt->to);
free(pkt);
}
/** send a packet out */
int out_packet(s2s_t s2s, pkt_t pkt) {
char *rkey;
int rkeylen;
conn_t out;
conn_state_t state;
int ret;
/* perform check against whitelist */
if (s2s->enable_whitelist > 0 &&
(pkt->to->domain != NULL) &&
(s2s_domain_in_whitelist(s2s, pkt->to->domain) == 0)) {
log_write(s2s->log, LOG_NOTICE, "sending a packet to domain not in the whitelist, dropping it");
if (pkt->to != NULL)
jid_free(pkt->to);
if (pkt->from != NULL)
jid_free(pkt->from);
if (pkt->nad != NULL)
nad_free(pkt->nad);
free(pkt);
return;
}
/* new route key */
rkey = s2s_route_key(NULL, pkt->from->domain, pkt->to->domain);
rkeylen = strlen(rkey);
/* get a connection */
ret = out_route(s2s, rkey, rkeylen, &out, 1);
if (out == NULL) {
/* connection not available, queue packet */
_out_packet_queue(s2s, pkt);
/* check if out_route was successful in attempting a connection */
if (ret) {
/* bounce queue */
out_bounce_route_queue(s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
return -1;
}
free(rkey);
return 0;
}
/* connection in progress */
if(!out->online) {
log_debug(ZONE, "connection in progress, queueing packet");
_out_packet_queue(s2s, pkt);
free(rkey);
return 0;
}
/* connection state */
state = (conn_state_t) xhash_get(out->states, rkey);
/* valid conns or dialback packets */
if(state == conn_VALID || pkt->db) {
log_debug(ZONE, "writing packet for %s to outgoing conn %d", rkey, out->fd->fd);
/* send it straight out */
if(pkt->db) {
/* if this is a db:verify packet, increment counter and set timestamp */
if(NAD_ENAME_L(pkt->nad, 0) == 6 && strncmp("verify", NAD_ENAME(pkt->nad, 0), 6) == 0) {
out->verify++;
out->last_verify = time(NULL);
}
/* dialback packet */
sx_nad_write(out->s, pkt->nad);
} else {
/* if the outgoing stanza has a jabber:client namespace, remove it so that the stream jabber:server namespaces will apply (XMPP 11.2.2) */
int ns = nad_find_namespace(pkt->nad, 1, uri_CLIENT, NULL);
if(ns >= 0) {
/* clear the namespaces of elem 0 (internal route element) and elem 1 (message|iq|presence) */
pkt->nad->elems[0].ns = -1;
pkt->nad->elems[0].my_ns = -1;
pkt->nad->elems[1].ns = -1;
pkt->nad->elems[1].my_ns = -1;
}
/* send it out */
sx_nad_write_elem(out->s, pkt->nad, 1);
}
/* update timestamp */
out->last_packet = time(NULL);
jid_free(pkt->from);
jid_free(pkt->to);
free(pkt);
free(rkey);
return 0;
}
/* can't be handled yet, queue */
_out_packet_queue(s2s, pkt);
/* if dialback is in progress, then we're done for now */
if(state == conn_INPROGRESS) {
free(rkey);
return 0;
}
/* this is a new route - send dialback auth request to piggyback on the existing connection */
if (out->s2s->require_tls == 0 || out->s->ssf > 0) {
_out_dialback(out, rkey, rkeylen);
}
free(rkey);
return 0;
}
char *dns_make_ipport(char *host, int port) {
char *c;
assert(port > 0 && port < 65536);
c = (char *) malloc(strlen(host) + 7);
sprintf(c, "%s/%d", host, port);
return c;
}
static void _dns_add_result(dnsquery_t query, char *ip, int port, int prio, int weight, unsigned int ttl) {
char *ipport = dns_make_ipport(ip, port);
dnsres_t res = xhash_get(query->results, ipport);
if (res != NULL) {
if (prio < res->prio)
res->prio = prio;
if (prio < res->prio) {
/* duplicate host at lower prio - reset weight */
res->weight = weight;
} else if (prio == res->prio) {
/* duplicate host at same prio - add to weight */
res->weight += weight;
if (res->weight > (65535 << 8))
res->weight = (65535 << 8);
}
if (ttl > res->expiry)
res->expiry = ttl;
if (ttl > query->expiry)
query->expiry = ttl;
log_debug(ZONE, "dns result updated for %s@%p: %s (%d/%d/%d)", query->name, query, ipport,
res->prio, (res->weight >> 8), res->expiry);
} else if (xhash_count(query->results) < DNS_MAX_RESULTS) {
res = pmalloc(xhash_pool(query->results), sizeof(struct dnsres_st));
res->key = pstrdup(xhash_pool(query->results), ipport);
res->prio = prio;
res->weight = weight;
res->expiry = ttl;
if (ttl > query->expiry)
query->expiry = ttl;
xhash_put(query->results, res->key, res);
log_debug(ZONE, "dns result added for %s@%p: %s (%d/%d/%d)", query->name, query, ipport,
res->prio, (res->weight >> 8), res->expiry);
} else {
log_debug(ZONE, "dns result ignored for %s@%p: %s (%d/%d/%d)", query->name, query, ipport,
prio, (weight >> 8), ttl);
}
free(ipport);
}
static void _dns_add_host(dnsquery_t query, char *ip, int port, int prio, int weight, unsigned int ttl) {
char *ipport = dns_make_ipport(ip, port);
dnsres_t res = xhash_get(query->hosts, ipport);
/* update host weights:
* RFC 2482 "In the presence of records containing weights greater
* than 0, records with weight 0 should have a very small chance of
* being selected."
* 0 -> 16
* 1-65535 -> 256-16776960
*/
if (weight == 0)
weight = 1 << 4;
else
weight <<= 8;
if (res != NULL) {
if (prio < res->prio)
res->prio = prio;
if (prio < res->prio) {
/* duplicate host at lower prio - reset weight */
res->weight = weight;
} else if (prio == res->prio) {
/* duplicate host at same prio - add to weight */
res->weight += weight;
if (res->weight > (65535 << 8))
res->weight = (65535 << 8);
}
if (ttl > res->expiry)
res->expiry = ttl;
log_debug(ZONE, "dns host updated for %s@%p: %s (%d/%d/%d)", query->name, query, ipport,
res->prio, (res->weight >> 8), res->expiry);
} else if (xhash_count(query->hosts) < DNS_MAX_RESULTS) {
res = pmalloc(xhash_pool(query->hosts), sizeof(struct dnsres_st));
res->key = pstrdup(xhash_pool(query->hosts), ipport);
res->prio = prio;
res->weight = weight;
res->expiry = ttl;
xhash_put(query->hosts, res->key, res);
log_debug(ZONE, "dns host added for %s@%p: %s (%d/%d/%d)", query->name, query, ipport,
res->prio, (res->weight >> 8), res->expiry);
} else {
log_debug(ZONE, "dns host ignored for %s@%p: %s (%d/%d/%d)", query->name, query, ipport,
prio, (weight >> 8), ttl);
}
free(ipport);
}
/* this function is called with a NULL ctx to start the SRV process */
static void _dns_result_srv(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) {
dnsquery_t query = data;
assert(query != NULL);
query->query = NULL;
if (ctx != NULL && result == NULL) {
log_debug(ZONE, "dns failure for %s@%p: SRV %s (%d)", query->name, query,
query->s2s->lookup_srv[query->srv_i], dns_status(ctx));
} else if (result != NULL) {
int i;
log_debug(ZONE, "dns response for %s@%p: SRV %s %d (%d)", query->name, query,
result->dnssrv_qname, result->dnssrv_nrr, result->dnssrv_ttl);
for (i = 0; i < result->dnssrv_nrr; i++) {
if (strlen(result->dnssrv_srv[i].name) > 0
&& result->dnssrv_srv[i].port > 0
&& result->dnssrv_srv[i].port < 65536) {
log_debug(ZONE, "dns response for %s@%p: SRV %s[%d] %s/%d (%d/%d)", query->name,
query, result->dnssrv_qname, i,
result->dnssrv_srv[i].name, result->dnssrv_srv[i].port,
result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight);
_dns_add_host(query, result->dnssrv_srv[i].name,
result->dnssrv_srv[i].port, result->dnssrv_srv[i].priority,
result->dnssrv_srv[i].weight, result->dnssrv_ttl);
}
}
free(result);
}
/* check next SRV service name */
query->srv_i++;
if (query->srv_i < query->s2s->lookup_nsrv) {
log_debug(ZONE, "dns request for %s@%p: SRV %s", query->name, query,
query->s2s->lookup_srv[query->srv_i]);
query->query = dns_submit_srv(NULL, query->name, query->s2s->lookup_srv[query->srv_i], "tcp",
DNS_NOSRCH, _dns_result_srv, query);
/* if submit failed, call ourselves with a NULL result */
if (query->query == NULL)
_dns_result_srv(ctx, NULL, query);
} else {
/* no more SRV records to check, resolve hosts */
if (xhash_count(query->hosts) > 0) {
_dns_result_a(NULL, NULL, query);
/* no SRV records returned, resolve hostname */
} else {
query->cur_host = strdup(query->name);
query->cur_port = 5269;
query->cur_prio = 0;
query->cur_weight = 0;
query->cur_expiry = 0;
if (query->s2s->resolve_aaaa) {
log_debug(ZONE, "dns request for %s@%p: AAAA %s", query->name, query, query->name);
query->query = dns_submit_a6(NULL, query->name,
DNS_NOSRCH, _dns_result_aaaa, query);
/* if submit failed, call ourselves with a NULL result */
if (query->query == NULL)
_dns_result_aaaa(ctx, NULL, query);
} else {
log_debug(ZONE, "dns request for %s@%p: A %s", query->name, query, query->name);
query->query = dns_submit_a4(NULL, query->name,
DNS_NOSRCH, _dns_result_a, query);
/* if submit failed, call ourselves with a NULL result */
if (query->query == NULL)
_dns_result_a(ctx, NULL, query);
}
}
}
}
static void _dns_result_aaaa(struct dns_ctx *ctx, struct dns_rr_a6 *result, void *data) {
dnsquery_t query = data;
char ip[INET6_ADDRSTRLEN];
int i;
assert(query != NULL);
query->query = NULL;
if (ctx != NULL && result == NULL) {
log_debug(ZONE, "dns failure for %s@%p: AAAA %s (%d)", query->name, query,
query->cur_host, dns_status(ctx));
} else if (result != NULL) {
log_debug(ZONE, "dns response for %s@%p: AAAA %s %d (%d)", query->name, query,
result->dnsa6_qname, result->dnsa6_nrr, result->dnsa6_ttl);
if (query->cur_expiry > 0 && result->dnsa6_ttl > query->cur_expiry)
result->dnsa6_ttl = query->cur_expiry;
for (i = 0; i < result->dnsa6_nrr; i++) {
if (inet_ntop(AF_INET6, &result->dnsa6_addr[i], ip, INET6_ADDRSTRLEN) != NULL) {
log_debug(ZONE, "dns response for %s@%p: AAAA %s[%d] %s/%d", query->name,
query, result->dnsa6_qname, i, ip, query->cur_port);
_dns_add_result(query, ip, query->cur_port,
query->cur_prio, query->cur_weight, result->dnsa6_ttl);
}
}
}
if (query->cur_host != NULL) {
/* do ipv4 resolution too */
log_debug(ZONE, "dns request for %s@%p: A %s", query->name, query, query->cur_host);
query->query = dns_submit_a4(NULL, query->cur_host,
DNS_NOSRCH, _dns_result_a, query);
/* if submit failed, call ourselves with a NULL result */
if (query->query == NULL)
_dns_result_a(ctx, NULL, query);
} else {
/* uh-oh */
log_debug(ZONE, "dns result for %s@%p: AAAA host vanished...", query->name, query);
_dns_result_a(NULL, NULL, query);
}
free(result);
}
/* try /etc/hosts if the A process did not return any results */
static int _etc_hosts_lookup(const char *cszName, char *szIP, const int ciMaxIPLen) {
#define EHL_LINE_LEN 260
int iSuccess = 0;
size_t iLen;
char szLine[EHL_LINE_LEN + 1]; /* one extra for the space character (*) */
char *pcStart, *pcEnd;
FILE *fHosts;
do {
/* initialization */
fHosts = NULL;
/* sanity checks */
if ((cszName == NULL) || (szIP == NULL) || (ciMaxIPLen <= 0))
break;
szIP[0] = 0;
/* open the hosts file */
#ifdef _WIN32
pcStart = getenv("WINDIR");
if (pcStart != NULL) {
sprintf(szLine, "%s\\system32\\drivers\\etc\\hosts", pcStart);
} else {
strcpy(szLine, "C:\\WINDOWS\\system32\\drivers\\etc\\hosts");
}
#else
strcpy(szLine, "/etc/hosts");
#endif
fHosts = fopen(szLine, "r");
if (fHosts == NULL)
break;
/* read line by line ... */
while (fgets(szLine, EHL_LINE_LEN, fHosts) != NULL) {
/* remove comments */
pcStart = strchr (szLine, '#');
if (pcStart != NULL)
*pcStart = 0;
strcat(szLine, " "); /* append a space character for easier parsing (*) */
/* first to appear: IP address */
iLen = strspn(szLine, "1234567890.");
if ((iLen < 7) || (iLen > 15)) /* superficial test for anything between x.x.x.x and xxx.xxx.xxx.xxx */
continue;
pcEnd = szLine + iLen;
*pcEnd = 0;
pcEnd++; /* not beyond the end of the line yet (*) */
/* check strings separated by blanks, tabs or newlines */
pcStart = pcEnd + strspn(pcEnd, " \t\n");
while (*pcStart != 0) {
pcEnd = pcStart + strcspn(pcStart, " \t\n");
*pcEnd = 0;
pcEnd++; /* not beyond the end of the line yet (*) */
if (strcasecmp(pcStart, cszName) == 0) {
strncpy(szIP, szLine, ciMaxIPLen - 1);
szIP[ciMaxIPLen - 1] = '\0';
iSuccess = 1;
break;
}
pcStart = pcEnd + strspn(pcEnd, " \t\n");
}
if (iSuccess)
break;
}
} while (0);
if (fHosts != NULL)
fclose(fHosts);
return (iSuccess);
}
/* this function is called with a NULL ctx to start the A/AAAA process */
static void _dns_result_a(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) {
dnsquery_t query = data;
assert(query != NULL);
query->query = NULL;
if (ctx != NULL && result == NULL) {
#define DRA_IP_LEN 16
char szIP[DRA_IP_LEN];
if (_etc_hosts_lookup (query->name, szIP, DRA_IP_LEN)) {
log_debug(ZONE, "/etc/lookup for %s@%p: %s (%d)", query->name,
query, szIP, query->s2s->etc_hosts_ttl);
_dns_add_result (query, szIP, query->cur_port,
query->cur_prio, query->cur_weight, query->s2s->etc_hosts_ttl);
} else {
log_debug(ZONE, "dns failure for %s@%p: A %s (%d)", query->name, query,
query->cur_host, dns_status(ctx));
}
} else if (result != NULL) {
char ip[INET_ADDRSTRLEN];
int i;
log_debug(ZONE, "dns response for %s@%p: A %s %d (%d)", query->name,
query, result->dnsa4_qname, result->dnsa4_nrr, result->dnsa4_ttl);
if (query->cur_expiry > 0 && result->dnsa4_ttl > query->cur_expiry)
result->dnsa4_ttl = query->cur_expiry;
for (i = 0; i < result->dnsa4_nrr; i++) {
if (inet_ntop(AF_INET, &result->dnsa4_addr[i], ip, INET_ADDRSTRLEN) != NULL) {
log_debug(ZONE, "dns response for %s@%p: A %s[%d] %s/%d", query->name,
query, result->dnsa4_qname, i, ip, query->cur_port);
_dns_add_result(query, ip, query->cur_port,
query->cur_prio, query->cur_weight, result->dnsa4_ttl);
}
}
free(result);
}
/* resolve the next host in the list */
if (xhash_iter_first(query->hosts)) {
char *ipport, *c, *tmp;
int ipport_len, ip_len, port_len;
dnsres_t res;
union xhashv xhv;
xhv.dnsres_val = &res;
/* get the first entry */
xhash_iter_get(query->hosts, (const char **) &ipport, &ipport_len, xhv.val);
/* remove the host from the list */
xhash_iter_zap(query->hosts);
c = memchr(ipport, '/', ipport_len);
ip_len = c - ipport;
c++;
port_len = ipport_len - (c - ipport);
/* resolve hostname */
free(query->cur_host);
query->cur_host = strndup(ipport, ip_len);
tmp = strndup(c, port_len);
query->cur_port = atoi(tmp);
free(tmp);
query->cur_prio = res->prio;
query->cur_weight = res->weight;
query->cur_expiry = res->expiry;
log_debug(ZONE, "dns ttl for %s@%p limited to %d", query->name, query, query->cur_expiry);
if (query->s2s->resolve_aaaa) {
log_debug(ZONE, "dns request for %s@%p: AAAA %s", query->name, query, query->cur_host);
query->query = dns_submit_a6(NULL, query->cur_host, DNS_NOSRCH, _dns_result_aaaa, query);
/* if submit failed, call ourselves with a NULL result */
if (query->query == NULL)
_dns_result_aaaa(ctx, NULL, query);
} else {
log_debug(ZONE, "dns request for %s@%p: A %s", query->name, query, query->cur_host);
query->query = dns_submit_a4(NULL, query->cur_host, DNS_NOSRCH, _dns_result_a, query);
/* if submit failed, call ourselves with a NULL result */
if (query->query == NULL)
_dns_result_a(ctx, NULL, query);
}
/* finished */
} else {
time_t now = time(NULL);
char *domain;
free(query->cur_host);
query->cur_host = NULL;
log_debug(ZONE, "dns requests for %s@%p complete: %d (%d)", query->name,
query, xhash_count(query->results), query->expiry);
/* update query TTL */
if (query->expiry > query->s2s->dns_max_ttl)
query->expiry = query->s2s->dns_max_ttl;
if (query->expiry < query->s2s->dns_min_ttl)
query->expiry = query->s2s->dns_min_ttl;
query->expiry += now;
/* update result TTLs - the query expiry MUST NOT be longer than all result expiries */
if (xhash_iter_first(query->results)) {
union xhashv xhv;
dnsres_t res;
xhv.dnsres_val = &res;
do {
xhash_iter_get(query->results, NULL, NULL, xhv.val);
if (res->expiry > query->s2s->dns_max_ttl)
res->expiry = query->s2s->dns_max_ttl;
if (res->expiry < query->s2s->dns_min_ttl)
res->expiry = query->s2s->dns_min_ttl;
res->expiry += now;
} while(xhash_iter_next(query->results));
}
xhash_free(query->hosts);
query->hosts = NULL;
if (idna_to_unicode_8z8z(query->name, &domain, 0) != IDNA_SUCCESS) {
log_write(query->s2s->log, LOG_ERR, "idna dns decode for %s failed", query->name);
/* fake empty results to shortcut resolution failure */
xhash_free(query->results);
query->results = xhash_new(71);
query->expiry = time(NULL) + 99999999;
domain = strdup(query->name);
}
out_resolve(query->s2s, domain, query->results, query->expiry);
free(domain);
free(query->name);
free(query);
}
}
void dns_resolve_domain(s2s_t s2s, dnscache_t dns) {
dnsquery_t query = (dnsquery_t) calloc(1, sizeof(struct dnsquery_st));
query->s2s = s2s;
query->results = xhash_new(71);
if (idna_to_ascii_8z(dns->name, &query->name, 0) != IDNA_SUCCESS) {
log_write(s2s->log, LOG_ERR, "idna dns encode for %s failed", dns->name);
/* shortcut resolution failure */
query->expiry = time(NULL) + 99999999;
out_resolve(query->s2s, dns->name, query->results, query->expiry);
return;
}
query->hosts = xhash_new(71);
query->srv_i = -1;
query->expiry = 0;
query->cur_host = NULL;
query->cur_port = 0;
query->cur_expiry = 0;
query->query = NULL;
dns->query = query;
log_debug(ZONE, "dns resolve for %s@%p started", query->name, query);
/* - resolve all SRV records to host/port
* - if no results, include domain/5269
* - resolve all host/port combinations
* - return result
*/
_dns_result_srv(NULL, NULL, query);
}
/** responses from the resolver */
void out_resolve(s2s_t s2s, char *domain, xht results, time_t expiry) {
dnscache_t dns;
/* no results, resolve failed */
if(xhash_count(results) == 0) {
dns = xhash_get(s2s->dnscache, domain);
if (dns != NULL) {
/* store negative DNS cache */
xhash_free(dns->results);
dns->query = NULL;
dns->results = NULL;
dns->expiry = expiry;
dns->pending = 0;
}
log_write(s2s->log, LOG_NOTICE, "dns lookup for %s failed", domain);
/* bounce queue */
out_bounce_domain_queues(s2s, domain, stanza_err_REMOTE_SERVER_NOT_FOUND);
xhash_free(results);
return;
}
log_write(s2s->log, LOG_NOTICE, "dns lookup for %s returned %d result%s (ttl %d)",
domain, xhash_count(results), xhash_count(results)!=1?"s":"", expiry - time(NULL));
/* get the cache entry */
dns = xhash_get(s2s->dnscache, domain);
if(dns == NULL) {
/* retry using punycode */
char *punydomain;
if (idna_to_ascii_8z(domain, &punydomain, 0) == IDNA_SUCCESS) {
dns = xhash_get(s2s->dnscache, punydomain);
free(punydomain);
}
}
if(dns == NULL) {
log_write(s2s->log, LOG_ERR, "weird, never requested %s resolution", domain);
return;
}
/* fill it out */
xhash_free(dns->results);
dns->query = NULL;
dns->results = results;
dns->expiry = expiry;
dns->pending = 0;
out_flush_domain_queues(s2s, domain);
/* delete the cache entry if caching is disabled */
if (!s2s->dns_cache_enabled && !dns->pending) {
xhash_free(dns->results);
xhash_zap(s2s->dnscache, domain);
free(dns);
}
}
/** mio callback for outgoing conns */
static int _out_mio_callback(mio_t m, mio_action_t a, mio_fd_t fd, void *data, void *arg) {
conn_t out = (conn_t) arg;
char ipport[INET6_ADDRSTRLEN + 17];
int nbytes;
switch(a) {
case action_READ:
log_debug(ZONE, "read action on fd %d", fd->fd);
/* they did something */
out->last_activity = time(NULL);
ioctl(fd->fd, FIONREAD, &nbytes);
if(nbytes == 0) {
sx_kill(out->s);
return 0;
}
return sx_can_read(out->s);
case action_WRITE:
log_debug(ZONE, "write action on fd %d", fd->fd);
/* update activity timestamp */
out->last_activity = time(NULL);
return sx_can_write(out->s);
case action_CLOSE:
log_debug(ZONE, "close action on fd %d", fd->fd);
jqueue_push(out->s2s->dead, (void *) out->s, 0);
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] disconnect, packets: %i", fd->fd, out->ip, out->port, out->packet_count);
if (out->s2s->out_reuse) {
/* generate the ip/port pair */
snprintf(ipport, INET6_ADDRSTRLEN + 16, "%s/%d", out->ip, out->port);
xhash_zap(out->s2s->out_host, ipport);
}
if (xhash_iter_first(out->routes)) {
char *rkey;
int rkeylen;
char *c;
int c_len;
/* remove all the out_dest entries */
do {
xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL);
c = memchr(rkey, '/', rkeylen);
c++;
c_len = rkeylen - (c - rkey);
log_debug(ZONE, "route '%.*s'", rkeylen, rkey);
if (xhash_getx(out->s2s->out_dest, c, c_len) != NULL) {
log_debug(ZONE, "removing dest entry for '%.*s'", c_len, c);
xhash_zapx(out->s2s->out_dest, c, c_len);
}
} while(xhash_iter_next(out->routes));
}
if (xhash_iter_first(out->routes)) {
char *rkey;
int rkeylen;
jqueue_t q;
int npkt;
/* retry all the routes */
do {
xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL);
q = xhash_getx(out->s2s->outq, rkey, rkeylen);
if (out->s2s->retry_limit > 0 && q != NULL && jqueue_age(q) > out->s2s->retry_limit) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] retry limit reached for '%.*s' queue", fd->fd, out->ip, out->port, rkeylen, rkey);
q = NULL;
}
if (q != NULL && (npkt = jqueue_size(q)) > 0 && xhash_get(out->states, rkey) != (void*) conn_INPROGRESS) {
conn_t retry;
log_debug(ZONE, "retrying connection for '%.*s' queue", rkeylen, rkey);
if (!out_route(out->s2s, rkey, rkeylen, &retry, 0)) {
log_debug(ZONE, "retry successful");
if (retry != NULL) {
/* flush queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
}
} else {
log_debug(ZONE, "retry failed");
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
_out_dns_mark_bad(out);
}
} else {
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_REMOTE_SERVER_TIMEOUT);
_out_dns_mark_bad(out);
}
} while(xhash_iter_next(out->routes));
}
jqueue_push(out->s2s->dead_conn, (void *) out, 0);
case action_ACCEPT:
break;
}
return 0;
}
void send_dialbacks(conn_t out)
{
char *rkey;
int rkeylen;
if (out->s2s->dns_bad_timeout > 0) {
dnsres_t bad = xhash_get(out->s2s->dns_bad, out->key);
if (bad != NULL) {
log_debug(ZONE, "removing bad host entry for '%s'", out->key);
xhash_zap(out->s2s->dns_bad, out->key);
free(bad->key);
free(bad);
}
}
if (xhash_iter_first(out->routes)) {
log_debug(ZONE, "sending dialback packets for %s", out->key);
do {
xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL);
_out_dialback(out, rkey, rkeylen);
} while(xhash_iter_next(out->routes));
}
return;
}
static int _out_sx_callback(sx_t s, sx_event_t e, void *data, void *arg) {
conn_t out = (conn_t) arg;
sx_buf_t buf = (sx_buf_t) data;
int len, ns, elem, starttls = 0;
sx_error_t *sxe;
nad_t nad;
switch(e) {
case event_WANT_READ:
log_debug(ZONE, "want read");
mio_read(out->s2s->mio, out->fd);
break;
case event_WANT_WRITE:
log_debug(ZONE, "want write");
mio_write(out->s2s->mio, out->fd);
break;
case event_READ:
log_debug(ZONE, "reading from %d", out->fd->fd);
/* do the read */
len = recv(out->fd->fd, buf->data, buf->len, 0);
if(len < 0) {
if(MIO_WOULDBLOCK) {
buf->len = 0;
return 0;
}
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] read error: %s (%d)", out->fd->fd, out->ip, out->port, MIO_STRERROR(MIO_ERROR), MIO_ERROR);
if (!out->online) {
_out_dns_mark_bad(out);
}
sx_kill(s);
return -1;
}
else if(len == 0) {
/* they went away */
sx_kill(s);
return -1;
}
log_debug(ZONE, "read %d bytes", len);
buf->len = len;
return len;
case event_WRITE:
log_debug(ZONE, "writing to %d", out->fd->fd);
len = send(out->fd->fd, buf->data, buf->len, 0);
if(len >= 0) {
log_debug(ZONE, "%d bytes written", len);
return len;
}
if(MIO_WOULDBLOCK)
return 0;
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] write error: %s (%d)", out->fd->fd, out->ip, out->port, MIO_STRERROR(MIO_ERROR), MIO_ERROR);
if (!out->online) {
_out_dns_mark_bad(out);
}
sx_kill(s);
return -1;
case event_ERROR:
sxe = (sx_error_t *) data;
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] error: %s (%s)", out->fd->fd, out->ip, out->port, sxe->generic, sxe->specific);
/* mark as bad if we did not manage to connect or there is unrecoverable stream error */
if (!out->online ||
(sxe->code == SX_ERR_STREAM &&
(strstr(sxe->specific, "host-gone") || /* it's not there now */
strstr(sxe->specific, "host-unknown") || /* they do not service the host */
strstr(sxe->specific, "not-authorized") || /* they do not want us there */
strstr(sxe->specific, "see-other-host") || /* we do not support redirections yet */
strstr(sxe->specific, "system-shutdown") || /* they are going down */
strstr(sxe->specific, "policy-violation") || /* they do not want us there */
strstr(sxe->specific, "remote-connection-failed") || /* the required remote entity is gone */
strstr(sxe->specific, "unsupported-encoding") || /* they do not like our encoding */
strstr(sxe->specific, "undefined-condition") || /* something bad happend */
strstr(sxe->specific, "internal-server-error") || /* that server is broken */
strstr(sxe->specific, "unsupported-version") /* they do not support our stream version */
))) {
_out_dns_mark_bad(out);
}
sx_kill(s);
return -1;
case event_OPEN:
log_debug(ZONE, "OPEN event for %s", out->key);
break;
case event_STREAM:
/* check stream version - NULl = pre-xmpp (some jabber1 servers) */
log_debug(ZONE, "STREAM event for %s stream version is %s", out->key, out->s->res_version);
/* first time, bring them online */
if(!out->online) {
log_debug(ZONE, "outgoing conn to %s is online", out->key);
/* if no stream version from either side, kick off dialback for each route, */
/* otherwise wait for stream features */
if (((out->s->res_version==NULL) || (out->s2s->sx_ssl == NULL)) && out->s2s->require_tls == 0) {
log_debug(ZONE, "no stream version, sending dialbacks for %s immediately", out->key);
out->online = 1;
send_dialbacks(out);
} else
log_debug(ZONE, "outgoing conn to %s - waiting for STREAM features", out->key);
}
break;
case event_PACKET:
/* we're counting packets */
out->packet_count++;
out->s2s->packet_count++;
nad = (nad_t) data;
/* watch for the features packet - STARTTLS and/or SASL*/
if ((out->s->res_version!=NULL)
&& NAD_NURI_L(nad, NAD_ENS(nad, 0)) == strlen(uri_STREAMS)
&& strncmp(uri_STREAMS, NAD_NURI(nad, NAD_ENS(nad, 0)), strlen(uri_STREAMS)) == 0
&& NAD_ENAME_L(nad, 0) == 8 && strncmp("features", NAD_ENAME(nad, 0), 8) == 0) {
log_debug(ZONE, "got the stream features packet");
#ifdef HAVE_SSL
/* starttls if we can */
if(out->s2s->sx_ssl != NULL && s->ssf == 0) {
ns = nad_find_scoped_namespace(nad, uri_TLS, NULL);
if(ns >= 0) {
elem = nad_find_elem(nad, 0, ns, "starttls", 1);
if(elem >= 0) {
log_debug(ZONE, "got STARTTLS in stream features");
if(sx_ssl_client_starttls(out->s2s->sx_ssl, s, out->s2s->local_pemfile) == 0) {
starttls = 1;
nad_free(nad);
return 0;
}
log_write(out->s2s->log, LOG_ERR, "unable to establish encrypted session with peer");
}
}
}
/* If we're not establishing a starttls connection, send dialbacks */
if (!starttls) {
if (out->s2s->require_tls == 0 || s->ssf > 0) {
log_debug(ZONE, "No STARTTLS, sending dialbacks for %s", out->key);
out->online = 1;
send_dialbacks(out);
} else {
log_debug(ZONE, "No STARTTLS, dialbacks disabled for non-TLS connections, cannot complete negotiation");
}
}
#else
if (out->s2s->require_tls == 0) {
out->online = 1;
send_dialbacks(out);
}
#endif
}
/* we only accept dialback packets */
if(NAD_ENS(nad, 0) < 0 || NAD_NURI_L(nad, NAD_ENS(nad, 0)) != uri_DIALBACK_L || strncmp(uri_DIALBACK, NAD_NURI(nad, NAD_ENS(nad, 0)), uri_DIALBACK_L) != 0) {
log_debug(ZONE, "got a non-dialback packet on an outgoing conn, dropping it");
nad_free(nad);
return 0;
}
/* and then only result and verify */
if(NAD_ENAME_L(nad, 0) == 6) {
if(strncmp("result", NAD_ENAME(nad, 0), 6) == 0) {
_out_result(out, nad);
return 0;
}
if(strncmp("verify", NAD_ENAME(nad, 0), 6) == 0) {
_out_verify(out, nad);
return 0;
}
}
log_debug(ZONE, "unknown dialback packet, dropping it");
nad_free(nad);
return 0;
case event_CLOSED:
if (out->fd != NULL) {
mio_close(out->s2s->mio, out->fd);
out->fd = NULL;
}
return -1;
}
return 0;
}
/** process incoming auth responses */
static void _out_result(conn_t out, nad_t nad) {
int attr;
jid_t from, to;
char *rkey;
int rkeylen;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db result packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db result packet");
jid_free(from);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
rkeylen = strlen(rkey);
/* key is valid */
if(nad_find_attr(nad, 0, -1, "type", "valid") >= 0 && xhash_get(out->states, rkey) == (void*) conn_INPROGRESS) {
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now valid%s%s", out->fd->fd, out->ip, out->port, rkey, (out->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", out->s->compressed ? ", ZLIB compression enabled" : "");
xhash_put(out->states, pstrdup(xhash_pool(out->states), rkey), (void *) conn_VALID); /* !!! small leak here */
log_debug(ZONE, "%s valid, flushing queue", rkey);
/* flush the queue */
out_flush_route_queue(out->s2s, rkey, rkeylen);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* invalid */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] outgoing route '%s' is now invalid", out->fd->fd, out->ip, out->port, rkey);
/* close connection */
log_write(out->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] closing connection", out->fd->fd, out->ip, out->port);
/* report stream error */
sx_error(out->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the stream */
sx_close(out->s);
/* bounce queue */
out_bounce_route_queue(out->s2s, rkey, rkeylen, stanza_err_SERVICE_UNAVAILABLE);
free(rkey);
jid_free(from);
jid_free(to);
nad_free(nad);
}
/** incoming stream authenticated */
static void _out_verify(conn_t out, nad_t nad) {
int attr, ns;
jid_t from, to;
conn_t in;
char *rkey;
int valid;
attr = nad_find_attr(nad, 0, -1, "from", NULL);
if(attr < 0 || (from = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid from on db verify packet");
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "to", NULL);
if(attr < 0 || (to = jid_new(NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr))) == NULL) {
log_debug(ZONE, "missing or invalid to on db verify packet");
jid_free(from);
nad_free(nad);
return;
}
attr = nad_find_attr(nad, 0, -1, "id", NULL);
if(attr < 0) {
log_debug(ZONE, "missing id on db verify packet");
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
/* get the incoming conn */
in = xhash_getx(out->s2s->in, NAD_AVAL(nad, attr), NAD_AVAL_L(nad, attr));
if(in == NULL) {
log_debug(ZONE, "got a verify for incoming conn %.*s, but it doesn't exist, dropping the packet", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
jid_free(from);
jid_free(to);
nad_free(nad);
return;
}
rkey = s2s_route_key(NULL, to->domain, from->domain);
attr = nad_find_attr(nad, 0, -1, "type", "valid");
if(attr >= 0 && xhash_get(in->states, rkey) == (void*) conn_INPROGRESS) {
xhash_put(in->states, pstrdup(xhash_pool(in->states), rkey), (void *) conn_VALID);
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now valid%s%s", in->fd->fd, in->ip, in->port, rkey, (in->s->flags & SX_SSL_WRAPPER) ? ", TLS negotiated" : "", in->s->compressed ? ", ZLIB compression enabled" : "");
valid = 1;
} else {
log_write(in->s2s->log, LOG_NOTICE, "[%d] [%s, port=%d] incoming route '%s' is now invalid", in->fd->fd, in->ip, in->port, rkey);
valid = 0;
}
free(rkey);
nad_free(nad);
/* decrement outstanding verify counter */
--out->verify;
/* let them know what happened */
nad = nad_new();
ns = nad_add_namespace(nad, uri_DIALBACK, "db");
nad_append_elem(nad, ns, "result", 0);
nad_append_attr(nad, -1, "to", from->domain);
nad_append_attr(nad, -1, "from", to->domain);
nad_append_attr(nad, -1, "type", valid ? "valid" : "invalid");
/* off it goes */
sx_nad_write(in->s, nad);
/* if invalid, close the stream */
if (!valid) {
/* generate stream error */
sx_error(in->s, stream_err_INVALID_ID, "dialback negotiation failed");
/* close the incoming stream */
sx_close(in->s);
}
jid_free(from);
jid_free(to);
}
/* bounce all packets in the queues for domain */
int out_bounce_domain_queues(s2s_t s2s, const char *domain, int err)
{
char *rkey;
int rkeylen;
int pktcount = 0;
if (xhash_iter_first(s2s->outq)) {
do {
xhash_iter_get(s2s->outq, (const char **) &rkey, &rkeylen, NULL);
if(s2s_route_key_match(NULL, (char *) domain, rkey, rkeylen))
pktcount += out_bounce_route_queue(s2s, rkey, rkeylen, err);
} while(xhash_iter_next(s2s->outq));
}
return pktcount;
}
/* bounce all packets in the queue for route */
int out_bounce_route_queue(s2s_t s2s, char *rkey, int rkeylen, int err)
{
jqueue_t q;
pkt_t pkt;
int pktcount = 0;
q = xhash_getx(s2s->outq, rkey, rkeylen);
if(q == NULL)
return 0;
while((pkt = jqueue_pull(q)) != NULL) {
/* only packets with content, in namespace jabber:client and not already errors */
if(pkt->nad->ecur > 1 && NAD_NURI_L(pkt->nad, NAD_ENS(pkt->nad, 1)) == strlen(uri_CLIENT) && strncmp(NAD_NURI(pkt->nad, NAD_ENS(pkt->nad, 1)), uri_CLIENT, strlen(uri_CLIENT)) == 0 && nad_find_attr(pkt->nad, 0, -1, "error", NULL) < 0) {
sx_nad_write(s2s->router, stanza_tofrom(stanza_tofrom(stanza_error(pkt->nad, 1, err), 1), 0));
pktcount++;
}
else
nad_free(pkt->nad);
jid_free(pkt->to);
jid_free(pkt->from);
free(pkt);
}
/* delete queue and remove domain from queue hash */
log_debug(ZONE, "deleting out packet queue for %.*s", rkeylen, rkey);
rkey = q->key;
jqueue_free(q);
xhash_zap(s2s->outq, rkey);
free(rkey);
return pktcount;
}
int out_bounce_conn_queues(conn_t out, int err)
{
char *rkey;
int rkeylen;
int pktcount = 0;
/* bounce queues for all domains handled by this connection - iterate through routes */
if (xhash_iter_first(out->routes)) {
do {
xhash_iter_get(out->routes, (const char **) &rkey, &rkeylen, NULL);
pktcount += out_bounce_route_queue(out->s2s, rkey, rkeylen, err);
} while(xhash_iter_next(out->routes));
}
return pktcount;
}
void out_flush_domain_queues(s2s_t s2s, const char *domain) {
char *rkey;
int rkeylen;
char *c;
int c_len;
if (xhash_iter_first(s2s->outq)) {
do {
xhash_iter_get(s2s->outq, (const char **) &rkey, &rkeylen, NULL);
c = memchr(rkey, '/', rkeylen);
c++;
c_len = rkeylen - (c - rkey);
if (strncmp(domain, c, c_len) == 0)
out_flush_route_queue(s2s, rkey, rkeylen);
} while(xhash_iter_next(s2s->outq));
}
}
void out_flush_route_queue(s2s_t s2s, char *rkey, int rkeylen) {
jqueue_t q;
pkt_t pkt;
int npkt, i, ret;
q = xhash_getx(s2s->outq, rkey, rkeylen);
if(q == NULL)
return;
npkt = jqueue_size(q);
log_debug(ZONE, "flushing %d packets for '%.*s' to out_packet", npkt, rkeylen, rkey);
for(i = 0; i < npkt; i++) {
pkt = jqueue_pull(q);
if(pkt) {
ret = out_packet(s2s, pkt);
if (ret) {
/* uh-oh. the queue was deleted...
q and pkt have been freed
if q->key == rkey, rkey has also been freed */
return;
}
}
}
/* delete queue for route and remove route from queue hash */
if (jqueue_size(q) == 0) {
log_debug(ZONE, "deleting out packet queue for '%.*s'", rkeylen, rkey);
rkey = q->key;
jqueue_free(q);
xhash_zap(s2s->outq, rkey);
free(rkey);
} else {
log_debug(ZONE, "emptied queue gained more packets...");
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3722_0 |
crossvul-cpp_data_good_2891_10 | /* Request a key from userspace
*
* Copyright (C) 2004-2007 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* See Documentation/security/keys/request-key.rst
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kmod.h>
#include <linux/err.h>
#include <linux/keyctl.h>
#include <linux/slab.h>
#include "internal.h"
#define key_negative_timeout 60 /* default timeout on a negative key's existence */
/**
* complete_request_key - Complete the construction of a key.
* @cons: The key construction record.
* @error: The success or failute of the construction.
*
* Complete the attempt to construct a key. The key will be negated
* if an error is indicated. The authorisation key will be revoked
* unconditionally.
*/
void complete_request_key(struct key_construction *cons, int error)
{
kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error);
if (error < 0)
key_negate_and_link(cons->key, key_negative_timeout, NULL,
cons->authkey);
else
key_revoke(cons->authkey);
key_put(cons->key);
key_put(cons->authkey);
kfree(cons);
}
EXPORT_SYMBOL(complete_request_key);
/*
* Initialise a usermode helper that is going to have a specific session
* keyring.
*
* This is called in context of freshly forked kthread before kernel_execve(),
* so we can simply install the desired session_keyring at this point.
*/
static int umh_keys_init(struct subprocess_info *info, struct cred *cred)
{
struct key *keyring = info->data;
return install_session_keyring_to_cred(cred, keyring);
}
/*
* Clean up a usermode helper with session keyring.
*/
static void umh_keys_cleanup(struct subprocess_info *info)
{
struct key *keyring = info->data;
key_put(keyring);
}
/*
* Call a usermode helper with a specific session keyring.
*/
static int call_usermodehelper_keys(const char *path, char **argv, char **envp,
struct key *session_keyring, int wait)
{
struct subprocess_info *info;
info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL,
umh_keys_init, umh_keys_cleanup,
session_keyring);
if (!info)
return -ENOMEM;
key_get(session_keyring);
return call_usermodehelper_exec(info, wait);
}
/*
* Request userspace finish the construction of a key
* - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>"
*/
static int call_sbin_request_key(struct key_construction *cons,
const char *op,
void *aux)
{
static char const request_key[] = "/sbin/request-key";
const struct cred *cred = current_cred();
key_serial_t prkey, sskey;
struct key *key = cons->key, *authkey = cons->authkey, *keyring,
*session;
char *argv[9], *envp[3], uid_str[12], gid_str[12];
char key_str[12], keyring_str[3][12];
char desc[20];
int ret, i;
kenter("{%d},{%d},%s", key->serial, authkey->serial, op);
ret = install_user_keyrings();
if (ret < 0)
goto error_alloc;
/* allocate a new session keyring */
sprintf(desc, "_req.%u", key->serial);
cred = get_current_cred();
keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ,
KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL);
put_cred(cred);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error_alloc;
}
/* attach the auth key to the session keyring */
ret = key_link(keyring, authkey);
if (ret < 0)
goto error_link;
/* record the UID and GID */
sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid));
sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid));
/* we say which key is under construction */
sprintf(key_str, "%d", key->serial);
/* we specify the process's default keyrings */
sprintf(keyring_str[0], "%d",
cred->thread_keyring ? cred->thread_keyring->serial : 0);
prkey = 0;
if (cred->process_keyring)
prkey = cred->process_keyring->serial;
sprintf(keyring_str[1], "%d", prkey);
rcu_read_lock();
session = rcu_dereference(cred->session_keyring);
if (!session)
session = cred->user->session_keyring;
sskey = session->serial;
rcu_read_unlock();
sprintf(keyring_str[2], "%d", sskey);
/* set up a minimal environment */
i = 0;
envp[i++] = "HOME=/";
envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
envp[i] = NULL;
/* set up the argument list */
i = 0;
argv[i++] = (char *)request_key;
argv[i++] = (char *) op;
argv[i++] = key_str;
argv[i++] = uid_str;
argv[i++] = gid_str;
argv[i++] = keyring_str[0];
argv[i++] = keyring_str[1];
argv[i++] = keyring_str[2];
argv[i] = NULL;
/* do it */
ret = call_usermodehelper_keys(request_key, argv, envp, keyring,
UMH_WAIT_PROC);
kdebug("usermode -> 0x%x", ret);
if (ret >= 0) {
/* ret is the exit/wait code */
if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) ||
key_validate(key) < 0)
ret = -ENOKEY;
else
/* ignore any errors from userspace if the key was
* instantiated */
ret = 0;
}
error_link:
key_put(keyring);
error_alloc:
complete_request_key(cons, ret);
kleave(" = %d", ret);
return ret;
}
/*
* Call out to userspace for key construction.
*
* Program failure is ignored in favour of key status.
*/
static int construct_key(struct key *key, const void *callout_info,
size_t callout_len, void *aux,
struct key *dest_keyring)
{
struct key_construction *cons;
request_key_actor_t actor;
struct key *authkey;
int ret;
kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux);
cons = kmalloc(sizeof(*cons), GFP_KERNEL);
if (!cons)
return -ENOMEM;
/* allocate an authorisation key */
authkey = request_key_auth_new(key, callout_info, callout_len,
dest_keyring);
if (IS_ERR(authkey)) {
kfree(cons);
ret = PTR_ERR(authkey);
authkey = NULL;
} else {
cons->authkey = key_get(authkey);
cons->key = key_get(key);
/* make the call */
actor = call_sbin_request_key;
if (key->type->request_key)
actor = key->type->request_key;
ret = actor(cons, "create", aux);
/* check that the actor called complete_request_key() prior to
* returning an error */
WARN_ON(ret < 0 &&
!test_bit(KEY_FLAG_REVOKED, &authkey->flags));
key_put(authkey);
}
kleave(" = %d", ret);
return ret;
}
/*
* Get the appropriate destination keyring for the request.
*
* The keyring selected is returned with an extra reference upon it which the
* caller must release.
*/
static void construct_get_dest_keyring(struct key **_dest_keyring)
{
struct request_key_auth *rka;
const struct cred *cred = current_cred();
struct key *dest_keyring = *_dest_keyring, *authkey;
kenter("%p", dest_keyring);
/* find the appropriate keyring */
if (dest_keyring) {
/* the caller supplied one */
key_get(dest_keyring);
} else {
/* use a default keyring; falling through the cases until we
* find one that we actually have */
switch (cred->jit_keyring) {
case KEY_REQKEY_DEFL_DEFAULT:
case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
if (cred->request_key_auth) {
authkey = cred->request_key_auth;
down_read(&authkey->sem);
rka = authkey->payload.data[0];
if (!test_bit(KEY_FLAG_REVOKED,
&authkey->flags))
dest_keyring =
key_get(rka->dest_keyring);
up_read(&authkey->sem);
if (dest_keyring)
break;
}
case KEY_REQKEY_DEFL_THREAD_KEYRING:
dest_keyring = key_get(cred->thread_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_PROCESS_KEYRING:
dest_keyring = key_get(cred->process_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_SESSION_KEYRING:
rcu_read_lock();
dest_keyring = key_get(
rcu_dereference(cred->session_keyring));
rcu_read_unlock();
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
dest_keyring =
key_get(cred->user->session_keyring);
break;
case KEY_REQKEY_DEFL_USER_KEYRING:
dest_keyring = key_get(cred->user->uid_keyring);
break;
case KEY_REQKEY_DEFL_GROUP_KEYRING:
default:
BUG();
}
}
*_dest_keyring = dest_keyring;
kleave(" [dk %d]", key_serial(dest_keyring));
return;
}
/*
* Allocate a new key in under-construction state and attempt to link it in to
* the requested keyring.
*
* May return a key that's already under construction instead if there was a
* race between two thread calling request_key().
*/
static int construct_alloc_key(struct keyring_search_context *ctx,
struct key *dest_keyring,
unsigned long flags,
struct key_user *user,
struct key **_key)
{
struct assoc_array_edit *edit;
struct key *key;
key_perm_t perm;
key_ref_t key_ref;
int ret;
kenter("%s,%s,,,",
ctx->index_key.type->name, ctx->index_key.description);
*_key = NULL;
mutex_lock(&user->cons_lock);
perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;
perm |= KEY_USR_VIEW;
if (ctx->index_key.type->read)
perm |= KEY_POS_READ;
if (ctx->index_key.type == &key_type_keyring ||
ctx->index_key.type->update)
perm |= KEY_POS_WRITE;
key = key_alloc(ctx->index_key.type, ctx->index_key.description,
ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred,
perm, flags, NULL);
if (IS_ERR(key))
goto alloc_failed;
set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags);
if (dest_keyring) {
ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit);
if (ret < 0)
goto link_prealloc_failed;
}
/* attach the key to the destination keyring under lock, but we do need
* to do another check just in case someone beat us to it whilst we
* waited for locks */
mutex_lock(&key_construction_mutex);
key_ref = search_process_keyrings(ctx);
if (!IS_ERR(key_ref))
goto key_already_present;
if (dest_keyring)
__key_link(key, &edit);
mutex_unlock(&key_construction_mutex);
if (dest_keyring)
__key_link_end(dest_keyring, &ctx->index_key, edit);
mutex_unlock(&user->cons_lock);
*_key = key;
kleave(" = 0 [%d]", key_serial(key));
return 0;
/* the key is now present - we tell the caller that we found it by
* returning -EINPROGRESS */
key_already_present:
key_put(key);
mutex_unlock(&key_construction_mutex);
key = key_ref_to_ptr(key_ref);
if (dest_keyring) {
ret = __key_link_check_live_key(dest_keyring, key);
if (ret == 0)
__key_link(key, &edit);
__key_link_end(dest_keyring, &ctx->index_key, edit);
if (ret < 0)
goto link_check_failed;
}
mutex_unlock(&user->cons_lock);
*_key = key;
kleave(" = -EINPROGRESS [%d]", key_serial(key));
return -EINPROGRESS;
link_check_failed:
mutex_unlock(&user->cons_lock);
key_put(key);
kleave(" = %d [linkcheck]", ret);
return ret;
link_prealloc_failed:
mutex_unlock(&user->cons_lock);
key_put(key);
kleave(" = %d [prelink]", ret);
return ret;
alloc_failed:
mutex_unlock(&user->cons_lock);
kleave(" = %ld", PTR_ERR(key));
return PTR_ERR(key);
}
/*
* Commence key construction.
*/
static struct key *construct_key_and_link(struct keyring_search_context *ctx,
const char *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct key_user *user;
struct key *key;
int ret;
kenter("");
if (ctx->index_key.type == &key_type_keyring)
return ERR_PTR(-EPERM);
user = key_user_lookup(current_fsuid());
if (!user)
return ERR_PTR(-ENOMEM);
construct_get_dest_keyring(&dest_keyring);
ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
key_user_put(user);
if (ret == 0) {
ret = construct_key(key, callout_info, callout_len, aux,
dest_keyring);
if (ret < 0) {
kdebug("cons failed");
goto construction_failed;
}
} else if (ret == -EINPROGRESS) {
ret = 0;
} else {
goto couldnt_alloc_key;
}
key_put(dest_keyring);
kleave(" = key %d", key_serial(key));
return key;
construction_failed:
key_negate_and_link(key, key_negative_timeout, NULL, NULL);
key_put(key);
couldnt_alloc_key:
key_put(dest_keyring);
kleave(" = %d", ret);
return ERR_PTR(ret);
}
/**
* request_key_and_link - Request a key and cache it in a keyring.
* @type: The type of key we want.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
* @aux: Auxiliary data for the upcall.
* @dest_keyring: Where to cache the key.
* @flags: Flags to key_alloc().
*
* A key matching the specified criteria is searched for in the process's
* keyrings and returned with its usage count incremented if found. Otherwise,
* if callout_info is not NULL, a key will be allocated and some service
* (probably in userspace) will be asked to instantiate it.
*
* If successfully found or created, the key will be linked to the destination
* keyring if one is provided.
*
* Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED
* or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was
* found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT
* if insufficient key quota was available to create a new key; or -ENOMEM if
* insufficient memory was available.
*
* If the returned key was created, then it may still be under construction,
* and wait_for_key_construction() should be used to wait for that to complete.
*/
struct key *request_key_and_link(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len,
void *aux,
struct key *dest_keyring,
unsigned long flags)
{
struct keyring_search_context ctx = {
.index_key.type = type,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = key_default_cmp,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = (KEYRING_SEARCH_DO_STATE_CHECK |
KEYRING_SEARCH_SKIP_EXPIRED),
};
struct key *key;
key_ref_t key_ref;
int ret;
kenter("%s,%s,%p,%zu,%p,%p,%lx",
ctx.index_key.type->name, ctx.index_key.description,
callout_info, callout_len, aux, dest_keyring, flags);
if (type->match_preparse) {
ret = type->match_preparse(&ctx.match_data);
if (ret < 0) {
key = ERR_PTR(ret);
goto error;
}
}
/* search all the process keyrings for a key */
key_ref = search_process_keyrings(&ctx);
if (!IS_ERR(key_ref)) {
key = key_ref_to_ptr(key_ref);
if (dest_keyring) {
construct_get_dest_keyring(&dest_keyring);
ret = key_link(dest_keyring, key);
key_put(dest_keyring);
if (ret < 0) {
key_put(key);
key = ERR_PTR(ret);
goto error_free;
}
}
} else if (PTR_ERR(key_ref) != -EAGAIN) {
key = ERR_CAST(key_ref);
} else {
/* the search failed, but the keyrings were searchable, so we
* should consult userspace if we can */
key = ERR_PTR(-ENOKEY);
if (!callout_info)
goto error_free;
key = construct_key_and_link(&ctx, callout_info, callout_len,
aux, dest_keyring, flags);
}
error_free:
if (type->match_free)
type->match_free(&ctx.match_data);
error:
kleave(" = %p", key);
return key;
}
/**
* wait_for_key_construction - Wait for construction of a key to complete
* @key: The key being waited for.
* @intr: Whether to wait interruptibly.
*
* Wait for a key to finish being constructed.
*
* Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY
* if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was
* revoked or expired.
*/
int wait_for_key_construction(struct key *key, bool intr)
{
int ret;
ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT,
intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE);
if (ret)
return -ERESTARTSYS;
ret = key_read_state(key);
if (ret < 0)
return ret;
return key_validate(key);
}
EXPORT_SYMBOL(wait_for_key_construction);
/**
* request_key - Request a key and wait for construction
* @type: Type of key.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found, new keys are always allocated in the user's quota,
* the callout_info must be a NUL-terminated string and no auxiliary data can
* be passed.
*
* Furthermore, it then works as wait_for_key_construction() to wait for the
* completion of keys undergoing construction with a non-interruptible wait.
*/
struct key *request_key(struct key_type *type,
const char *description,
const char *callout_info)
{
struct key *key;
size_t callout_len = 0;
int ret;
if (callout_info)
callout_len = strlen(callout_info);
key = request_key_and_link(type, description, callout_info, callout_len,
NULL, NULL, KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key)) {
ret = wait_for_key_construction(key, false);
if (ret < 0) {
key_put(key);
return ERR_PTR(ret);
}
}
return key;
}
EXPORT_SYMBOL(request_key);
/**
* request_key_with_auxdata - Request a key with auxiliary data for the upcaller
* @type: The type of key we want.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
* @aux: Auxiliary data for the upcall.
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found and new keys are always allocated in the user's quota.
*
* Furthermore, it then works as wait_for_key_construction() to wait for the
* completion of keys undergoing construction with a non-interruptible wait.
*/
struct key *request_key_with_auxdata(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len,
void *aux)
{
struct key *key;
int ret;
key = request_key_and_link(type, description, callout_info, callout_len,
aux, NULL, KEY_ALLOC_IN_QUOTA);
if (!IS_ERR(key)) {
ret = wait_for_key_construction(key, false);
if (ret < 0) {
key_put(key);
return ERR_PTR(ret);
}
}
return key;
}
EXPORT_SYMBOL(request_key_with_auxdata);
/*
* request_key_async - Request a key (allow async construction)
* @type: Type of key.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found, new keys are always allocated in the user's quota and
* no auxiliary data can be passed.
*
* The caller should call wait_for_key_construction() to wait for the
* completion of the returned key if it is still undergoing construction.
*/
struct key *request_key_async(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len)
{
return request_key_and_link(type, description, callout_info,
callout_len, NULL, NULL,
KEY_ALLOC_IN_QUOTA);
}
EXPORT_SYMBOL(request_key_async);
/*
* request a key with auxiliary data for the upcaller (allow async construction)
* @type: Type of key.
* @description: The searchable description of the key.
* @callout_info: The data to pass to the instantiation upcall (or NULL).
* @callout_len: The length of callout_info.
* @aux: Auxiliary data for the upcall.
*
* As for request_key_and_link() except that it does not add the returned key
* to a keyring if found and new keys are always allocated in the user's quota.
*
* The caller should call wait_for_key_construction() to wait for the
* completion of the returned key if it is still undergoing construction.
*/
struct key *request_key_async_with_auxdata(struct key_type *type,
const char *description,
const void *callout_info,
size_t callout_len,
void *aux)
{
return request_key_and_link(type, description, callout_info,
callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA);
}
EXPORT_SYMBOL(request_key_async_with_auxdata);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_10 |
crossvul-cpp_data_bad_5823_0 | /*
* JPEG 2000 image decoder
* Copyright (c) 2007 Kamil Nowosad
* Copyright (c) 2013 Nicolas Bertrand <nicoinattendu@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* JPEG 2000 image decoder
*/
#include "libavutil/avassert.h"
#include "libavutil/common.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "avcodec.h"
#include "bytestream.h"
#include "internal.h"
#include "thread.h"
#include "jpeg2000.h"
#define JP2_SIG_TYPE 0x6A502020
#define JP2_SIG_VALUE 0x0D0A870A
#define JP2_CODESTREAM 0x6A703263
#define JP2_HEADER 0x6A703268
#define HAD_COC 0x01
#define HAD_QCC 0x02
typedef struct Jpeg2000TilePart {
uint8_t tile_index; // Tile index who refers the tile-part
const uint8_t *tp_end;
GetByteContext tpg; // bit stream in tile-part
} Jpeg2000TilePart;
/* RMK: For JPEG2000 DCINEMA 3 tile-parts in a tile
* one per component, so tile_part elements have a size of 3 */
typedef struct Jpeg2000Tile {
Jpeg2000Component *comp;
uint8_t properties[4];
Jpeg2000CodingStyle codsty[4];
Jpeg2000QuantStyle qntsty[4];
Jpeg2000TilePart tile_part[4];
uint16_t tp_idx; // Tile-part index
} Jpeg2000Tile;
typedef struct Jpeg2000DecoderContext {
AVClass *class;
AVCodecContext *avctx;
GetByteContext g;
int width, height;
int image_offset_x, image_offset_y;
int tile_offset_x, tile_offset_y;
uint8_t cbps[4]; // bits per sample in particular components
uint8_t sgnd[4]; // if a component is signed
uint8_t properties[4];
int cdx[4], cdy[4];
int precision;
int ncomponents;
int colour_space;
uint32_t palette[256];
int8_t pal8;
int cdef[4];
int tile_width, tile_height;
unsigned numXtiles, numYtiles;
int maxtilelen;
Jpeg2000CodingStyle codsty[4];
Jpeg2000QuantStyle qntsty[4];
int bit_index;
int curtileno;
Jpeg2000Tile *tile;
/*options parameters*/
int reduction_factor;
} Jpeg2000DecoderContext;
/* get_bits functions for JPEG2000 packet bitstream
* It is a get_bit function with a bit-stuffing routine. If the value of the
* byte is 0xFF, the next byte includes an extra zero bit stuffed into the MSB.
* cf. ISO-15444-1:2002 / B.10.1 Bit-stuffing routine */
static int get_bits(Jpeg2000DecoderContext *s, int n)
{
int res = 0;
while (--n >= 0) {
res <<= 1;
if (s->bit_index == 0) {
s->bit_index = 7 + (bytestream2_get_byte(&s->g) != 0xFFu);
}
s->bit_index--;
res |= (bytestream2_peek_byte(&s->g) >> s->bit_index) & 1;
}
return res;
}
static void jpeg2000_flush(Jpeg2000DecoderContext *s)
{
if (bytestream2_get_byte(&s->g) == 0xff)
bytestream2_skip(&s->g, 1);
s->bit_index = 8;
}
/* decode the value stored in node */
static int tag_tree_decode(Jpeg2000DecoderContext *s, Jpeg2000TgtNode *node,
int threshold)
{
Jpeg2000TgtNode *stack[30];
int sp = -1, curval = 0;
if (!node)
return AVERROR_INVALIDDATA;
while (node && !node->vis) {
stack[++sp] = node;
node = node->parent;
}
if (node)
curval = node->val;
else
curval = stack[sp]->val;
while (curval < threshold && sp >= 0) {
if (curval < stack[sp]->val)
curval = stack[sp]->val;
while (curval < threshold) {
int ret;
if ((ret = get_bits(s, 1)) > 0) {
stack[sp]->vis++;
break;
} else if (!ret)
curval++;
else
return ret;
}
stack[sp]->val = curval;
sp--;
}
return curval;
}
static int pix_fmt_match(enum AVPixelFormat pix_fmt, int components,
int bpc, uint32_t log2_chroma_wh, int pal8)
{
int match = 1;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt);
if (desc->nb_components != components) {
return 0;
}
switch (components) {
case 4:
match = match && desc->comp[3].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 14 & 3) == 0 &&
(log2_chroma_wh >> 12 & 3) == 0;
case 3:
match = match && desc->comp[2].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 10 & 3) == desc->log2_chroma_w &&
(log2_chroma_wh >> 8 & 3) == desc->log2_chroma_h;
case 2:
match = match && desc->comp[1].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 6 & 3) == desc->log2_chroma_w &&
(log2_chroma_wh >> 4 & 3) == desc->log2_chroma_h;
case 1:
match = match && desc->comp[0].depth_minus1 + 1 >= bpc &&
(log2_chroma_wh >> 2 & 3) == 0 &&
(log2_chroma_wh & 3) == 0 &&
(desc->flags & AV_PIX_FMT_FLAG_PAL) == pal8 * AV_PIX_FMT_FLAG_PAL;
}
return match;
}
// pix_fmts with lower bpp have to be listed before
// similar pix_fmts with higher bpp.
#define RGB_PIXEL_FORMATS AV_PIX_FMT_PAL8,AV_PIX_FMT_RGB24,AV_PIX_FMT_RGBA,AV_PIX_FMT_RGB48,AV_PIX_FMT_RGBA64
#define GRAY_PIXEL_FORMATS AV_PIX_FMT_GRAY8,AV_PIX_FMT_GRAY8A,AV_PIX_FMT_GRAY16
#define YUV_PIXEL_FORMATS AV_PIX_FMT_YUV410P,AV_PIX_FMT_YUV411P,AV_PIX_FMT_YUVA420P, \
AV_PIX_FMT_YUV420P,AV_PIX_FMT_YUV422P,AV_PIX_FMT_YUVA422P, \
AV_PIX_FMT_YUV440P,AV_PIX_FMT_YUV444P,AV_PIX_FMT_YUVA444P, \
AV_PIX_FMT_YUV420P9,AV_PIX_FMT_YUV422P9,AV_PIX_FMT_YUV444P9, \
AV_PIX_FMT_YUVA420P9,AV_PIX_FMT_YUVA422P9,AV_PIX_FMT_YUVA444P9, \
AV_PIX_FMT_YUV420P10,AV_PIX_FMT_YUV422P10,AV_PIX_FMT_YUV444P10, \
AV_PIX_FMT_YUVA420P10,AV_PIX_FMT_YUVA422P10,AV_PIX_FMT_YUVA444P10, \
AV_PIX_FMT_YUV420P12,AV_PIX_FMT_YUV422P12,AV_PIX_FMT_YUV444P12, \
AV_PIX_FMT_YUV420P14,AV_PIX_FMT_YUV422P14,AV_PIX_FMT_YUV444P14, \
AV_PIX_FMT_YUV420P16,AV_PIX_FMT_YUV422P16,AV_PIX_FMT_YUV444P16, \
AV_PIX_FMT_YUVA420P16,AV_PIX_FMT_YUVA422P16,AV_PIX_FMT_YUVA444P16
#define XYZ_PIXEL_FORMATS AV_PIX_FMT_XYZ12
static const enum AVPixelFormat rgb_pix_fmts[] = {RGB_PIXEL_FORMATS};
static const enum AVPixelFormat gray_pix_fmts[] = {GRAY_PIXEL_FORMATS};
static const enum AVPixelFormat yuv_pix_fmts[] = {YUV_PIXEL_FORMATS};
static const enum AVPixelFormat xyz_pix_fmts[] = {XYZ_PIXEL_FORMATS};
static const enum AVPixelFormat all_pix_fmts[] = {RGB_PIXEL_FORMATS,
GRAY_PIXEL_FORMATS,
YUV_PIXEL_FORMATS,
XYZ_PIXEL_FORMATS};
/* marker segments */
/* get sizes and offsets of image, tiles; number of components */
static int get_siz(Jpeg2000DecoderContext *s)
{
int i;
int ncomponents;
uint32_t log2_chroma_wh = 0;
const enum AVPixelFormat *possible_fmts = NULL;
int possible_fmts_nb = 0;
if (bytestream2_get_bytes_left(&s->g) < 36)
return AVERROR_INVALIDDATA;
s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
s->width = bytestream2_get_be32u(&s->g); // Width
s->height = bytestream2_get_be32u(&s->g); // Height
s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
ncomponents = bytestream2_get_be16u(&s->g); // CSiz
if (ncomponents <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
s->ncomponents);
return AVERROR_INVALIDDATA;
}
if (ncomponents > 4) {
avpriv_request_sample(s->avctx, "Support for %d components",
s->ncomponents);
return AVERROR_PATCHWELCOME;
}
s->ncomponents = ncomponents;
if (s->tile_width <= 0 || s->tile_height <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
s->tile_width, s->tile_height);
return AVERROR_INVALIDDATA;
}
if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
return AVERROR_INVALIDDATA;
for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
uint8_t x = bytestream2_get_byteu(&s->g);
s->cbps[i] = (x & 0x7f) + 1;
s->precision = FFMAX(s->cbps[i], s->precision);
s->sgnd[i] = !!(x & 0x80);
s->cdx[i] = bytestream2_get_byteu(&s->g);
s->cdy[i] = bytestream2_get_byteu(&s->g);
if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
|| !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
return AVERROR_INVALIDDATA;
}
log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
}
s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(EINVAL);
}
s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
if (!s->tile) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
Jpeg2000Tile *tile = s->tile + i;
tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
if (!tile->comp)
return AVERROR(ENOMEM);
}
/* compute image size with reduction factor */
s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
s->reduction_factor);
s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
s->reduction_factor);
if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
possible_fmts = xyz_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
} else {
switch (s->colour_space) {
case 16:
possible_fmts = rgb_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
break;
case 17:
possible_fmts = gray_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
break;
case 18:
possible_fmts = yuv_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
break;
default:
possible_fmts = all_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
break;
}
}
for (i = 0; i < possible_fmts_nb; ++i) {
if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
s->avctx->pix_fmt = possible_fmts[i];
break;
}
}
if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown pix_fmt, profile: %d, colour_space: %d, "
"components: %d, precision: %d, "
"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
s->avctx->profile, s->colour_space, ncomponents, s->precision,
ncomponents > 2 ? s->cdx[1] : 0,
ncomponents > 2 ? s->cdy[1] : 0,
ncomponents > 2 ? s->cdx[2] : 0,
ncomponents > 2 ? s->cdy[2] : 0);
}
s->avctx->bits_per_raw_sample = s->precision;
return 0;
}
/* get common part for COD and COC segments */
static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c)
{
uint8_t byte;
if (bytestream2_get_bytes_left(&s->g) < 5)
return AVERROR_INVALIDDATA;
/* nreslevels = number of resolution levels
= number of decomposition level +1 */
c->nreslevels = bytestream2_get_byteu(&s->g) + 1;
if (c->nreslevels >= JPEG2000_MAX_RESLEVELS) {
av_log(s->avctx, AV_LOG_ERROR, "nreslevels %d is invalid\n", c->nreslevels);
return AVERROR_INVALIDDATA;
}
/* compute number of resolution levels to decode */
if (c->nreslevels < s->reduction_factor)
c->nreslevels2decode = 1;
else
c->nreslevels2decode = c->nreslevels - s->reduction_factor;
c->log2_cblk_width = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk width
c->log2_cblk_height = (bytestream2_get_byteu(&s->g) & 15) + 2; // cblk height
if (c->log2_cblk_width > 10 || c->log2_cblk_height > 10 ||
c->log2_cblk_width + c->log2_cblk_height > 12) {
av_log(s->avctx, AV_LOG_ERROR, "cblk size invalid\n");
return AVERROR_INVALIDDATA;
}
if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) {
avpriv_request_sample(s->avctx, "cblk size > 64");
return AVERROR_PATCHWELCOME;
}
c->cblk_style = bytestream2_get_byteu(&s->g);
if (c->cblk_style != 0) { // cblk style
av_log(s->avctx, AV_LOG_WARNING, "extra cblk styles %X\n", c->cblk_style);
}
c->transform = bytestream2_get_byteu(&s->g); // DWT transformation type
/* set integer 9/7 DWT in case of BITEXACT flag */
if ((s->avctx->flags & CODEC_FLAG_BITEXACT) && (c->transform == FF_DWT97))
c->transform = FF_DWT97_INT;
if (c->csty & JPEG2000_CSTY_PREC) {
int i;
for (i = 0; i < c->nreslevels; i++) {
byte = bytestream2_get_byte(&s->g);
c->log2_prec_widths[i] = byte & 0x0F; // precinct PPx
c->log2_prec_heights[i] = (byte >> 4) & 0x0F; // precinct PPy
}
} else {
memset(c->log2_prec_widths , 15, sizeof(c->log2_prec_widths ));
memset(c->log2_prec_heights, 15, sizeof(c->log2_prec_heights));
}
return 0;
}
/* get coding parameters for a particular tile or whole image*/
static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
uint8_t *properties)
{
Jpeg2000CodingStyle tmp;
int compno, ret;
if (bytestream2_get_bytes_left(&s->g) < 5)
return AVERROR_INVALIDDATA;
tmp.csty = bytestream2_get_byteu(&s->g);
// get progression order
tmp.prog_order = bytestream2_get_byteu(&s->g);
tmp.nlayers = bytestream2_get_be16u(&s->g);
tmp.mct = bytestream2_get_byteu(&s->g); // multiple component transformation
if (tmp.mct && s->ncomponents < 3) {
av_log(s->avctx, AV_LOG_ERROR,
"MCT %d with too few components (%d)\n",
tmp.mct, s->ncomponents);
return AVERROR_INVALIDDATA;
}
if ((ret = get_cox(s, &tmp)) < 0)
return ret;
for (compno = 0; compno < s->ncomponents; compno++)
if (!(properties[compno] & HAD_COC))
memcpy(c + compno, &tmp, sizeof(tmp));
return 0;
}
/* Get coding parameters for a component in the whole image or a
* particular tile. */
static int get_coc(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,
uint8_t *properties)
{
int compno, ret;
if (bytestream2_get_bytes_left(&s->g) < 2)
return AVERROR_INVALIDDATA;
compno = bytestream2_get_byteu(&s->g);
if (compno >= s->ncomponents) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid compno %d. There are %d components in the image.\n",
compno, s->ncomponents);
return AVERROR_INVALIDDATA;
}
c += compno;
c->csty = bytestream2_get_byteu(&s->g);
if ((ret = get_cox(s, c)) < 0)
return ret;
properties[compno] |= HAD_COC;
return 0;
}
/* Get common part for QCD and QCC segments. */
static int get_qcx(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q)
{
int i, x;
if (bytestream2_get_bytes_left(&s->g) < 1)
return AVERROR_INVALIDDATA;
x = bytestream2_get_byteu(&s->g); // Sqcd
q->nguardbits = x >> 5;
q->quantsty = x & 0x1f;
if (q->quantsty == JPEG2000_QSTY_NONE) {
n -= 3;
if (bytestream2_get_bytes_left(&s->g) < n ||
n > JPEG2000_MAX_DECLEVELS*3)
return AVERROR_INVALIDDATA;
for (i = 0; i < n; i++)
q->expn[i] = bytestream2_get_byteu(&s->g) >> 3;
} else if (q->quantsty == JPEG2000_QSTY_SI) {
if (bytestream2_get_bytes_left(&s->g) < 2)
return AVERROR_INVALIDDATA;
x = bytestream2_get_be16u(&s->g);
q->expn[0] = x >> 11;
q->mant[0] = x & 0x7ff;
for (i = 1; i < JPEG2000_MAX_DECLEVELS * 3; i++) {
int curexpn = FFMAX(0, q->expn[0] - (i - 1) / 3);
q->expn[i] = curexpn;
q->mant[i] = q->mant[0];
}
} else {
n = (n - 3) >> 1;
if (bytestream2_get_bytes_left(&s->g) < 2 * n ||
n > JPEG2000_MAX_DECLEVELS*3)
return AVERROR_INVALIDDATA;
for (i = 0; i < n; i++) {
x = bytestream2_get_be16u(&s->g);
q->expn[i] = x >> 11;
q->mant[i] = x & 0x7ff;
}
}
return 0;
}
/* Get quantization parameters for a particular tile or a whole image. */
static int get_qcd(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
uint8_t *properties)
{
Jpeg2000QuantStyle tmp;
int compno, ret;
if ((ret = get_qcx(s, n, &tmp)) < 0)
return ret;
for (compno = 0; compno < s->ncomponents; compno++)
if (!(properties[compno] & HAD_QCC))
memcpy(q + compno, &tmp, sizeof(tmp));
return 0;
}
/* Get quantization parameters for a component in the whole image
* on in a particular tile. */
static int get_qcc(Jpeg2000DecoderContext *s, int n, Jpeg2000QuantStyle *q,
uint8_t *properties)
{
int compno;
if (bytestream2_get_bytes_left(&s->g) < 1)
return AVERROR_INVALIDDATA;
compno = bytestream2_get_byteu(&s->g);
if (compno >= s->ncomponents) {
av_log(s->avctx, AV_LOG_ERROR,
"Invalid compno %d. There are %d components in the image.\n",
compno, s->ncomponents);
return AVERROR_INVALIDDATA;
}
properties[compno] |= HAD_QCC;
return get_qcx(s, n - 1, q + compno);
}
/* Get start of tile segment. */
static int get_sot(Jpeg2000DecoderContext *s, int n)
{
Jpeg2000TilePart *tp;
uint16_t Isot;
uint32_t Psot;
uint8_t TPsot;
if (bytestream2_get_bytes_left(&s->g) < 8)
return AVERROR_INVALIDDATA;
s->curtileno = 0;
Isot = bytestream2_get_be16u(&s->g); // Isot
if (Isot >= s->numXtiles * s->numYtiles)
return AVERROR_INVALIDDATA;
s->curtileno = Isot;
Psot = bytestream2_get_be32u(&s->g); // Psot
TPsot = bytestream2_get_byteu(&s->g); // TPsot
/* Read TNSot but not used */
bytestream2_get_byteu(&s->g); // TNsot
if (Psot > bytestream2_get_bytes_left(&s->g) + n + 2) {
av_log(s->avctx, AV_LOG_ERROR, "Psot %d too big\n", Psot);
return AVERROR_INVALIDDATA;
}
if (TPsot >= FF_ARRAY_ELEMS(s->tile[Isot].tile_part)) {
avpriv_request_sample(s->avctx, "Support for %d components", TPsot);
return AVERROR_PATCHWELCOME;
}
s->tile[Isot].tp_idx = TPsot;
tp = s->tile[Isot].tile_part + TPsot;
tp->tile_index = Isot;
tp->tp_end = s->g.buffer + Psot - n - 2;
if (!TPsot) {
Jpeg2000Tile *tile = s->tile + s->curtileno;
/* copy defaults */
memcpy(tile->codsty, s->codsty, s->ncomponents * sizeof(Jpeg2000CodingStyle));
memcpy(tile->qntsty, s->qntsty, s->ncomponents * sizeof(Jpeg2000QuantStyle));
}
return 0;
}
/* Tile-part lengths: see ISO 15444-1:2002, section A.7.1
* Used to know the number of tile parts and lengths.
* There may be multiple TLMs in the header.
* TODO: The function is not used for tile-parts management, nor anywhere else.
* It can be useful to allocate memory for tile parts, before managing the SOT
* markers. Parsing the TLM header is needed to increment the input header
* buffer.
* This marker is mandatory for DCI. */
static uint8_t get_tlm(Jpeg2000DecoderContext *s, int n)
{
uint8_t Stlm, ST, SP, tile_tlm, i;
bytestream2_get_byte(&s->g); /* Ztlm: skipped */
Stlm = bytestream2_get_byte(&s->g);
// too complex ? ST = ((Stlm >> 4) & 0x01) + ((Stlm >> 4) & 0x02);
ST = (Stlm >> 4) & 0x03;
// TODO: Manage case of ST = 0b11 --> raise error
SP = (Stlm >> 6) & 0x01;
tile_tlm = (n - 4) / ((SP + 1) * 2 + ST);
for (i = 0; i < tile_tlm; i++) {
switch (ST) {
case 0:
break;
case 1:
bytestream2_get_byte(&s->g);
break;
case 2:
bytestream2_get_be16(&s->g);
break;
case 3:
bytestream2_get_be32(&s->g);
break;
}
if (SP == 0) {
bytestream2_get_be16(&s->g);
} else {
bytestream2_get_be32(&s->g);
}
}
return 0;
}
static int init_tile(Jpeg2000DecoderContext *s, int tileno)
{
int compno;
int tilex = tileno % s->numXtiles;
int tiley = tileno / s->numXtiles;
Jpeg2000Tile *tile = s->tile + tileno;
if (!tile->comp)
return AVERROR(ENOMEM);
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
int ret; // global bandno
comp->coord_o[0][0] = FFMAX(tilex * s->tile_width + s->tile_offset_x, s->image_offset_x);
comp->coord_o[0][1] = FFMIN((tilex + 1) * s->tile_width + s->tile_offset_x, s->width);
comp->coord_o[1][0] = FFMAX(tiley * s->tile_height + s->tile_offset_y, s->image_offset_y);
comp->coord_o[1][1] = FFMIN((tiley + 1) * s->tile_height + s->tile_offset_y, s->height);
comp->coord[0][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][0], s->reduction_factor);
comp->coord[0][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[0][1], s->reduction_factor);
comp->coord[1][0] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][0], s->reduction_factor);
comp->coord[1][1] = ff_jpeg2000_ceildivpow2(comp->coord_o[1][1], s->reduction_factor);
if (ret = ff_jpeg2000_init_component(comp, codsty, qntsty,
s->cbps[compno], s->cdx[compno],
s->cdy[compno], s->avctx))
return ret;
}
return 0;
}
/* Read the number of coding passes. */
static int getnpasses(Jpeg2000DecoderContext *s)
{
int num;
if (!get_bits(s, 1))
return 1;
if (!get_bits(s, 1))
return 2;
if ((num = get_bits(s, 2)) != 3)
return num < 0 ? num : 3 + num;
if ((num = get_bits(s, 5)) != 31)
return num < 0 ? num : 6 + num;
num = get_bits(s, 7);
return num < 0 ? num : 37 + num;
}
static int getlblockinc(Jpeg2000DecoderContext *s)
{
int res = 0, ret;
while (ret = get_bits(s, 1)) {
if (ret < 0)
return ret;
res++;
}
return res;
}
static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s,
Jpeg2000CodingStyle *codsty,
Jpeg2000ResLevel *rlevel, int precno,
int layno, uint8_t *expn, int numgbits)
{
int bandno, cblkno, ret, nb_code_blocks;
if (!(ret = get_bits(s, 1))) {
jpeg2000_flush(s);
return 0;
} else if (ret < 0)
return ret;
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
Jpeg2000Band *band = rlevel->band + bandno;
Jpeg2000Prec *prec = band->prec + precno;
if (band->coord[0][0] == band->coord[0][1] ||
band->coord[1][0] == band->coord[1][1])
continue;
nb_code_blocks = prec->nb_codeblocks_height *
prec->nb_codeblocks_width;
for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
int incl, newpasses, llen;
if (cblk->npasses)
incl = get_bits(s, 1);
else
incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;
if (!incl)
continue;
else if (incl < 0)
return incl;
if (!cblk->npasses) {
int v = expn[bandno] + numgbits - 1 -
tag_tree_decode(s, prec->zerobits + cblkno, 100);
if (v < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"nonzerobits %d invalid\n", v);
return AVERROR_INVALIDDATA;
}
cblk->nonzerobits = v;
}
if ((newpasses = getnpasses(s)) < 0)
return newpasses;
if ((llen = getlblockinc(s)) < 0)
return llen;
cblk->lblock += llen;
if ((ret = get_bits(s, av_log2(newpasses) + cblk->lblock)) < 0)
return ret;
if (ret > sizeof(cblk->data)) {
avpriv_request_sample(s->avctx,
"Block with lengthinc greater than %zu",
sizeof(cblk->data));
return AVERROR_PATCHWELCOME;
}
cblk->lengthinc = ret;
cblk->npasses += newpasses;
}
}
jpeg2000_flush(s);
if (codsty->csty & JPEG2000_CSTY_EPH) {
if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)
bytestream2_skip(&s->g, 2);
else
av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found.\n");
}
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
Jpeg2000Band *band = rlevel->band + bandno;
Jpeg2000Prec *prec = band->prec + precno;
nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;
for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
if ( bytestream2_get_bytes_left(&s->g) < cblk->lengthinc
|| sizeof(cblk->data) < cblk->length + cblk->lengthinc + 2
) {
av_log(s->avctx, AV_LOG_ERROR,
"Block length %d or lengthinc %d is too large\n",
cblk->length, cblk->lengthinc);
return AVERROR_INVALIDDATA;
}
bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc);
cblk->length += cblk->lengthinc;
cblk->lengthinc = 0;
}
}
return 0;
}
static int jpeg2000_decode_packets(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
{
int ret = 0;
int layno, reslevelno, compno, precno, ok_reslevel;
int x, y;
s->bit_index = 8;
switch (tile->codsty[0].prog_order) {
case JPEG2000_PGOD_RLCP:
avpriv_request_sample(s->avctx, "Progression order RLCP");
case JPEG2000_PGOD_LRCP:
for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
ok_reslevel = 1;
for (reslevelno = 0; ok_reslevel; reslevelno++) {
ok_reslevel = 0;
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
if (reslevelno < codsty->nreslevels) {
Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel +
reslevelno;
ok_reslevel = 1;
for (precno = 0; precno < rlevel->num_precincts_x * rlevel->num_precincts_y; precno++)
if ((ret = jpeg2000_decode_packet(s,
codsty, rlevel,
precno, layno,
qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
qntsty->nguardbits)) < 0)
return ret;
}
}
}
}
break;
case JPEG2000_PGOD_CPRL:
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
Jpeg2000QuantStyle *qntsty = tile->qntsty + compno;
/* Set bit stream buffer address according to tile-part.
* For DCinema one tile-part per component, so can be
* indexed by component. */
s->g = tile->tile_part[compno].tpg;
/* Position loop (y axis)
* TODO: Automate computing of step 256.
* Fixed here, but to be computed before entering here. */
for (y = 0; y < s->height; y += 256) {
/* Position loop (y axis)
* TODO: automate computing of step 256.
* Fixed here, but to be computed before entering here. */
for (x = 0; x < s->width; x += 256) {
for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
uint16_t prcx, prcy;
uint8_t reducedresno = codsty->nreslevels - 1 -reslevelno; // ==> N_L - r
Jpeg2000ResLevel *rlevel = tile->comp[compno].reslevel + reslevelno;
if (!((y % (1 << (rlevel->log2_prec_height + reducedresno)) == 0) ||
(y == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
continue;
if (!((x % (1 << (rlevel->log2_prec_width + reducedresno)) == 0) ||
(x == 0))) // TODO: 2nd condition simplified as try0 always =0 for dcinema
continue;
// check if a precinct exists
prcx = ff_jpeg2000_ceildivpow2(x, reducedresno) >> rlevel->log2_prec_width;
prcy = ff_jpeg2000_ceildivpow2(y, reducedresno) >> rlevel->log2_prec_height;
precno = prcx + rlevel->num_precincts_x * prcy;
for (layno = 0; layno < tile->codsty[0].nlayers; layno++) {
if ((ret = jpeg2000_decode_packet(s, codsty, rlevel,
precno, layno,
qntsty->expn + (reslevelno ? 3 * (reslevelno - 1) + 1 : 0),
qntsty->nguardbits)) < 0)
return ret;
}
}
}
}
}
break;
case JPEG2000_PGOD_RPCL:
avpriv_request_sample(s->avctx, "Progression order RPCL");
ret = AVERROR_PATCHWELCOME;
break;
case JPEG2000_PGOD_PCRL:
avpriv_request_sample(s->avctx, "Progression order PCRL");
ret = AVERROR_PATCHWELCOME;
break;
default:
break;
}
/* EOC marker reached */
bytestream2_skip(&s->g, 2);
return ret;
}
/* TIER-1 routines */
static void decode_sigpass(Jpeg2000T1Context *t1, int width, int height,
int bpno, int bandno, int bpass_csty_symbol,
int vert_causal_ctx_csty_symbol)
{
int mask = 3 << (bpno - 1), y0, x, y;
for (y0 = 0; y0 < height; y0 += 4)
for (x = 0; x < width; x++)
for (y = y0; y < height && y < y0 + 4; y++) {
if ((t1->flags[y+1][x+1] & JPEG2000_T1_SIG_NB)
&& !(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
int flags_mask = -1;
if (vert_causal_ctx_csty_symbol && y == y0 + 3)
flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
if (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask, bandno))) {
int xorbit, ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y+1][x+1], &xorbit);
if (bpass_csty_symbol)
t1->data[y][x] = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ? -mask : mask;
else
t1->data[y][x] = (ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ctxno) ^ xorbit) ?
-mask : mask;
ff_jpeg2000_set_significance(t1, x, y,
t1->data[y][x] < 0);
}
t1->flags[y + 1][x + 1] |= JPEG2000_T1_VIS;
}
}
}
static void decode_refpass(Jpeg2000T1Context *t1, int width, int height,
int bpno)
{
int phalf, nhalf;
int y0, x, y;
phalf = 1 << (bpno - 1);
nhalf = -phalf;
for (y0 = 0; y0 < height; y0 += 4)
for (x = 0; x < width; x++)
for (y = y0; y < height && y < y0 + 4; y++)
if ((t1->flags[y + 1][x + 1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS)) == JPEG2000_T1_SIG) {
int ctxno = ff_jpeg2000_getrefctxno(t1->flags[y + 1][x + 1]);
int r = ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states + ctxno)
? phalf : nhalf;
t1->data[y][x] += t1->data[y][x] < 0 ? -r : r;
t1->flags[y + 1][x + 1] |= JPEG2000_T1_REF;
}
}
static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,
int width, int height, int bpno, int bandno,
int seg_symbols, int vert_causal_ctx_csty_symbol)
{
int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;
for (y0 = 0; y0 < height; y0 += 4) {
for (x = 0; x < width; x++) {
if (y0 + 3 < height &&
!((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
(t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
(t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||
(t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)))) {
if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))
continue;
runlen = ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states + MQC_CX_UNI);
runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states +
MQC_CX_UNI);
dec = 1;
} else {
runlen = 0;
dec = 0;
}
for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {
if (!dec) {
if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {
int flags_mask = -1;
if (vert_causal_ctx_csty_symbol && y == y0 + 3)
flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE);
dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,
bandno));
}
}
if (dec) {
int xorbit;
int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1],
&xorbit);
t1->data[y][x] = (ff_mqc_decode(&t1->mqc,
t1->mqc.cx_states + ctxno) ^
xorbit)
? -mask : mask;
ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);
}
dec = 0;
t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;
}
}
}
if (seg_symbols) {
int val;
val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);
if (val != 0xa)
av_log(s->avctx, AV_LOG_ERROR,
"Segmentation symbol value incorrect\n");
}
}
static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,
Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,
int width, int height, int bandpos)
{
int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;
int clnpass_cnt = 0;
int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS;
int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;
av_assert0(width <= JPEG2000_MAX_CBLKW);
av_assert0(height <= JPEG2000_MAX_CBLKH);
for (y = 0; y < height; y++)
memset(t1->data[y], 0, width * sizeof(**t1->data));
/* If code-block contains no compressed data: nothing to do. */
if (!cblk->length)
return 0;
for (y = 0; y < height + 2; y++)
memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));
cblk->data[cblk->length] = 0xff;
cblk->data[cblk->length+1] = 0xff;
ff_mqc_initdec(&t1->mqc, cblk->data);
while (passno--) {
switch(pass_t) {
case 0:
decode_sigpass(t1, width, height, bpno + 1, bandpos,
bpass_csty_symbol && (clnpass_cnt >= 4),
vert_causal_ctx_csty_symbol);
break;
case 1:
decode_refpass(t1, width, height, bpno + 1);
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
case 2:
decode_clnpass(s, t1, width, height, bpno + 1, bandpos,
codsty->cblk_style & JPEG2000_CBLK_SEGSYM,
vert_causal_ctx_csty_symbol);
clnpass_cnt = clnpass_cnt + 1;
if (bpass_csty_symbol && clnpass_cnt >= 4)
ff_mqc_initdec(&t1->mqc, cblk->data);
break;
}
pass_t++;
if (pass_t == 3) {
bpno--;
pass_t = 0;
}
}
return 0;
}
/* TODO: Verify dequantization for lossless case
* comp->data can be float or int
* band->stepsize can be float or int
* depending on the type of DWT transformation.
* see ISO/IEC 15444-1:2002 A.6.1 */
/* Float dequantization of a codeblock.*/
static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,
Jpeg2000Component *comp,
Jpeg2000T1Context *t1, Jpeg2000Band *band)
{
int i, j;
int w = cblk->coord[0][1] - cblk->coord[0][0];
for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
float *datap = &comp->f_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
int *src = t1->data[j];
for (i = 0; i < w; ++i)
datap[i] = src[i] * band->f_stepsize;
}
}
/* Integer dequantization of a codeblock.*/
static void dequantization_int(int x, int y, Jpeg2000Cblk *cblk,
Jpeg2000Component *comp,
Jpeg2000T1Context *t1, Jpeg2000Band *band)
{
int i, j;
int w = cblk->coord[0][1] - cblk->coord[0][0];
for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j) {
int32_t *datap = &comp->i_data[(comp->coord[0][1] - comp->coord[0][0]) * (y + j) + x];
int *src = t1->data[j];
for (i = 0; i < w; ++i)
datap[i] = (src[i] * band->i_stepsize + (1 << 14)) >> 15;
}
}
/* Inverse ICT parameters in float and integer.
* int value = (float value) * (1<<16) */
static const float f_ict_params[4] = {
1.402f,
0.34413f,
0.71414f,
1.772f
};
static const int i_ict_params[4] = {
91881,
22553,
46802,
116130
};
static void mct_decode(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)
{
int i, csize = 1;
int32_t *src[3], i0, i1, i2;
float *srcf[3], i0f, i1f, i2f;
for (i = 1; i < 3; i++)
if (tile->codsty[0].transform != tile->codsty[i].transform) {
av_log(s->avctx, AV_LOG_ERROR, "Transforms mismatch, MCT not supported\n");
return;
}
for (i = 0; i < 3; i++)
if (tile->codsty[0].transform == FF_DWT97)
srcf[i] = tile->comp[i].f_data;
else
src [i] = tile->comp[i].i_data;
for (i = 0; i < 2; i++)
csize *= tile->comp[0].coord[i][1] - tile->comp[0].coord[i][0];
switch (tile->codsty[0].transform) {
case FF_DWT97:
for (i = 0; i < csize; i++) {
i0f = *srcf[0] + (f_ict_params[0] * *srcf[2]);
i1f = *srcf[0] - (f_ict_params[1] * *srcf[1])
- (f_ict_params[2] * *srcf[2]);
i2f = *srcf[0] + (f_ict_params[3] * *srcf[1]);
*srcf[0]++ = i0f;
*srcf[1]++ = i1f;
*srcf[2]++ = i2f;
}
break;
case FF_DWT97_INT:
for (i = 0; i < csize; i++) {
i0 = *src[0] + (((i_ict_params[0] * *src[2]) + (1 << 15)) >> 16);
i1 = *src[0] - (((i_ict_params[1] * *src[1]) + (1 << 15)) >> 16)
- (((i_ict_params[2] * *src[2]) + (1 << 15)) >> 16);
i2 = *src[0] + (((i_ict_params[3] * *src[1]) + (1 << 15)) >> 16);
*src[0]++ = i0;
*src[1]++ = i1;
*src[2]++ = i2;
}
break;
case FF_DWT53:
for (i = 0; i < csize; i++) {
i1 = *src[0] - (*src[2] + *src[1] >> 2);
i0 = i1 + *src[2];
i2 = i1 + *src[1];
*src[0]++ = i0;
*src[1]++ = i1;
*src[2]++ = i2;
}
break;
}
}
static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile,
AVFrame *picture)
{
int compno, reslevelno, bandno;
int x, y;
uint8_t *line;
Jpeg2000T1Context t1;
/* Loop on tile components */
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
/* Loop on resolution levels */
for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {
Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;
/* Loop on bands */
for (bandno = 0; bandno < rlevel->nbands; bandno++) {
int nb_precincts, precno;
Jpeg2000Band *band = rlevel->band + bandno;
int cblkno = 0, bandpos;
bandpos = bandno + (reslevelno > 0);
if (band->coord[0][0] == band->coord[0][1] ||
band->coord[1][0] == band->coord[1][1])
continue;
nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;
/* Loop on precincts */
for (precno = 0; precno < nb_precincts; precno++) {
Jpeg2000Prec *prec = band->prec + precno;
/* Loop on codeblocks */
for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {
int x, y;
Jpeg2000Cblk *cblk = prec->cblk + cblkno;
decode_cblk(s, codsty, &t1, cblk,
cblk->coord[0][1] - cblk->coord[0][0],
cblk->coord[1][1] - cblk->coord[1][0],
bandpos);
x = cblk->coord[0][0];
y = cblk->coord[1][0];
if (codsty->transform == FF_DWT97)
dequantization_float(x, y, cblk, comp, &t1, band);
else
dequantization_int(x, y, cblk, comp, &t1, band);
} /* end cblk */
} /*end prec */
} /* end band */
} /* end reslevel */
/* inverse DWT */
ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data);
} /*end comp */
/* inverse MCT transformation */
if (tile->codsty[0].mct)
mct_decode(s, tile);
if (s->cdef[0] < 0) {
for (x = 0; x < s->ncomponents; x++)
s->cdef[x] = x + 1;
if ((s->ncomponents & 1) == 0)
s->cdef[s->ncomponents-1] = 0;
}
if (s->precision <= 8) {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
float *datap = comp->f_data;
int32_t *i_datap = comp->i_data;
int cbps = s->cbps[compno];
int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
int planar = !!picture->data[2];
int pixelsize = planar ? 1 : s->ncomponents;
int plane = 0;
if (planar)
plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
y = tile->comp[compno].coord[1][0] - s->image_offset_y;
line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane];
for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
uint8_t *dst;
x = tile->comp[compno].coord[0][0] - s->image_offset_x;
dst = line + x / s->cdx[compno] * pixelsize + compno*!planar;
if (codsty->transform == FF_DWT97) {
for (; x < w; x += s->cdx[compno]) {
int val = lrintf(*datap) + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
*dst = val << (8 - cbps);
datap++;
dst += pixelsize;
}
} else {
for (; x < w; x += s->cdx[compno]) {
int val = *i_datap + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
*dst = val << (8 - cbps);
i_datap++;
dst += pixelsize;
}
}
line += picture->linesize[plane];
}
}
} else {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = tile->comp + compno;
Jpeg2000CodingStyle *codsty = tile->codsty + compno;
float *datap = comp->f_data;
int32_t *i_datap = comp->i_data;
uint16_t *linel;
int cbps = s->cbps[compno];
int w = tile->comp[compno].coord[0][1] - s->image_offset_x;
int planar = !!picture->data[2];
int pixelsize = planar ? 1 : s->ncomponents;
int plane = 0;
if (planar)
plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1);
y = tile->comp[compno].coord[1][0] - s->image_offset_y;
linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1);
for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {
uint16_t *dst;
x = tile->comp[compno].coord[0][0] - s->image_offset_x;
dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar);
if (codsty->transform == FF_DWT97) {
for (; x < w; x += s-> cdx[compno]) {
int val = lrintf(*datap) + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
/* align 12 bit values in little-endian mode */
*dst = val << (16 - cbps);
datap++;
dst += pixelsize;
}
} else {
for (; x < w; x += s-> cdx[compno]) {
int val = *i_datap + (1 << (cbps - 1));
/* DC level shift and clip see ISO 15444-1:2002 G.1.2 */
val = av_clip(val, 0, (1 << cbps) - 1);
/* align 12 bit values in little-endian mode */
*dst = val << (16 - cbps);
i_datap++;
dst += pixelsize;
}
}
linel += picture->linesize[plane] >> 1;
}
}
}
return 0;
}
static void jpeg2000_dec_cleanup(Jpeg2000DecoderContext *s)
{
int tileno, compno;
for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
if (s->tile[tileno].comp) {
for (compno = 0; compno < s->ncomponents; compno++) {
Jpeg2000Component *comp = s->tile[tileno].comp + compno;
Jpeg2000CodingStyle *codsty = s->tile[tileno].codsty + compno;
ff_jpeg2000_cleanup(comp, codsty);
}
av_freep(&s->tile[tileno].comp);
}
}
av_freep(&s->tile);
memset(s->codsty, 0, sizeof(s->codsty));
memset(s->qntsty, 0, sizeof(s->qntsty));
s->numXtiles = s->numYtiles = 0;
}
static int jpeg2000_read_main_headers(Jpeg2000DecoderContext *s)
{
Jpeg2000CodingStyle *codsty = s->codsty;
Jpeg2000QuantStyle *qntsty = s->qntsty;
uint8_t *properties = s->properties;
for (;;) {
int len, ret = 0;
uint16_t marker;
int oldpos;
if (bytestream2_get_bytes_left(&s->g) < 2) {
av_log(s->avctx, AV_LOG_ERROR, "Missing EOC\n");
break;
}
marker = bytestream2_get_be16u(&s->g);
oldpos = bytestream2_tell(&s->g);
if (marker == JPEG2000_SOD) {
Jpeg2000Tile *tile;
Jpeg2000TilePart *tp;
if (!s->tile) {
av_log(s->avctx, AV_LOG_ERROR, "Missing SIZ\n");
return AVERROR_INVALIDDATA;
}
if (s->curtileno < 0) {
av_log(s->avctx, AV_LOG_ERROR, "Missing SOT\n");
return AVERROR_INVALIDDATA;
}
tile = s->tile + s->curtileno;
tp = tile->tile_part + tile->tp_idx;
if (tp->tp_end < s->g.buffer) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tpend\n");
return AVERROR_INVALIDDATA;
}
bytestream2_init(&tp->tpg, s->g.buffer, tp->tp_end - s->g.buffer);
bytestream2_skip(&s->g, tp->tp_end - s->g.buffer);
continue;
}
if (marker == JPEG2000_EOC)
break;
len = bytestream2_get_be16(&s->g);
if (len < 2 || bytestream2_get_bytes_left(&s->g) < len - 2)
return AVERROR_INVALIDDATA;
switch (marker) {
case JPEG2000_SIZ:
ret = get_siz(s);
if (!s->tile)
s->numXtiles = s->numYtiles = 0;
break;
case JPEG2000_COC:
ret = get_coc(s, codsty, properties);
break;
case JPEG2000_COD:
ret = get_cod(s, codsty, properties);
break;
case JPEG2000_QCC:
ret = get_qcc(s, len, qntsty, properties);
break;
case JPEG2000_QCD:
ret = get_qcd(s, len, qntsty, properties);
break;
case JPEG2000_SOT:
if (!(ret = get_sot(s, len))) {
av_assert1(s->curtileno >= 0);
codsty = s->tile[s->curtileno].codsty;
qntsty = s->tile[s->curtileno].qntsty;
properties = s->tile[s->curtileno].properties;
}
break;
case JPEG2000_COM:
// the comment is ignored
bytestream2_skip(&s->g, len - 2);
break;
case JPEG2000_TLM:
// Tile-part lengths
ret = get_tlm(s, len);
break;
default:
av_log(s->avctx, AV_LOG_ERROR,
"unsupported marker 0x%.4X at pos 0x%X\n",
marker, bytestream2_tell(&s->g) - 4);
bytestream2_skip(&s->g, len - 2);
break;
}
if (bytestream2_tell(&s->g) - oldpos != len || ret) {
av_log(s->avctx, AV_LOG_ERROR,
"error during processing marker segment %.4x\n", marker);
return ret ? ret : -1;
}
}
return 0;
}
/* Read bit stream packets --> T2 operation. */
static int jpeg2000_read_bitstream_packets(Jpeg2000DecoderContext *s)
{
int ret = 0;
int tileno;
for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++) {
Jpeg2000Tile *tile = s->tile + tileno;
if (ret = init_tile(s, tileno))
return ret;
s->g = tile->tile_part[0].tpg;
if (ret = jpeg2000_decode_packets(s, tile))
return ret;
}
return 0;
}
static int jp2_find_codestream(Jpeg2000DecoderContext *s)
{
uint32_t atom_size, atom, atom_end;
int search_range = 10;
while (search_range
&&
bytestream2_get_bytes_left(&s->g) >= 8) {
atom_size = bytestream2_get_be32u(&s->g);
atom = bytestream2_get_be32u(&s->g);
atom_end = bytestream2_tell(&s->g) + atom_size - 8;
if (atom == JP2_CODESTREAM)
return 1;
if (bytestream2_get_bytes_left(&s->g) < atom_size || atom_end < atom_size)
return 0;
if (atom == JP2_HEADER &&
atom_size >= 16) {
uint32_t atom2_size, atom2, atom2_end;
do {
atom2_size = bytestream2_get_be32u(&s->g);
atom2 = bytestream2_get_be32u(&s->g);
atom2_end = bytestream2_tell(&s->g) + atom2_size - 8;
if (atom2_size < 8 || atom2_end > atom_end || atom2_end < atom2_size)
break;
if (atom2 == JP2_CODESTREAM) {
return 1;
} else if (atom2 == MKBETAG('c','o','l','r') && atom2_size >= 7) {
int method = bytestream2_get_byteu(&s->g);
bytestream2_skipu(&s->g, 2);
if (method == 1) {
s->colour_space = bytestream2_get_be32u(&s->g);
}
} else if (atom2 == MKBETAG('p','c','l','r') && atom2_size >= 6) {
int i, size, colour_count, colour_channels, colour_depth[3];
uint32_t r, g, b;
colour_count = bytestream2_get_be16u(&s->g);
colour_channels = bytestream2_get_byteu(&s->g);
// FIXME: Do not ignore channel_sign
colour_depth[0] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
colour_depth[1] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
colour_depth[2] = (bytestream2_get_byteu(&s->g) & 0x7f) + 1;
size = (colour_depth[0] + 7 >> 3) * colour_count +
(colour_depth[1] + 7 >> 3) * colour_count +
(colour_depth[2] + 7 >> 3) * colour_count;
if (colour_count > 256 ||
colour_channels != 3 ||
colour_depth[0] > 16 ||
colour_depth[1] > 16 ||
colour_depth[2] > 16 ||
atom2_size < size) {
avpriv_request_sample(s->avctx, "Unknown palette");
bytestream2_seek(&s->g, atom2_end, SEEK_SET);
continue;
}
s->pal8 = 1;
for (i = 0; i < colour_count; i++) {
if (colour_depth[0] <= 8) {
r = bytestream2_get_byteu(&s->g) << 8 - colour_depth[0];
r |= r >> colour_depth[0];
} else {
r = bytestream2_get_be16u(&s->g) >> colour_depth[0] - 8;
}
if (colour_depth[1] <= 8) {
g = bytestream2_get_byteu(&s->g) << 8 - colour_depth[1];
r |= r >> colour_depth[1];
} else {
g = bytestream2_get_be16u(&s->g) >> colour_depth[1] - 8;
}
if (colour_depth[2] <= 8) {
b = bytestream2_get_byteu(&s->g) << 8 - colour_depth[2];
r |= r >> colour_depth[2];
} else {
b = bytestream2_get_be16u(&s->g) >> colour_depth[2] - 8;
}
s->palette[i] = 0xffu << 24 | r << 16 | g << 8 | b;
}
} else if (atom2 == MKBETAG('c','d','e','f') && atom2_size >= 2) {
int n = bytestream2_get_be16u(&s->g);
for (; n>0; n--) {
int cn = bytestream2_get_be16(&s->g);
int av_unused typ = bytestream2_get_be16(&s->g);
int asoc = bytestream2_get_be16(&s->g);
if (cn < 4 || asoc < 4)
s->cdef[cn] = asoc;
}
}
bytestream2_seek(&s->g, atom2_end, SEEK_SET);
} while (atom_end - atom2_end >= 8);
} else {
search_range--;
}
bytestream2_seek(&s->g, atom_end, SEEK_SET);
}
return 0;
}
static int jpeg2000_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
Jpeg2000DecoderContext *s = avctx->priv_data;
ThreadFrame frame = { .f = data };
AVFrame *picture = data;
int tileno, ret;
s->avctx = avctx;
bytestream2_init(&s->g, avpkt->data, avpkt->size);
s->curtileno = -1;
memset(s->cdef, -1, sizeof(s->cdef));
if (bytestream2_get_bytes_left(&s->g) < 2) {
ret = AVERROR_INVALIDDATA;
goto end;
}
// check if the image is in jp2 format
if (bytestream2_get_bytes_left(&s->g) >= 12 &&
(bytestream2_get_be32u(&s->g) == 12) &&
(bytestream2_get_be32u(&s->g) == JP2_SIG_TYPE) &&
(bytestream2_get_be32u(&s->g) == JP2_SIG_VALUE)) {
if (!jp2_find_codestream(s)) {
av_log(avctx, AV_LOG_ERROR,
"Could not find Jpeg2000 codestream atom.\n");
ret = AVERROR_INVALIDDATA;
goto end;
}
} else {
bytestream2_seek(&s->g, 0, SEEK_SET);
}
while (bytestream2_get_bytes_left(&s->g) >= 3 && bytestream2_peek_be16(&s->g) != JPEG2000_SOC)
bytestream2_skip(&s->g, 1);
if (bytestream2_get_be16u(&s->g) != JPEG2000_SOC) {
av_log(avctx, AV_LOG_ERROR, "SOC marker not present\n");
ret = AVERROR_INVALIDDATA;
goto end;
}
if (ret = jpeg2000_read_main_headers(s))
goto end;
/* get picture buffer */
if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
goto end;
picture->pict_type = AV_PICTURE_TYPE_I;
picture->key_frame = 1;
if (ret = jpeg2000_read_bitstream_packets(s))
goto end;
for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++)
if (ret = jpeg2000_decode_tile(s, s->tile + tileno, picture))
goto end;
jpeg2000_dec_cleanup(s);
*got_frame = 1;
if (s->avctx->pix_fmt == AV_PIX_FMT_PAL8)
memcpy(picture->data[1], s->palette, 256 * sizeof(uint32_t));
return bytestream2_tell(&s->g);
end:
jpeg2000_dec_cleanup(s);
return ret;
}
static void jpeg2000_init_static_data(AVCodec *codec)
{
ff_jpeg2000_init_tier1_luts();
ff_mqc_init_context_tables();
}
#define OFFSET(x) offsetof(Jpeg2000DecoderContext, x)
#define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
static const AVOption options[] = {
{ "lowres", "Lower the decoding resolution by a power of two",
OFFSET(reduction_factor), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, JPEG2000_MAX_RESLEVELS - 1, VD },
{ NULL },
};
static const AVProfile profiles[] = {
{ FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_0, "JPEG 2000 codestream restriction 0" },
{ FF_PROFILE_JPEG2000_CSTREAM_RESTRICTION_1, "JPEG 2000 codestream restriction 1" },
{ FF_PROFILE_JPEG2000_CSTREAM_NO_RESTRICTION, "JPEG 2000 no codestream restrictions" },
{ FF_PROFILE_JPEG2000_DCINEMA_2K, "JPEG 2000 digital cinema 2K" },
{ FF_PROFILE_JPEG2000_DCINEMA_4K, "JPEG 2000 digital cinema 4K" },
{ FF_PROFILE_UNKNOWN },
};
static const AVClass jpeg2000_class = {
.class_name = "jpeg2000",
.item_name = av_default_item_name,
.option = options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_jpeg2000_decoder = {
.name = "jpeg2000",
.long_name = NULL_IF_CONFIG_SMALL("JPEG 2000"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_JPEG2000,
.capabilities = CODEC_CAP_FRAME_THREADS,
.priv_data_size = sizeof(Jpeg2000DecoderContext),
.init_static_data = jpeg2000_init_static_data,
.decode = jpeg2000_decode_frame,
.priv_class = &jpeg2000_class,
.max_lowres = 5,
.profiles = NULL_IF_CONFIG_SMALL(profiles)
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5823_0 |
crossvul-cpp_data_bad_3987_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "path.h"
#include "posix.h"
#include "repository.h"
#ifdef GIT_WIN32
#include "win32/posix.h"
#include "win32/w32_buffer.h"
#include "win32/w32_util.h"
#include "win32/version.h"
#include <aclapi.h>
#else
#include <dirent.h>
#endif
#include <stdio.h>
#include <ctype.h>
#define LOOKS_LIKE_DRIVE_PREFIX(S) (git__isalpha((S)[0]) && (S)[1] == ':')
#ifdef GIT_WIN32
static bool looks_like_network_computer_name(const char *path, int pos)
{
if (pos < 3)
return false;
if (path[0] != '/' || path[1] != '/')
return false;
while (pos-- > 2) {
if (path[pos] == '/')
return false;
}
return true;
}
#endif
/*
* Based on the Android implementation, BSD licensed.
* http://android.git.kernel.org/
*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git_path_basename_r(git_buf *buffer, const char *path)
{
const char *endp, *startp;
int len, result;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
startp = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
/* All slashes becomes "/" */
if (endp == path && *endp == '/') {
startp = "/";
len = 1;
goto Exit;
}
/* Find the start of the base */
startp = endp;
while (startp > path && *(startp - 1) != '/')
startp--;
/* Cast is safe because max path < max int */
len = (int)(endp - startp + 1);
Exit:
result = len;
if (buffer != NULL && git_buf_set(buffer, startp, len) < 0)
return -1;
return result;
}
/*
* Determine if the path is a Windows prefix and, if so, returns
* its actual lentgh. If it is not a prefix, returns -1.
*/
static int win32_prefix_length(const char *path, int len)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
GIT_UNUSED(len);
#else
/*
* Mimic unix behavior where '/.git' returns '/': 'C:/.git' will return
* 'C:/' here
*/
if (len == 2 && LOOKS_LIKE_DRIVE_PREFIX(path))
return 2;
/*
* Similarly checks if we're dealing with a network computer name
* '//computername/.git' will return '//computername/'
*/
if (looks_like_network_computer_name(path, len))
return len;
#endif
return -1;
}
/*
* Based on the Android implementation, BSD licensed.
* Check http://android.git.kernel.org/
*/
int git_path_dirname_r(git_buf *buffer, const char *path)
{
const char *endp;
int is_prefix = 0, len;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
path = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Find the start of the dir */
while (endp > path && *endp != '/')
endp--;
/* Either the dir is "/" or there are no slashes */
if (endp == path) {
path = (*endp == '/') ? "/" : ".";
len = 1;
goto Exit;
}
do {
endp--;
} while (endp > path && *endp == '/');
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Cast is safe because max path < max int */
len = (int)(endp - path + 1);
Exit:
if (buffer) {
if (git_buf_set(buffer, path, len) < 0)
return -1;
if (is_prefix && git_buf_putc(buffer, '/') < 0)
return -1;
}
return len;
}
char *git_path_dirname(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *dirname;
git_path_dirname_r(&buf, path);
dirname = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return dirname;
}
char *git_path_basename(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *basename;
git_path_basename_r(&buf, path);
basename = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return basename;
}
size_t git_path_basename_offset(git_buf *buffer)
{
ssize_t slash;
if (!buffer || buffer->size <= 0)
return 0;
slash = git_buf_rfind_next(buffer, '/');
if (slash >= 0 && buffer->ptr[slash] == '/')
return (size_t)(slash + 1);
return 0;
}
const char *git_path_topdir(const char *path)
{
size_t len;
ssize_t i;
assert(path);
len = strlen(path);
if (!len || path[len - 1] != '/')
return NULL;
for (i = (ssize_t)len - 2; i >= 0; --i)
if (path[i] == '/')
break;
return &path[i + 1];
}
int git_path_root(const char *path)
{
int offset = 0;
/* Does the root of the path look like a windows drive ? */
if (LOOKS_LIKE_DRIVE_PREFIX(path))
offset += 2;
#ifdef GIT_WIN32
/* Are we dealing with a windows network path? */
else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
(path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
{
offset += 2;
/* Skip the computer name segment */
while (path[offset] && path[offset] != '/' && path[offset] != '\\')
offset++;
}
if (path[offset] == '\\')
return offset;
#endif
if (path[offset] == '/')
return offset;
return -1; /* Not a real error - signals that path is not rooted */
}
void git_path_trim_slashes(git_buf *path)
{
int ceiling = git_path_root(path->ptr) + 1;
assert(ceiling >= 0);
while (path->size > (size_t)ceiling) {
if (path->ptr[path->size-1] != '/')
break;
path->ptr[path->size-1] = '\0';
path->size--;
}
}
int git_path_join_unrooted(
git_buf *path_out, const char *path, const char *base, ssize_t *root_at)
{
ssize_t root;
assert(path && path_out);
root = (ssize_t)git_path_root(path);
if (base != NULL && root < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
root = (ssize_t)strlen(base);
} else {
if (git_buf_sets(path_out, path) < 0)
return -1;
if (root < 0)
root = 0;
else if (base)
git_path_equal_or_prefixed(base, path, &root);
}
if (root_at)
*root_at = root;
return 0;
}
void git_path_squash_slashes(git_buf *path)
{
char *p, *q;
if (path->size == 0)
return;
for (p = path->ptr, q = path->ptr; *q; p++, q++) {
*p = *q;
while (*q == '/' && *(q+1) == '/') {
path->size--;
q++;
}
}
*p = '\0';
}
int git_path_prettify(git_buf *path_out, const char *path, const char *base)
{
char buf[GIT_PATH_MAX];
assert(path && path_out);
/* construct path if needed */
if (base != NULL && git_path_root(path) < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
path = path_out->ptr;
}
if (p_realpath(path, buf) == NULL) {
/* git_error_set resets the errno when dealing with a GIT_ERROR_OS kind of error */
int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
git_error_set(GIT_ERROR_OS, "failed to resolve path '%s'", path);
git_buf_clear(path_out);
return error;
}
return git_buf_sets(path_out, buf);
}
int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
{
int error = git_path_prettify(path_out, path, base);
return (error < 0) ? error : git_path_to_dir(path_out);
}
int git_path_to_dir(git_buf *path)
{
if (path->asize > 0 &&
git_buf_len(path) > 0 &&
path->ptr[git_buf_len(path) - 1] != '/')
git_buf_putc(path, '/');
return git_buf_oom(path) ? -1 : 0;
}
void git_path_string_to_dir(char* path, size_t size)
{
size_t end = strlen(path);
if (end && path[end - 1] != '/' && end < size) {
path[end] = '/';
path[end + 1] = '\0';
}
}
int git__percent_decode(git_buf *decoded_out, const char *input)
{
int len, hi, lo, i;
assert(decoded_out && input);
len = (int)strlen(input);
git_buf_clear(decoded_out);
for(i = 0; i < len; i++)
{
char c = input[i];
if (c != '%')
goto append;
if (i >= len - 2)
goto append;
hi = git__fromhex(input[i + 1]);
lo = git__fromhex(input[i + 2]);
if (hi < 0 || lo < 0)
goto append;
c = (char)(hi << 4 | lo);
i += 2;
append:
if (git_buf_putc(decoded_out, c) < 0)
return -1;
}
return 0;
}
static int error_invalid_local_file_uri(const char *uri)
{
git_error_set(GIT_ERROR_CONFIG, "'%s' is not a valid local file URI", uri);
return -1;
}
static int local_file_url_prefixlen(const char *file_url)
{
int len = -1;
if (git__prefixcmp(file_url, "file://") == 0) {
if (file_url[7] == '/')
len = 8;
else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
len = 17;
}
return len;
}
bool git_path_is_local_file_url(const char *file_url)
{
return (local_file_url_prefixlen(file_url) > 0);
}
int git_path_fromurl(git_buf *local_path_out, const char *file_url)
{
int offset;
assert(local_path_out && file_url);
if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
file_url[offset] == '\0' || file_url[offset] == '/')
return error_invalid_local_file_uri(file_url);
#ifndef GIT_WIN32
offset--; /* A *nix absolute path starts with a forward slash */
#endif
git_buf_clear(local_path_out);
return git__percent_decode(local_path_out, file_url + offset);
}
int git_path_walk_up(
git_buf *path,
const char *ceiling,
int (*cb)(void *data, const char *),
void *data)
{
int error = 0;
git_buf iter;
ssize_t stop = 0, scan;
char oldc = '\0';
assert(path && cb);
if (ceiling != NULL) {
if (git__prefixcmp(path->ptr, ceiling) == 0)
stop = (ssize_t)strlen(ceiling);
else
stop = git_buf_len(path);
}
scan = git_buf_len(path);
/* empty path: yield only once */
if (!scan) {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
return error;
}
iter.ptr = path->ptr;
iter.size = git_buf_len(path);
iter.asize = path->asize;
while (scan >= stop) {
error = cb(data, iter.ptr);
iter.ptr[scan] = oldc;
if (error) {
git_error_set_after_callback(error);
break;
}
scan = git_buf_rfind_next(&iter, '/');
if (scan >= 0) {
scan++;
oldc = iter.ptr[scan];
iter.size = scan;
iter.ptr[scan] = '\0';
}
}
if (scan >= 0)
iter.ptr[scan] = oldc;
/* relative path: yield for the last component */
if (!error && stop == 0 && iter.ptr[0] != '/') {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
}
return error;
}
bool git_path_exists(const char *path)
{
assert(path);
return p_access(path, F_OK) == 0;
}
bool git_path_isdir(const char *path)
{
struct stat st;
if (p_stat(path, &st) < 0)
return false;
return S_ISDIR(st.st_mode) != 0;
}
bool git_path_isfile(const char *path)
{
struct stat st;
assert(path);
if (p_stat(path, &st) < 0)
return false;
return S_ISREG(st.st_mode) != 0;
}
bool git_path_islink(const char *path)
{
struct stat st;
assert(path);
if (p_lstat(path, &st) < 0)
return false;
return S_ISLNK(st.st_mode) != 0;
}
#ifdef GIT_WIN32
bool git_path_is_empty_dir(const char *path)
{
git_win32_path filter_w;
bool empty = false;
if (git_win32__findfirstfile_filter(filter_w, path)) {
WIN32_FIND_DATAW findData;
HANDLE hFind = FindFirstFileW(filter_w, &findData);
/* FindFirstFile will fail if there are no children to the given
* path, which can happen if the given path is a file (and obviously
* has no children) or if the given path is an empty mount point.
* (Most directories have at least directory entries '.' and '..',
* but ridiculously another volume mounted in another drive letter's
* path space do not, and thus have nothing to enumerate.) If
* FindFirstFile fails, check if this is a directory-like thing
* (a mount point).
*/
if (hFind == INVALID_HANDLE_VALUE)
return git_path_isdir(path);
/* If the find handle was created successfully, then it's a directory */
empty = true;
do {
/* Allow the enumeration to return . and .. and still be considered
* empty. In the special case of drive roots (i.e. C:\) where . and
* .. do not occur, we can still consider the path to be an empty
* directory if there's nothing there. */
if (!git_path_is_dot_or_dotdotW(findData.cFileName)) {
empty = false;
break;
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
return empty;
}
#else
static int path_found_entry(void *payload, git_buf *path)
{
GIT_UNUSED(payload);
return !git_path_is_dot_or_dotdot(path->ptr);
}
bool git_path_is_empty_dir(const char *path)
{
int error;
git_buf dir = GIT_BUF_INIT;
if (!git_path_isdir(path))
return false;
if ((error = git_buf_sets(&dir, path)) != 0)
git_error_clear();
else
error = git_path_direach(&dir, 0, path_found_entry, NULL);
git_buf_dispose(&dir);
return !error;
}
#endif
int git_path_set_error(int errno_value, const char *path, const char *action)
{
switch (errno_value) {
case ENOENT:
case ENOTDIR:
git_error_set(GIT_ERROR_OS, "could not find '%s' to %s", path, action);
return GIT_ENOTFOUND;
case EINVAL:
case ENAMETOOLONG:
git_error_set(GIT_ERROR_OS, "invalid path for filesystem '%s'", path);
return GIT_EINVALIDSPEC;
case EEXIST:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' already exists", action, path);
return GIT_EEXISTS;
case EACCES:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' is locked", action, path);
return GIT_ELOCKED;
default:
git_error_set(GIT_ERROR_OS, "could not %s '%s'", action, path);
return -1;
}
}
int git_path_lstat(const char *path, struct stat *st)
{
if (p_lstat(path, st) == 0)
return 0;
return git_path_set_error(errno, path, "stat");
}
static bool _check_dir_contents(
git_buf *dir,
const char *sub,
bool (*predicate)(const char *))
{
bool result;
size_t dir_size = git_buf_len(dir);
size_t sub_size = strlen(sub);
size_t alloc_size;
/* leave base valid even if we could not make space for subdir */
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
git_buf_try_grow(dir, alloc_size, false) < 0)
return false;
/* save excursion */
if (git_buf_joinpath(dir, dir->ptr, sub) < 0)
return false;
result = predicate(dir->ptr);
/* restore path */
git_buf_truncate(dir, dir_size);
return result;
}
bool git_path_contains(git_buf *dir, const char *item)
{
return _check_dir_contents(dir, item, &git_path_exists);
}
bool git_path_contains_dir(git_buf *base, const char *subdir)
{
return _check_dir_contents(base, subdir, &git_path_isdir);
}
bool git_path_contains_file(git_buf *base, const char *file)
{
return _check_dir_contents(base, file, &git_path_isfile);
}
int git_path_find_dir(git_buf *dir, const char *path, const char *base)
{
int error = git_path_join_unrooted(dir, path, base, NULL);
if (!error) {
char buf[GIT_PATH_MAX];
if (p_realpath(dir->ptr, buf) != NULL)
error = git_buf_sets(dir, buf);
}
/* call dirname if this is not a directory */
if (!error) /* && git_path_isdir(dir->ptr) == false) */
error = (git_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
if (!error)
error = git_path_to_dir(dir);
return error;
}
int git_path_resolve_relative(git_buf *path, size_t ceiling)
{
char *base, *to, *from, *next;
size_t len;
GIT_ERROR_CHECK_ALLOC_BUF(path);
if (ceiling > path->size)
ceiling = path->size;
/* recognize drive prefixes, etc. that should not be backed over */
if (ceiling == 0)
ceiling = git_path_root(path->ptr) + 1;
/* recognize URL prefixes that should not be backed over */
if (ceiling == 0) {
for (next = path->ptr; *next && git__isalpha(*next); ++next);
if (next[0] == ':' && next[1] == '/' && next[2] == '/')
ceiling = (next + 3) - path->ptr;
}
base = to = from = path->ptr + ceiling;
while (*from) {
for (next = from; *next && *next != '/'; ++next);
len = next - from;
if (len == 1 && from[0] == '.')
/* do nothing with singleton dot */;
else if (len == 2 && from[0] == '.' && from[1] == '.') {
/* error out if trying to up one from a hard base */
if (to == base && ceiling != 0) {
git_error_set(GIT_ERROR_INVALID,
"cannot strip root component off url");
return -1;
}
/* no more path segments to strip,
* use '../' as a new base path */
if (to == base) {
if (*next == '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
/* this is now the base, can't back up from a
* relative prefix */
base = to;
} else {
/* back up a path segment */
while (to > base && to[-1] == '/') to--;
while (to > base && to[-1] != '/') to--;
}
} else {
if (*next == '/' && *from != '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
}
from += len;
while (*from == '/') from++;
}
*to = '\0';
path->size = to - path->ptr;
return 0;
}
int git_path_apply_relative(git_buf *target, const char *relpath)
{
return git_buf_joinpath(target, git_buf_cstr(target), relpath) ||
git_path_resolve_relative(target, 0);
}
int git_path_cmp(
const char *name1, size_t len1, int isdir1,
const char *name2, size_t len2, int isdir2,
int (*compare)(const char *, const char *, size_t))
{
unsigned char c1, c2;
size_t len = len1 < len2 ? len1 : len2;
int cmp;
cmp = compare(name1, name2, len);
if (cmp)
return cmp;
c1 = name1[len];
c2 = name2[len];
if (c1 == '\0' && isdir1)
c1 = '/';
if (c2 == '\0' && isdir2)
c2 = '/';
return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}
size_t git_path_common_dirlen(const char *one, const char *two)
{
const char *p, *q, *dirsep = NULL;
for (p = one, q = two; *p && *q; p++, q++) {
if (*p == '/' && *q == '/')
dirsep = p;
else if (*p != *q)
break;
}
return dirsep ? (dirsep - one) + 1 : 0;
}
int git_path_make_relative(git_buf *path, const char *parent)
{
const char *p, *q, *p_dirsep, *q_dirsep;
size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
if (*p == '/' && *q == '/') {
p_dirsep = p;
q_dirsep = q;
}
else if (*p != *q)
break;
}
/* need at least 1 common path segment */
if ((p_dirsep == path->ptr || q_dirsep == parent) &&
(*p_dirsep != '/' || *q_dirsep != '/')) {
git_error_set(GIT_ERROR_INVALID,
"%s is not a parent of %s", parent, path->ptr);
return GIT_ENOTFOUND;
}
if (*p == '/' && !*q)
p++;
else if (!*p && *q == '/')
q++;
else if (!*p && !*q)
return git_buf_clear(path), 0;
else {
p = p_dirsep + 1;
q = q_dirsep + 1;
}
plen -= (p - path->ptr);
if (!*q)
return git_buf_set(path, p, plen);
for (; (q = strchr(q, '/')) && *(q + 1); q++)
depth++;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
GIT_ERROR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
/* save the offset as we might realllocate the pointer */
offset = p - path->ptr;
if (git_buf_try_grow(path, alloclen, 1) < 0)
return -1;
p = path->ptr + offset;
memmove(path->ptr + (depth * 3), p, plen + 1);
for (i = 0; i < depth; i++)
memcpy(path->ptr + (i * 3), "../", 3);
path->size = newlen;
return 0;
}
bool git_path_has_non_ascii(const char *path, size_t pathlen)
{
const uint8_t *scan = (const uint8_t *)path, *end;
for (end = scan + pathlen; scan < end; ++scan)
if (*scan & 0x80)
return true;
return false;
}
#ifdef GIT_USE_ICONV
int git_path_iconv_init_precompose(git_path_iconv_t *ic)
{
git_buf_init(&ic->buf, 0);
ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
return 0;
}
void git_path_iconv_clear(git_path_iconv_t *ic)
{
if (ic) {
if (ic->map != (iconv_t)-1)
iconv_close(ic->map);
git_buf_dispose(&ic->buf);
}
}
int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen)
{
char *nfd = (char*)*in, *nfc;
size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
int retry = 1;
if (!ic || ic->map == (iconv_t)-1 ||
!git_path_has_non_ascii(*in, *inlen))
return 0;
git_buf_clear(&ic->buf);
while (1) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
if (git_buf_grow(&ic->buf, alloclen) < 0)
return -1;
nfc = ic->buf.ptr + ic->buf.size;
nfclen = ic->buf.asize - ic->buf.size;
rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
ic->buf.size = (nfc - ic->buf.ptr);
if (rv != (size_t)-1)
break;
/* if we cannot convert the data (probably because iconv thinks
* it is not valid UTF-8 source data), then use original data
*/
if (errno != E2BIG)
return 0;
/* make space for 2x the remaining data to be converted
* (with per retry overhead to avoid infinite loops)
*/
wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
if (retry++ > 4)
goto fail;
}
ic->buf.ptr[ic->buf.size] = '\0';
*in = ic->buf.ptr;
*inlen = ic->buf.size;
return 0;
fail:
git_error_set(GIT_ERROR_OS, "unable to convert unicode path data");
return -1;
}
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D.XXXXXX";
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D.XXXXXX";
/* Check if the platform is decomposing unicode data for us. We will
* emulate core Git and prefer to use precomposed unicode data internally
* on these platforms, composing the decomposed unicode on the fly.
*
* This mainly happens on the Mac where HDFS stores filenames as
* decomposed unicode. Even on VFAT and SAMBA file systems, the Mac will
* return decomposed unicode from readdir() even when the actual
* filesystem is storing precomposed unicode.
*/
bool git_path_does_fs_decompose_unicode(const char *root)
{
git_buf path = GIT_BUF_INIT;
int fd;
bool found_decomposed = false;
char tmp[6];
/* Create a file using a precomposed path and then try to find it
* using the decomposed name. If the lookup fails, then we will mark
* that we should precompose unicode for this repository.
*/
if (git_buf_joinpath(&path, root, nfc_file) < 0 ||
(fd = p_mkstemp(path.ptr)) < 0)
goto done;
p_close(fd);
/* record trailing digits generated by mkstemp */
memcpy(tmp, path.ptr + path.size - sizeof(tmp), sizeof(tmp));
/* try to look up as NFD path */
if (git_buf_joinpath(&path, root, nfd_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
found_decomposed = git_path_exists(path.ptr);
/* remove temporary file (using original precomposed path) */
if (git_buf_joinpath(&path, root, nfc_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
(void)p_unlink(path.ptr);
done:
git_buf_dispose(&path);
return found_decomposed;
}
#else
bool git_path_does_fs_decompose_unicode(const char *root)
{
GIT_UNUSED(root);
return false;
}
#endif
#if defined(__sun) || defined(__GNU__)
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
#else
typedef struct dirent path_dirent_data;
#endif
int git_path_direach(
git_buf *path,
uint32_t flags,
int (*fn)(void *, git_buf *),
void *arg)
{
int error = 0;
ssize_t wd_len;
DIR *dir;
struct dirent *de;
#ifdef GIT_USE_ICONV
git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
#endif
GIT_UNUSED(flags);
if (git_path_to_dir(path) < 0)
return -1;
wd_len = git_buf_len(path);
if ((dir = opendir(path->ptr)) == NULL) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path->ptr);
if (errno == ENOENT)
return GIT_ENOTFOUND;
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&ic);
#endif
while ((de = readdir(dir)) != NULL) {
const char *de_path = de->d_name;
size_t de_len = strlen(de_path);
if (git_path_is_dot_or_dotdot(de_path))
continue;
#ifdef GIT_USE_ICONV
if ((error = git_path_iconv(&ic, &de_path, &de_len)) < 0)
break;
#endif
if ((error = git_buf_put(path, de_path, de_len)) < 0)
break;
git_error_clear();
error = fn(arg, path);
git_buf_truncate(path, wd_len); /* restore path */
/* Only set our own error if the callback did not set one already */
if (error != 0) {
if (!git_error_last())
git_error_set_after_callback(error);
break;
}
}
closedir(dir);
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&ic);
#endif
return error;
}
#if defined(GIT_WIN32) && !defined(__MINGW32__)
/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
* and better.
*/
#ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 2
#endif
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
git_win32_path path_filter;
static int is_win7_or_later = -1;
if (is_win7_or_later < 0)
is_win7_or_later = git_has_win32_version(6, 1, 0);
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
diriter->handle = INVALID_HANDLE_VALUE;
if (git_buf_puts(&diriter->path_utf8, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path_utf8);
if (diriter->path_utf8.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
!git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
git_error_set(GIT_ERROR_OS, "could not parse the directory path '%s'", path);
return -1;
}
diriter->handle = FindFirstFileExW(
path_filter,
is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
&diriter->current,
FindExSearchNameMatch,
NULL,
is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
if (diriter->handle == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", path);
return -1;
}
diriter->parent_utf8_len = diriter->path_utf8.size;
diriter->flags = flags;
return 0;
}
static int diriter_update_paths(git_path_diriter *diriter)
{
size_t filename_len, path_len;
filename_len = wcslen(diriter->current.cFileName);
if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
return -1;
if (path_len > GIT_WIN_PATH_UTF16) {
git_error_set(GIT_ERROR_FILESYSTEM,
"invalid path '%.*ls\\%ls' (path too long)",
diriter->parent_len, diriter->path, diriter->current.cFileName);
return -1;
}
diriter->path[diriter->parent_len] = L'\\';
memcpy(&diriter->path[diriter->parent_len+1],
diriter->current.cFileName, filename_len * sizeof(wchar_t));
diriter->path[path_len-1] = L'\0';
git_buf_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
if (diriter->parent_utf8_len > 0 &&
diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
git_buf_putc(&diriter->path_utf8, '/');
git_buf_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
if (git_buf_oom(&diriter->path_utf8))
return -1;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
do {
/* Our first time through, we already have the data from
* FindFirstFileW. Use it, otherwise get the next file.
*/
if (!diriter->needs_next)
diriter->needs_next = 1;
else if (!FindNextFileW(diriter->handle, &diriter->current))
return GIT_ITEROVER;
} while (skip_dot && git_path_is_dot_or_dotdotW(diriter->current.cFileName));
if (diriter_update_paths(diriter) < 0)
return -1;
return 0;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path_utf8.size > diriter->parent_utf8_len);
*out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
*out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path_utf8.ptr;
*out_len = diriter->path_utf8.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_win32__file_attribute_to_stat(out,
(WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
diriter->path);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
git_buf_dispose(&diriter->path_utf8);
if (diriter->handle != INVALID_HANDLE_VALUE) {
FindClose(diriter->handle);
diriter->handle = INVALID_HANDLE_VALUE;
}
}
#else
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
if (git_buf_puts(&diriter->path, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path);
if (diriter->path.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
git_buf_dispose(&diriter->path);
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path);
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&diriter->ic);
#endif
diriter->parent_len = diriter->path.size;
diriter->flags = flags;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
struct dirent *de;
const char *filename;
size_t filename_len;
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
int error = 0;
assert(diriter);
errno = 0;
do {
if ((de = readdir(diriter->dir)) == NULL) {
if (!errno)
return GIT_ITEROVER;
git_error_set(GIT_ERROR_OS,
"could not read directory '%s'", diriter->path.ptr);
return -1;
}
} while (skip_dot && git_path_is_dot_or_dotdot(de->d_name));
filename = de->d_name;
filename_len = strlen(filename);
#ifdef GIT_USE_ICONV
if ((diriter->flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
(error = git_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
return error;
#endif
git_buf_truncate(&diriter->path, diriter->parent_len);
if (diriter->parent_len > 0 &&
diriter->path.ptr[diriter->parent_len-1] != '/')
git_buf_putc(&diriter->path, '/');
git_buf_put(&diriter->path, filename, filename_len);
if (git_buf_oom(&diriter->path))
return -1;
return error;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path.size > diriter->parent_len);
*out = &diriter->path.ptr[diriter->parent_len+1];
*out_len = diriter->path.size - diriter->parent_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path.ptr;
*out_len = diriter->path.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_path_lstat(diriter->path.ptr, out);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
if (diriter->dir) {
closedir(diriter->dir);
diriter->dir = NULL;
}
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&diriter->ic);
#endif
git_buf_dispose(&diriter->path);
}
#endif
int git_path_dirload(
git_vector *contents,
const char *path,
size_t prefix_len,
uint32_t flags)
{
git_path_diriter iter = GIT_PATH_DIRITER_INIT;
const char *name;
size_t name_len;
char *dup;
int error;
assert(contents && path);
if ((error = git_path_diriter_init(&iter, path, flags)) < 0)
return error;
while ((error = git_path_diriter_next(&iter)) == 0) {
if ((error = git_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
break;
assert(name_len > prefix_len);
dup = git__strndup(name + prefix_len, name_len - prefix_len);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(contents, dup)) < 0)
break;
}
if (error == GIT_ITEROVER)
error = 0;
git_path_diriter_free(&iter);
return error;
}
int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path)
{
if (git_path_is_local_file_url(url_or_path))
return git_path_fromurl(local_path_out, url_or_path);
else
return git_buf_sets(local_path_out, url_or_path);
}
/* Reject paths like AUX or COM1, or those versions that end in a dot or
* colon. ("AUX." or "AUX:")
*/
GIT_INLINE(bool) verify_dospath(
const char *component,
size_t len,
const char dospath[3],
bool trailing_num)
{
size_t last = trailing_num ? 4 : 3;
if (len < last || git__strncasecmp(component, dospath, 3) != 0)
return true;
if (trailing_num && (component[3] < '1' || component[3] > '9'))
return true;
return (len > last &&
component[last] != '.' &&
component[last] != ':');
}
static int32_t next_hfs_char(const char **in, size_t *len)
{
while (*len) {
int32_t codepoint;
int cp_len = git__utf8_iterate((const uint8_t *)(*in), (int)(*len), &codepoint);
if (cp_len < 0)
return -1;
(*in) += cp_len;
(*len) -= cp_len;
/* these code points are ignored completely */
switch (codepoint) {
case 0x200c: /* ZERO WIDTH NON-JOINER */
case 0x200d: /* ZERO WIDTH JOINER */
case 0x200e: /* LEFT-TO-RIGHT MARK */
case 0x200f: /* RIGHT-TO-LEFT MARK */
case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
case 0x202c: /* POP DIRECTIONAL FORMATTING */
case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
case 0x206e: /* NATIONAL DIGIT SHAPES */
case 0x206f: /* NOMINAL DIGIT SHAPES */
case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
continue;
}
/* fold into lowercase -- this will only fold characters in
* the ASCII range, which is perfectly fine, because the
* git folder name can only be composed of ascii characters
*/
return git__tolower(codepoint);
}
return 0; /* NULL byte -- end of string */
}
static bool verify_dotgit_hfs_generic(const char *path, size_t len, const char *needle, size_t needle_len)
{
size_t i;
char c;
if (next_hfs_char(&path, &len) != '.')
return true;
for (i = 0; i < needle_len; i++) {
c = next_hfs_char(&path, &len);
if (c != needle[i])
return true;
}
if (next_hfs_char(&path, &len) != '\0')
return true;
return false;
}
static bool verify_dotgit_hfs(const char *path, size_t len)
{
return verify_dotgit_hfs_generic(path, len, "git", CONST_STRLEN("git"));
}
GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)
{
git_buf *reserved = git_repository__reserved_names_win32;
size_t reserved_len = git_repository__reserved_names_win32_len;
size_t start = 0, i;
if (repo)
git_repository__reserved_names(&reserved, &reserved_len, repo, true);
for (i = 0; i < reserved_len; i++) {
git_buf *r = &reserved[i];
if (len >= r->size &&
strncasecmp(path, r->ptr, r->size) == 0) {
start = r->size;
break;
}
}
if (!start)
return true;
/* Reject paths like ".git\" */
if (path[start] == '\\')
return false;
/* Reject paths like '.git ' or '.git.' */
for (i = start; i < len; i++) {
if (path[i] != ' ' && path[i] != '.')
return true;
}
return false;
}
GIT_INLINE(bool) only_spaces_and_dots(const char *path)
{
const char *c = path;
for (;; c++) {
if (*c == '\0')
return true;
if (*c != ' ' && *c != '.')
return false;
}
return true;
}
GIT_INLINE(bool) verify_dotgit_ntfs_generic(const char *name, size_t len, const char *dotgit_name, size_t dotgit_len, const char *shortname_pfix)
{
int i, saw_tilde;
if (name[0] == '.' && len >= dotgit_len &&
!strncasecmp(name + 1, dotgit_name, dotgit_len)) {
return !only_spaces_and_dots(name + dotgit_len + 1);
}
/* Detect the basic NTFS shortname with the first six chars */
if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
name[7] >= '1' && name[7] <= '4')
return !only_spaces_and_dots(name + 8);
/* Catch fallback names */
for (i = 0, saw_tilde = 0; i < 8; i++) {
if (name[i] == '\0') {
return true;
} else if (saw_tilde) {
if (name[i] < '0' || name[i] > '9')
return true;
} else if (name[i] == '~') {
if (name[i+1] < '1' || name[i+1] > '9')
return true;
saw_tilde = 1;
} else if (i >= 6) {
return true;
} else if ((unsigned char)name[i] > 127) {
return true;
} else if (git__tolower(name[i]) != shortname_pfix[i]) {
return true;
}
}
return !only_spaces_and_dots(name + i);
}
GIT_INLINE(bool) verify_char(unsigned char c, unsigned int flags)
{
if ((flags & GIT_PATH_REJECT_BACKSLASH) && c == '\\')
return false;
if ((flags & GIT_PATH_REJECT_SLASH) && c == '/')
return false;
if (flags & GIT_PATH_REJECT_NT_CHARS) {
if (c < 32)
return false;
switch (c) {
case '<':
case '>':
case ':':
case '"':
case '|':
case '?':
case '*':
return false;
}
}
return true;
}
/*
* Return the length of the common prefix between str and prefix, comparing them
* case-insensitively (must be ASCII to match).
*/
GIT_INLINE(size_t) common_prefix_icase(const char *str, size_t len, const char *prefix)
{
size_t count = 0;
while (len >0 && tolower(*str) == tolower(*prefix)) {
count++;
str++;
prefix++;
len--;
}
return count;
}
/*
* We fundamentally don't like some paths when dealing with user-inputted
* strings (in checkout or ref names): we don't want dot or dot-dot
* anywhere, we want to avoid writing weird paths on Windows that can't
* be handled by tools that use the non-\\?\ APIs, we don't want slashes
* or double slashes at the end of paths that can make them ambiguous.
*
* For checkout, we don't want to recurse into ".git" either.
*/
static bool verify_component(
git_repository *repo,
const char *component,
size_t len,
uint16_t mode,
unsigned int flags)
{
if (len == 0)
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 1 && component[0] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 2 && component[0] == '.' && component[1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_DOT) && component[len-1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_SPACE) && component[len-1] == ' ')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_COLON) && component[len-1] == ':')
return false;
if (flags & GIT_PATH_REJECT_DOS_PATHS) {
if (!verify_dospath(component, len, "CON", false) ||
!verify_dospath(component, len, "PRN", false) ||
!verify_dospath(component, len, "AUX", false) ||
!verify_dospath(component, len, "NUL", false) ||
!verify_dospath(component, len, "COM", true) ||
!verify_dospath(component, len, "LPT", true))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_HFS) {
if (!verify_dotgit_hfs(component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_HFS))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_NTFS) {
if (!verify_dotgit_ntfs(repo, component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_NTFS))
return false;
}
/* don't bother rerunning the `.git` test if we ran the HFS or NTFS
* specific tests, they would have already rejected `.git`.
*/
if ((flags & GIT_PATH_REJECT_DOT_GIT_HFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_NTFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_LITERAL)) {
if (len >= 4 &&
component[0] == '.' &&
(component[1] == 'g' || component[1] == 'G') &&
(component[2] == 'i' || component[2] == 'I') &&
(component[3] == 't' || component[3] == 'T')) {
if (len == 4)
return false;
if (S_ISLNK(mode) && common_prefix_icase(component, len, ".gitmodules") == len)
return false;
}
}
return true;
}
GIT_INLINE(unsigned int) dotgit_flags(
git_repository *repo,
unsigned int flags)
{
int protectHFS = 0, protectNTFS = 0;
int error = 0;
flags |= GIT_PATH_REJECT_DOT_GIT_LITERAL;
#ifdef __APPLE__
protectHFS = 1;
#endif
#ifdef GIT_WIN32
protectNTFS = 1;
#endif
if (repo && !protectHFS)
error = git_repository__configmap_lookup(&protectHFS, repo, GIT_CONFIGMAP_PROTECTHFS);
if (!error && protectHFS)
flags |= GIT_PATH_REJECT_DOT_GIT_HFS;
if (repo && !protectNTFS)
error = git_repository__configmap_lookup(&protectNTFS, repo, GIT_CONFIGMAP_PROTECTNTFS);
if (!error && protectNTFS)
flags |= GIT_PATH_REJECT_DOT_GIT_NTFS;
return flags;
}
bool git_path_isvalid(
git_repository *repo,
const char *path,
uint16_t mode,
unsigned int flags)
{
const char *start, *c;
/* Upgrade the ".git" checks based on platform */
if ((flags & GIT_PATH_REJECT_DOT_GIT))
flags = dotgit_flags(repo, flags);
for (start = c = path; *c; c++) {
if (!verify_char(*c, flags))
return false;
if (*c == '/') {
if (!verify_component(repo, start, (c - start), mode, flags))
return false;
start = c+1;
}
}
return verify_component(repo, start, (c - start), mode, flags);
}
int git_path_normalize_slashes(git_buf *out, const char *path)
{
int error;
char *p;
if ((error = git_buf_puts(out, path)) < 0)
return error;
for (p = out->ptr; *p; p++) {
if (*p == '\\')
*p = '/';
}
return 0;
}
static const struct {
const char *file;
const char *hash;
size_t filelen;
} gitfiles[] = {
{ "gitignore", "gi250a", CONST_STRLEN("gitignore") },
{ "gitmodules", "gi7eba", CONST_STRLEN("gitmodules") },
{ "gitattributes", "gi7d29", CONST_STRLEN("gitattributes") }
};
extern int git_path_is_gitfile(const char *path, size_t pathlen, git_path_gitfile gitfile, git_path_fs fs)
{
const char *file, *hash;
size_t filelen;
if (!(gitfile >= GIT_PATH_GITFILE_GITIGNORE && gitfile < ARRAY_SIZE(gitfiles))) {
git_error_set(GIT_ERROR_OS, "invalid gitfile for path validation");
return -1;
}
file = gitfiles[gitfile].file;
filelen = gitfiles[gitfile].filelen;
hash = gitfiles[gitfile].hash;
switch (fs) {
case GIT_PATH_FS_GENERIC:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash) ||
!verify_dotgit_hfs_generic(path, pathlen, file, filelen);
case GIT_PATH_FS_NTFS:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash);
case GIT_PATH_FS_HFS:
return !verify_dotgit_hfs_generic(path, pathlen, file, filelen);
default:
git_error_set(GIT_ERROR_OS, "invalid filesystem for path validation");
return -1;
}
}
bool git_path_supports_symlinks(const char *dir)
{
git_buf path = GIT_BUF_INIT;
bool supported = false;
struct stat st;
int fd;
if ((fd = git_futils_mktmp(&path, dir, 0666)) < 0 ||
p_close(fd) < 0 ||
p_unlink(path.ptr) < 0 ||
p_symlink("testing", path.ptr) < 0 ||
p_lstat(path.ptr, &st) < 0)
goto done;
supported = (S_ISLNK(st.st_mode) != 0);
done:
if (path.size)
(void)p_unlink(path.ptr);
git_buf_dispose(&path);
return supported;
}
int git_path_validate_system_file_ownership(const char *path)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
return GIT_OK;
#else
git_win32_path buf;
PSID owner_sid;
PSECURITY_DESCRIPTOR descriptor = NULL;
HANDLE token;
TOKEN_USER *info = NULL;
DWORD err, len;
int ret;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
err = GetNamedSecurityInfoW(buf, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION,
&owner_sid, NULL, NULL, NULL, &descriptor);
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
ret = GIT_ENOTFOUND;
goto cleanup;
}
if (err != ERROR_SUCCESS) {
git_error_set(GIT_ERROR_OS, "failed to get security information");
ret = GIT_ERROR;
goto cleanup;
}
if (!IsValidSid(owner_sid)) {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is unknown");
ret = GIT_ERROR;
goto cleanup;
}
if (IsWellKnownSid(owner_sid, WinBuiltinAdministratorsSid) ||
IsWellKnownSid(owner_sid, WinLocalSystemSid)) {
ret = GIT_OK;
goto cleanup;
}
/* Obtain current user's SID */
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
info = git__malloc(len);
GIT_ERROR_CHECK_ALLOC(info);
if (!GetTokenInformation(token, TokenUser, info, len, &len)) {
git__free(info);
info = NULL;
}
}
/*
* If the file is owned by the same account that is running the current
* process, it's okay to read from that file.
*/
if (info && EqualSid(owner_sid, info->User.Sid))
ret = GIT_OK;
else {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is not valid");
ret = GIT_ERROR;
}
free(info);
cleanup:
if (descriptor)
LocalFree(descriptor);
return ret;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3987_0 |
crossvul-cpp_data_bad_4701_0 | /*
network-ssl.c : SSL support
Copyright (C) 2002 vjt
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "module.h"
#include "network.h"
#include "misc.h"
#ifdef HAVE_OPENSSL
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
/* ssl i/o channel object */
typedef struct
{
GIOChannel pad;
gint fd;
GIOChannel *giochan;
SSL *ssl;
SSL_CTX *ctx;
unsigned int verify:1;
} GIOSSLChannel;
static SSL_CTX *ssl_ctx = NULL;
static void irssi_ssl_free(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
g_io_channel_unref(chan->giochan);
SSL_free(chan->ssl);
if (chan->ctx != ssl_ctx)
SSL_CTX_free(chan->ctx);
g_free(chan);
}
static gboolean irssi_ssl_verify(SSL *ssl, SSL_CTX *ctx, X509 *cert)
{
if (SSL_get_verify_result(ssl) != X509_V_OK) {
unsigned char md[EVP_MAX_MD_SIZE];
unsigned int n;
char *str;
g_warning("Could not verify SSL servers certificate:");
if ((str = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0)) == NULL)
g_warning(" Could not get subject-name from peer certificate");
else {
g_warning(" Subject : %s", str);
free(str);
}
if ((str = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0)) == NULL)
g_warning(" Could not get issuer-name from peer certificate");
else {
g_warning(" Issuer : %s", str);
free(str);
}
if (! X509_digest(cert, EVP_md5(), md, &n))
g_warning(" Could not get fingerprint from peer certificate");
else {
char hex[] = "0123456789ABCDEF";
char fp[EVP_MAX_MD_SIZE*3];
if (n < sizeof(fp)) {
unsigned int i;
for (i = 0; i < n; i++) {
fp[i*3+0] = hex[(md[i] >> 4) & 0xF];
fp[i*3+1] = hex[(md[i] >> 0) & 0xF];
fp[i*3+2] = i == n - 1 ? '\0' : ':';
}
g_warning(" MD5 Fingerprint : %s", fp);
}
}
return FALSE;
}
return TRUE;
}
static GIOStatus irssi_ssl_read(GIOChannel *handle, gchar *buf, gsize len, gsize *ret, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
gint ret1, err;
const char *errstr;
ret1 = SSL_read(chan->ssl, buf, len);
if(ret1 <= 0)
{
*ret = 0;
err = SSL_get_error(chan->ssl, ret1);
if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
return G_IO_STATUS_AGAIN;
else if(err == SSL_ERROR_ZERO_RETURN)
return G_IO_STATUS_EOF;
else if (err == SSL_ERROR_SYSCALL)
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret1 == -1)
errstr = strerror(errno);
if (errstr == NULL)
errstr = "server closed connection unexpectedly";
}
else
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL)
errstr = "unknown SSL error";
}
g_warning("SSL read error: %s", errstr);
*gerr = g_error_new_literal(G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED,
errstr);
return G_IO_STATUS_ERROR;
}
else
{
*ret = ret1;
return G_IO_STATUS_NORMAL;
}
/*UNREACH*/
return G_IO_STATUS_ERROR;
}
static GIOStatus irssi_ssl_write(GIOChannel *handle, const gchar *buf, gsize len, gsize *ret, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
gint ret1, err;
const char *errstr;
ret1 = SSL_write(chan->ssl, (const char *)buf, len);
if(ret1 <= 0)
{
*ret = 0;
err = SSL_get_error(chan->ssl, ret1);
if(err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE)
return G_IO_STATUS_AGAIN;
else if(err == SSL_ERROR_ZERO_RETURN)
errstr = "server closed connection";
else if (err == SSL_ERROR_SYSCALL)
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret1 == -1)
errstr = strerror(errno);
if (errstr == NULL)
errstr = "server closed connection unexpectedly";
}
else
{
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL)
errstr = "unknown SSL error";
}
g_warning("SSL write error: %s", errstr);
*gerr = g_error_new_literal(G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED,
errstr);
return G_IO_STATUS_ERROR;
}
else
{
*ret = ret1;
return G_IO_STATUS_NORMAL;
}
/*UNREACH*/
return G_IO_STATUS_ERROR;
}
static GIOStatus irssi_ssl_seek(GIOChannel *handle, gint64 offset, GSeekType type, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_seek(handle, offset, type, gerr);
}
static GIOStatus irssi_ssl_close(GIOChannel *handle, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_close(handle, gerr);
}
static GSource *irssi_ssl_create_watch(GIOChannel *handle, GIOCondition cond)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_create_watch(handle, cond);
}
static GIOStatus irssi_ssl_set_flags(GIOChannel *handle, GIOFlags flags, GError **gerr)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_set_flags(handle, flags, gerr);
}
static GIOFlags irssi_ssl_get_flags(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
return chan->giochan->funcs->io_get_flags(handle);
}
static GIOFuncs irssi_ssl_channel_funcs = {
irssi_ssl_read,
irssi_ssl_write,
irssi_ssl_seek,
irssi_ssl_close,
irssi_ssl_create_watch,
irssi_ssl_free,
irssi_ssl_set_flags,
irssi_ssl_get_flags
};
static gboolean irssi_ssl_init(void)
{
SSL_library_init();
SSL_load_error_strings();
ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if(!ssl_ctx)
{
g_error("Initialization of the SSL library failed");
return FALSE;
}
return TRUE;
}
static GIOChannel *irssi_ssl_get_iochannel(GIOChannel *handle, const char *mycert, const char *mypkey, const char *cafile, const char *capath, gboolean verify)
{
GIOSSLChannel *chan;
GIOChannel *gchan;
int fd;
SSL *ssl;
SSL_CTX *ctx = NULL;
g_return_val_if_fail(handle != NULL, NULL);
if(!ssl_ctx && !irssi_ssl_init())
return NULL;
if(!(fd = g_io_channel_unix_get_fd(handle)))
return NULL;
if (mycert && *mycert) {
char *scert = NULL, *spkey = NULL;
if ((ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
scert = convert_home(mycert);
if (mypkey && *mypkey)
spkey = convert_home(mypkey);
if (! SSL_CTX_use_certificate_file(ctx, scert, SSL_FILETYPE_PEM))
g_warning("Loading of client certificate '%s' failed", mycert);
else if (! SSL_CTX_use_PrivateKey_file(ctx, spkey ? spkey : scert, SSL_FILETYPE_PEM))
g_warning("Loading of private key '%s' failed", mypkey ? mypkey : mycert);
else if (! SSL_CTX_check_private_key(ctx))
g_warning("Private key does not match the certificate");
g_free(scert);
g_free(spkey);
}
if ((cafile && *cafile) || (capath && *capath)) {
char *scafile = NULL;
char *scapath = NULL;
if (! ctx && (ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
g_error("Could not allocate memory for SSL context");
return NULL;
}
if (cafile && *cafile)
scafile = convert_home(cafile);
if (capath && *capath)
scapath = convert_home(capath);
if (! SSL_CTX_load_verify_locations(ctx, scafile, scapath)) {
g_warning("Could not load CA list for verifying SSL server certificate");
g_free(scafile);
g_free(scapath);
SSL_CTX_free(ctx);
return NULL;
}
g_free(scafile);
g_free(scapath);
verify = TRUE;
}
if (ctx == NULL)
ctx = ssl_ctx;
if(!(ssl = SSL_new(ctx)))
{
g_warning("Failed to allocate SSL structure");
return NULL;
}
if(!SSL_set_fd(ssl, fd))
{
g_warning("Failed to associate socket to SSL stream");
SSL_free(ssl);
if (ctx != ssl_ctx)
SSL_CTX_free(ctx);
return NULL;
}
SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE |
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
chan = g_new0(GIOSSLChannel, 1);
chan->fd = fd;
chan->giochan = handle;
chan->ssl = ssl;
chan->ctx = ctx;
chan->verify = verify;
gchan = (GIOChannel *)chan;
gchan->funcs = &irssi_ssl_channel_funcs;
g_io_channel_init(gchan);
gchan->is_readable = gchan->is_writeable = TRUE;
gchan->use_buffer = FALSE;
return gchan;
}
GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)
{
GIOChannel *handle, *ssl_handle;
handle = net_connect_ip(ip, port, my_ip);
if (handle == NULL)
return NULL;
ssl_handle = irssi_ssl_get_iochannel(handle, cert, pkey, cafile, capath, verify);
if (ssl_handle == NULL)
g_io_channel_unref(handle);
return ssl_handle;
}
int irssi_ssl_handshake(GIOChannel *handle)
{
GIOSSLChannel *chan = (GIOSSLChannel *)handle;
int ret, err;
X509 *cert;
const char *errstr;
ret = SSL_connect(chan->ssl);
if (ret <= 0) {
err = SSL_get_error(chan->ssl, ret);
switch (err) {
case SSL_ERROR_WANT_READ:
return 1;
case SSL_ERROR_WANT_WRITE:
return 3;
case SSL_ERROR_ZERO_RETURN:
g_warning("SSL handshake failed: %s", "server closed connection");
return -1;
case SSL_ERROR_SYSCALL:
errstr = ERR_reason_error_string(ERR_get_error());
if (errstr == NULL && ret == -1)
errstr = strerror(errno);
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "server closed connection unexpectedly");
return -1;
default:
errstr = ERR_reason_error_string(ERR_get_error());
g_warning("SSL handshake failed: %s", errstr != NULL ? errstr : "unknown SSL error");
return -1;
}
}
cert = SSL_get_peer_certificate(chan->ssl);
if (cert == NULL) {
g_warning("SSL server supplied no certificate");
return -1;
}
ret = !chan->verify || irssi_ssl_verify(chan->ssl, chan->ctx, cert);
X509_free(cert);
return ret ? 0 : -1;
}
#else /* HAVE_OPENSSL */
GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify)
{
g_warning("Connection failed: SSL support not enabled in this build.");
errno = ENOSYS;
return NULL;
}
#endif /* ! HAVE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4701_0 |
crossvul-cpp_data_bad_5105_0 | /* airpdcap.c
*
* Copyright (c) 2006 CACE Technologies, Davis (California)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* The files matching airpcap*.[ch] were originally developed as part of
* Wireshark's support for AirPcap adapters. However, they've been used
* for general 802.11 decryption for quite some time. It might make sense
* to rename them accordingly.
*/
/****************************************************************************/
/* File includes */
#include "config.h"
#include <glib.h>
#include <wsutil/crc32.h>
#include <wsutil/rc4.h>
#include <wsutil/sha1.h>
#include <wsutil/sha2.h>
#include <wsutil/md5.h>
#include <wsutil/pint.h>
#include <wsutil/aes.h>
#include <epan/tvbuff.h>
#include <epan/to_str.h>
#include <epan/strutil.h>
#include <epan/crypt/airpdcap_rijndael.h>
#include "airpdcap_system.h"
#include "airpdcap_int.h"
#include "airpdcap_debug.h"
#include "wep-wpadefs.h"
/****************************************************************************/
/****************************************************************************/
/* Constant definitions */
/* EAPOL definitions */
/**
* Length of the EAPOL-Key key confirmation key (KCK) used to calculate
* MIC over EAPOL frame and validate an EAPOL packet (128 bits)
*/
#define AIRPDCAP_WPA_KCK_LEN 16
/**
*Offset of the Key MIC in the EAPOL packet body
*/
#define AIRPDCAP_WPA_MICKEY_OFFSET 77
/**
* Maximum length of the EAPOL packet (it depends on the maximum MAC
* frame size)
*/
#define AIRPDCAP_WPA_MAX_EAPOL_LEN 4095
/**
* EAPOL Key Descriptor Version 1, used for all EAPOL-Key frames to and
* from a STA when neither the group nor pairwise ciphers are CCMP for
* Key Descriptor 1.
* @note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_NOT_CCMP 1
/**
* EAPOL Key Descriptor Version 2, used for all EAPOL-Key frames to and
* from a STA when either the pairwise or the group cipher is AES-CCMP
* for Key Descriptor 2.
* /note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_AES_CCMP 2
/** Define EAPOL Key Descriptor type values: use 254 for WPA and 2 for WPA2 **/
#define AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR 254
#define AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR 2
/****************************************************************************/
/****************************************************************************/
/* Macro definitions */
extern const UINT32 crc32_table[256];
#define CRC(crc, ch) (crc = (crc >> 8) ^ crc32_table[(crc ^ (ch)) & 0xff])
#define AIRPDCAP_GET_TK(ptk) (ptk + 32)
/****************************************************************************/
/****************************************************************************/
/* Type definitions */
/* Internal function prototype declarations */
#ifdef __cplusplus
extern "C" {
#endif
/**
* It is a step of the PBKDF2 (specifically the PKCS #5 v2.0) defined in
* the RFC 2898 to derive a key (used as PMK in WPA)
* @param ppbytes [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param iterations [IN] times to hash the password (4096 for WPA)
* @param count [IN] ???
* @param output [OUT] pointer to a preallocated buffer of
* SHA1_DIGEST_LEN characters that will contain a part of the key
*/
static INT AirPDcapRsnaPwd2PskStep(
const guint8 *ppbytes,
const guint passLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
;
/**
* It calculates the passphrase-to-PSK mapping reccomanded for use with
* RSNAs. This implementation uses the PBKDF2 method defined in the RFC
* 2898.
* @param passphrase [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param output [OUT] calculated PSK (to use as PMK in WPA)
* @note
* Described in 802.11i-2004, page 165
*/
static INT AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
;
static INT AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
;
/**
* It checks whether the specified key is corrected or not.
* @note
* For a standard WEP key the length will be changed to the standard
* length, and the type changed in a generic WEP key.
* @param key [IN] pointer to the key to validate
* @return
* - TRUE: the key contains valid fields and values
* - FALSE: the key has some invalid field or value
*/
static INT AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
;
static INT AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
;
/**
* @param ctx [IN] pointer to the current context
* @param id [IN] id of the association (composed by BSSID and MAC of
* the station)
* @return
* - index of the Security Association structure if found
* - -1, if the specified addresses pair BSSID-STA MAC has not been found
*/
static INT AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static const UCHAR * AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static const UCHAR * AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static void AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
;
/**
* @param sa [IN/OUT] pointer to SA that will hold the key
* @param data [IN] Frame
* @param offset_rsne [IN] RSNE IE offset in the frame
* @param offset_fte [IN] Fast BSS Transition IE offset in the frame
* @param offset_timeout [IN] Timeout Interval IE offset in the frame
* @param offset_link [IN] Link Identifier IE offset in the frame
* @param action [IN] Tdls Action code (response or confirm)
*
* @return
* AIRPDCAP_RET_SUCCESS if Key has been sucessfully derived (and MIC verified)
* AIRPDCAP_RET_UNSUCCESS otherwise
*/
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
;
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Exported function definitions */
#ifdef __cplusplus
extern "C" {
#endif
const guint8 broadcast_mac[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
#define EAPKEY_MIC_LEN 16 /* length of the MIC key for EAPoL_Key packet's MIC using MD5 */
#define NONCE_LEN 32
#define TKIP_GROUP_KEY_LEN 32
#define CCMP_GROUP_KEY_LEN 16
typedef struct {
guint8 type;
guint8 key_information[2]; /* Make this an array to avoid alignment issues */
guint8 key_length[2]; /* Make this an array to avoid alignment issues */
guint8 replay_counter[8];
guint8 key_nonce[NONCE_LEN];
guint8 key_iv[16];
guint8 key_sequence_counter[8]; /* also called the RSC */
guint8 key_id[8];
guint8 key_mic[EAPKEY_MIC_LEN];
guint8 key_data_len[2]; /* Make this an array rather than a U16 to avoid alignment shifting */
} EAPOL_RSN_KEY, * P_EAPOL_RSN_KEY;
/* Minimum possible key data size (at least one GTK KDE with CCMP key) */
#define GROUP_KEY_MIN_LEN 8 + CCMP_GROUP_KEY_LEN
/* Minimum possible group key msg size (group key msg using CCMP as cipher)*/
#define GROUP_KEY_PAYLOAD_LEN_MIN sizeof(EAPOL_RSN_KEY) + GROUP_KEY_MIN_LEN
/* XXX - what if this doesn't get the key? */
static INT
AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len)
{
guint8 key_version;
guint8 *key_data;
guint8 *szEncryptedKey;
guint16 key_bytes_len = 0; /* Length of the total key data field */
guint16 key_len; /* Actual group key length */
static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
/* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */
/* Preparation for decrypting the group key - determine group key data length */
/* depending on whether the pairwise key is TKIP or AES encryption key */
key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]);
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
/* TKIP */
key_bytes_len = pntoh16(pEAPKey->key_length);
}else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES */
key_bytes_len = pntoh16(pEAPKey->key_data_len);
/* AES keys must be at least 128 bits = 16 bytes. */
if (key_bytes_len < 16) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
}
if ((key_bytes_len < GROUP_KEY_MIN_LEN) ||
(eapol_len < sizeof(EAPOL_RSN_KEY)) ||
(key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Encrypted key is in the information element field of the EAPOL key packet */
key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY);
szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len);
DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len);
DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16);
DEBUG_DUMP("decryption_key:", decryption_key, 16);
/* We are rekeying, save old sa */
tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION));
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
/* As we have no concept of the prior association request at this point, we need to deduce the */
/* group key cipher from the length of the key bytes. In WPA this is straightforward as the */
/* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */
/* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */
/* does not. Also there are other (variable length) items in the keybytes which we need to account */
/* for to determine the true key length, and thus the group cipher. */
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
guint8 new_key[32];
guint8 dummy[256];
/* TKIP key */
/* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */
/* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */
rc4_state_struct rc4_state;
/* The WPA group key just contains the GTK bytes so deducing the type is straightforward */
/* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */
sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP;
/* Build the full decryption key based on the IV and part of the pairwise key */
memcpy(new_key, pEAPKey->key_iv, 16);
memcpy(new_key+16, decryption_key, 16);
DEBUG_DUMP("FullDecrKey:", new_key, 32);
crypt_rc4_init(&rc4_state, new_key, sizeof(new_key));
/* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */
crypt_rc4(&rc4_state, dummy, 256);
crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len);
} else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES CCMP key */
guint8 key_found;
guint8 key_length;
guint16 key_index;
guint8 *decrypted_data;
/* Unwrap the key; the result is key_bytes_len in length */
decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len);
/* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure.
The key itself is stored as a GTK KDE
WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to
pass pointer to the actual key with 8 bytes offset */
key_found = FALSE;
key_index = 0;
/* Parse Key data until we found GTK KDE */
/* GTK KDE = 00-0F-AC 01 */
while(key_index < (key_bytes_len - 6) && !key_found){
guint8 rsn_id;
guint32 type;
/* Get RSN ID */
rsn_id = decrypted_data[key_index];
type = ((decrypted_data[key_index + 2] << 24) +
(decrypted_data[key_index + 3] << 16) +
(decrypted_data[key_index + 4] << 8) +
(decrypted_data[key_index + 5]));
if (rsn_id == 0xdd && type == 0x000fac01) {
key_found = TRUE;
} else {
key_index += decrypted_data[key_index+1]+2;
}
}
if (key_found){
key_length = decrypted_data[key_index+1] - 6;
if (key_index+8 >= key_bytes_len ||
key_length > key_bytes_len - key_index - 8) {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Skip over the GTK header info, and don't copy past the end of the encrypted data */
memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length);
} else {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
if (key_length == TKIP_GROUP_KEY_LEN)
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP;
else
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
g_free(decrypted_data);
}
key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN;
if (key_len > key_bytes_len) {
/* the key required for this protocol is longer than the key that we just calculated */
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Decrypted key is now in szEncryptedKey with len of key_len */
DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len);
/* Load the proper key material info into the SA */
sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */
sa->validKey = TRUE;
/* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */
/* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */
memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk));
memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len);
g_free(szEncryptedKey);
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* Return a pointer the the requested SA. If it doesn't exist create it. */
static PAIRPDCAP_SEC_ASSOCIATION
AirPDcapGetSaPtr(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
int sa_index;
/* search for a cached Security Association for supplied BSSID and STA MAC */
if ((sa_index=AirPDcapGetSa(ctx, id))==-1) {
/* create a new Security Association if it doesn't currently exist */
if ((sa_index=AirPDcapStoreSa(ctx, id))==-1) {
return NULL;
}
}
/* get the Security Association structure */
return &ctx->sa[sa_index];
}
static INT AirPDcapScanForKeys(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
AIRPDCAP_SEC_ASSOCIATION_ID id
)
{
const UCHAR *addr;
guint bodyLength;
PAIRPDCAP_SEC_ASSOCIATION sta_sa;
PAIRPDCAP_SEC_ASSOCIATION sa;
guint offset = 0;
const guint8 dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x88, 0x8E /* Type: 802.1X authentication */
};
const guint8 bt_dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */
0x00, 0x03 /* Type: Bluetooth Security */
};
const guint8 tdls_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */
0x02, /* Payload Type: TDLS */
0X0C /* Action Category: TDLS */
};
const EAPOL_RSN_KEY *pEAPKey;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapScanForKeys");
/* cache offset in the packet data */
offset = mac_header_len;
/* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */
if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=8;
/* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */
if (data[offset+1]!=3) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not EAPOL-Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* get and check the body length (IEEE 802.1X-2004, pg. 25) */
bodyLength=pntoh16(data+offset+2);
if ((tot_len-offset-4) < bodyLength) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "EAPOL body too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip EAPOL MPDU and go to the first byte of the body */
offset+=4;
pEAPKey = (const EAPOL_RSN_KEY *) (data+offset);
/* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */
if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */
pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */
pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not valid key descriptor type", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* start with descriptor body */
offset+=1;
/* search for a cached Security Association for current BSSID and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "No SA for BSSID found", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_REQ_DATA;
}
/* It could be a Pairwise Key exchange, check */
if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE)
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Message too short for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 ||
AIRPDCAP_EAP_ACK(data[offset+1])!=1 ||
AIRPDCAP_EAP_MIC(data[offset]) != 1 ||
AIRPDCAP_EAP_SEC(data[offset]) != 1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Key bitfields not correct for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* force STA address to be the broadcast MAC so we create an SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
/* get the Security Association structure for the broadcast MAC and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */
/* get STA address */
if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) {
memcpy(id.sta, addr, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
#endif
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "SA not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
sta_sa = AirPDcapGetSaPtr(ctx, &id);
if (sta_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Try to extract the group key and install it in the SA */
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1));
} else if (memcmp(data+offset, tdls_header, 10) == 0) {
const guint8 *initiator, *responder;
guint8 action;
guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: TDLS Action Frame", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=10;
/* check if the packet is a TDLS response or confirm */
action = data[offset];
if (action!=1 && action!=2) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not Response nor confirm", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* check status */
offset++;
status=pntoh16(data+offset);
if (status!=0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "TDLS setup not successfull", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip Token + capabilities */
offset+=5;
/* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */
while(offset < (tot_len - 2)) {
if (data[offset] == 48) {
offset_rsne = offset;
} else if (data[offset] == 55) {
offset_fte = offset;
} else if (data[offset] == 56) {
offset_timeout = offset;
} else if (data[offset] == 101) {
offset_link = offset;
}
if (tot_len < offset + data[offset + 1] + 2) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
offset += data[offset + 1] + 2;
}
if (offset_rsne == 0 || offset_fte == 0 ||
offset_timeout == 0 || offset_link == 0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Cannot Find all necessary IEs", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Found RSNE/Fast BSS/Timeout Interval/Link IEs", AIRPDCAP_DEBUG_LEVEL_3);
/* Will create a Security Association between 2 STA. Need to get both MAC address */
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN);
} else {
memcpy(id.sta, responder, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN);
}
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
if (sa->validKey) {
if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) {
/* Already have valid key for this SA, no need to redo key derivation */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* We are opening a new session with the same two STA, save previous sa */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
sa->validKey = FALSE;
}
}
if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action)
== AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Skipping: not an EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
INT AirPDcapPacketProcess(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
UCHAR *decrypt_data,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
gboolean scanHandshake)
{
AIRPDCAP_SEC_ASSOCIATION_ID id;
UCHAR tmp_data[AIRPDCAP_MAX_CAPLEN];
guint tmp_len;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapPacketProcess");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
if (data==NULL || tot_len==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL data or length=0", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
/* check if the packet is of data or robust managment type */
if (!((AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_DATA) ||
(AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_MANAGEMENT &&
(AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DISASS ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DEAUTHENTICATION ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_ACTION)))) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "not data nor robust mgmt packet", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_DATA;
}
/* check correct packet size, to avoid wrong elaboration of encryption algorithms */
if (tot_len < (UINT)(mac_header_len+AIRPDCAP_CRYPTED_DATA_MINLEN)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "minimum length violated", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_WRONG_DATA_SIZE;
}
/* Assume that the decrypt_data field is at least this size. */
if (tot_len > AIRPDCAP_MAX_CAPLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "length too large", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* get STA/BSSID address */
if (AirPDcapGetSaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data), &id) != AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "STA/BSSID not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
/* check if data is encrypted (use the WEP bit in the Frame Control field) */
if (AIRPDCAP_WEP(data[1])==0) {
if (scanHandshake) {
/* data is sent in cleartext, check if is an authentication message or end the process */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Unencrypted data", AIRPDCAP_DEBUG_LEVEL_3);
return (AirPDcapScanForKeys(ctx, data, mac_header_len, tot_len, id));
}
return AIRPDCAP_RET_NO_DATA_ENCRYPTED;
} else {
PAIRPDCAP_SEC_ASSOCIATION sa;
int offset = 0;
/* get the Security Association structure for the STA and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* cache offset in the packet data (to scan encryption data) */
offset = mac_header_len;
if (decrypt_data==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "no decrypt buffer, use local", AIRPDCAP_DEBUG_LEVEL_3);
decrypt_data=tmp_data;
decrypt_len=&tmp_len;
}
/* create new header and data to modify */
*decrypt_len = tot_len;
memcpy(decrypt_data, data, *decrypt_len);
/* encrypted data */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Encrypted data", AIRPDCAP_DEBUG_LEVEL_3);
/* check the Extension IV to distinguish between WEP encryption and WPA encryption */
/* refer to IEEE 802.11i-2004, 8.2.1.2, pag.35 for WEP, */
/* IEEE 802.11i-2004, 8.3.2.2, pag. 45 for TKIP, */
/* IEEE 802.11i-2004, 8.3.3.2, pag. 57 for CCMP */
if (AIRPDCAP_EXTIV(data[offset+3])==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "WEP encryption", AIRPDCAP_DEBUG_LEVEL_3);
return AirPDcapWepMng(ctx, decrypt_data, mac_header_len, decrypt_len, key, sa, offset);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "TKIP or CCMP encryption", AIRPDCAP_DEBUG_LEVEL_3);
/* If index >= 1, then use the group key. This will not work if the AP is using
more than one group key simultaneously. I've not seen this in practice, however.
Usually an AP will rotate between the two key index values of 1 and 2 whenever
it needs to change the group key to be used. */
if (AIRPDCAP_KEY_INDEX(data[offset+3])>=1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "The key index >= 1. This is encrypted with a group key.", AIRPDCAP_DEBUG_LEVEL_3);
/* force STA address to broadcast MAC so we load the SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
/* search for a cached Security Association for current BSSID and broadcast MAC */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL)
return AIRPDCAP_RET_REQ_DATA;
}
/* Decrypt the packet using the appropriate SA */
if (AirPDcapRsnaMng(decrypt_data, mac_header_len, decrypt_len, key, sa, offset) == AIRPDCAP_RET_SUCCESS) {
/* If we successfully decrypted a packet, scan it to see if it contains a key handshake.
The group key handshake could be sent at any time the AP wants to change the key (such as when
it is using key rotation) and it also could be a rekey for the Pairwise key. So we must scan every packet. */
if (scanHandshake) {
return (AirPDcapScanForKeys(ctx, decrypt_data, mac_header_len, *decrypt_len, id));
} else {
return AIRPDCAP_RET_SUCCESS;
}
}
}
}
return AIRPDCAP_RET_UNSUCCESS;
}
INT AirPDcapSetKeys(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
INT i;
INT success;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapSetKeys");
if (ctx==NULL || keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "NULL context or NULL keys array", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
if (keys_nr>AIRPDCAP_MAX_KEYS_NR) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Keys number greater than maximum", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
/* clean key and SA collections before setting new ones */
AirPDcapInitContext(ctx);
/* check and insert keys */
for (i=0, success=0; i<(INT)keys_nr; i++) {
if (AirPDcapValidateKey(keys+i)==TRUE) {
if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PWD key", AIRPDCAP_DEBUG_LEVEL_4);
AirPDcapRsnaPwd2Psk(keys[i].UserPwd.Passphrase, keys[i].UserPwd.Ssid, keys[i].UserPwd.SsidLen, keys[i].KeyData.Wpa.Psk);
}
#ifdef _DEBUG
else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PMK key", AIRPDCAP_DEBUG_LEVEL_4);
} else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WEP key", AIRPDCAP_DEBUG_LEVEL_4);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a key", AIRPDCAP_DEBUG_LEVEL_4);
}
#endif
memcpy(&ctx->keys[success], &keys[i], sizeof(keys[i]));
success++;
}
}
ctx->keys_nr=success;
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return success;
}
static void
AirPDcapCleanKeys(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapCleanKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
return;
}
memset(ctx->keys, 0, sizeof(AIRPDCAP_KEY_ITEM) * AIRPDCAP_MAX_KEYS_NR);
ctx->keys_nr=0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "Keys collection cleaned!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
}
static void
AirPDcapRecurseCleanSA(
PAIRPDCAP_SEC_ASSOCIATION sa)
{
if (sa->next != NULL) {
AirPDcapRecurseCleanSA(sa->next);
g_free(sa->next);
sa->next = NULL;
}
}
static void
AirPDcapCleanSecAssoc(
PAIRPDCAP_CONTEXT ctx)
{
PAIRPDCAP_SEC_ASSOCIATION psa;
int i;
for (psa = ctx->sa, i = 0; i < AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; i++, psa++) {
/* To iterate is human, to recurse, divine */
AirPDcapRecurseCleanSA(psa);
}
}
INT AirPDcapGetKeys(
const PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
UINT i;
UINT j;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapGetKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return 0;
} else if (keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL keys array", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return (INT)ctx->keys_nr;
} else {
for (i=0, j=0; i<ctx->keys_nr && i<keys_nr && i<AIRPDCAP_MAX_KEYS_NR; i++) {
memcpy(&keys[j], &ctx->keys[i], sizeof(keys[j]));
j++;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "Got a key", AIRPDCAP_DEBUG_LEVEL_5);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return j;
}
}
/*
* XXX - This won't be reliable if a packet containing SSID "B" shows
* up in the middle of a 4-way handshake for SSID "A".
* We should probably use a small array or hash table to keep multiple
* SSIDs.
*/
INT AirPDcapSetLastSSID(
PAIRPDCAP_CONTEXT ctx,
CHAR *pkt_ssid,
size_t pkt_ssid_len)
{
if (!ctx || !pkt_ssid || pkt_ssid_len < 1 || pkt_ssid_len > WPA_SSID_MAX_SIZE)
return AIRPDCAP_RET_UNSUCCESS;
memcpy(ctx->pkt_ssid, pkt_ssid, pkt_ssid_len);
ctx->pkt_ssid_len = pkt_ssid_len;
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapInitContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapInitContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
ctx->pkt_ssid_len = 0;
memset(ctx->sa, 0, AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR * sizeof(AIRPDCAP_SEC_ASSOCIATION));
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "Context initialized!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapDestroyContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapDestroyContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
AirPDcapCleanSecAssoc(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "Context destroyed!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Internal function definitions */
#ifdef __cplusplus
extern "C" {
#endif
static INT
AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
INT ret_value=1;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
if (*decrypt_len > try_data_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* allocate a temp buffer for the decryption loop */
try_data=(UCHAR *)g_malloc(try_data_len);
/* start of loop added by GCS */
for(/* sa */; sa != NULL ;sa=sa->next) {
if (sa->validKey==FALSE) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Key not yet valid", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
/* copy the encrypted data into a temp buffer */
memcpy(try_data, decrypt_data, *decrypt_len);
if (sa->wpa.key_ver==1) {
/* CCMP -> HMAC-MD5 is the EAPOL-Key MIC, RC4 is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP", AIRPDCAP_DEBUG_LEVEL_3);
DEBUG_DUMP("ptk", sa->wpa.ptk, 64);
DEBUG_DUMP("ptk portion used", AIRPDCAP_GET_TK(sa->wpa.ptk), 16);
ret_value=AirPDcapTkipDecrypt(try_data+offset, *decrypt_len-offset, try_data+AIRPDCAP_TA_OFFSET, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP failed!", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) and ICV (4bytes) from the end of packet */
*decrypt_len-=12;
break;
} else {
/* AES-CCMP -> HMAC-SHA1-128 is the EAPOL-Key MIC, AES wep_key wrap is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP", AIRPDCAP_DEBUG_LEVEL_3);
ret_value=AirPDcapCcmpDecrypt(try_data, mac_header_len, (INT)*decrypt_len, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value)
continue;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) from the end of packet */
*decrypt_len-=8;
break;
}
}
/* end of loop */
/* none of the keys worked */
if(sa == NULL) {
g_free(try_data);
return ret_value;
}
if (*decrypt_len > try_data_len || *decrypt_len < 8) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
g_free(try_data);
return AIRPDCAP_RET_UNSUCCESS;
}
/* copy the decrypted data into the decrypt buffer GCS*/
memcpy(decrypt_data, try_data, *decrypt_len);
g_free(try_data);
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove TKIP/CCMP header */
offset = mac_header_len;
*decrypt_len-=8;
memmove(decrypt_data+offset, decrypt_data+offset+8, *decrypt_len-offset);
if (key!=NULL) {
if (sa->key!=NULL)
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
else
memset(key, 0, sizeof(AIRPDCAP_KEY_ITEM));
memcpy(key->KeyData.Wpa.Ptk, sa->wpa.ptk, AIRPDCAP_WPA_PTK_LEN); /* copy the PTK to the key structure for future use by wireshark */
if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_TKIP;
else if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_CCMP;
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
UCHAR wep_key[AIRPDCAP_WEP_KEY_MAXLEN+AIRPDCAP_WEP_IVLEN];
size_t keylen;
INT ret_value=1;
INT key_index;
AIRPDCAP_KEY_ITEM *tmp_key;
UINT8 useCache=FALSE;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
try_data = (UCHAR *)g_malloc(try_data_len);
if (sa->key!=NULL)
useCache=TRUE;
for (key_index=0; key_index<(INT)ctx->keys_nr; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
tmp_key=&ctx->keys[key_index];
} else {
if (sa->key!=NULL && sa->key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try cached WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Cached key is not valid, try another WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WEP keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
memset(wep_key, 0, sizeof(wep_key));
memcpy(try_data, decrypt_data, *decrypt_len);
/* Costruct the WEP seed: copy the IV in first 3 bytes and then the WEP key (refer to 802-11i-2004, 8.2.1.4.3, pag. 36) */
memcpy(wep_key, try_data+mac_header_len, AIRPDCAP_WEP_IVLEN);
keylen=tmp_key->KeyData.Wep.WepKeyLen;
memcpy(wep_key+AIRPDCAP_WEP_IVLEN, tmp_key->KeyData.Wep.WepKey, keylen);
ret_value=AirPDcapWepDecrypt(wep_key,
keylen+AIRPDCAP_WEP_IVLEN,
try_data + (mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN),
*decrypt_len-(mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN+AIRPDCAP_CRC_LEN));
if (ret_value == AIRPDCAP_RET_SUCCESS)
memcpy(decrypt_data, try_data, *decrypt_len);
}
if (!ret_value && tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
/* the tried key is the correct one, cached in the Security Association */
sa->key=tmp_key;
if (key!=NULL) {
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
}
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
g_free(try_data);
if (ret_value)
return AIRPDCAP_RET_UNSUCCESS;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "WEP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove ICV (4bytes) from the end of packet */
*decrypt_len-=4;
if (*decrypt_len < 4) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Decryption length too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove IC header */
offset = mac_header_len;
*decrypt_len-=4;
memmove(decrypt_data+offset, decrypt_data+offset+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN, *decrypt_len-offset);
return AIRPDCAP_RET_SUCCESS;
}
/* Refer to IEEE 802.11i-2004, 8.5.3, pag. 85 */
static INT
AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
{
AIRPDCAP_KEY_ITEM *tmp_key, *tmp_pkt_key, pkt_key;
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
INT key_index;
INT ret_value=1;
UCHAR useCache=FALSE;
UCHAR eapol[AIRPDCAP_EAPOL_MAX_LEN];
USHORT eapol_len;
if (sa->key!=NULL)
useCache=TRUE;
/* a 4-way handshake packet use a Pairwise key type (IEEE 802.11i-2004, pg. 79) */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=1) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Group/STAKey message (not used)", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* TODO timeouts? */
/* TODO consider key-index */
/* TODO considera Deauthentications */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake...", AIRPDCAP_DEBUG_LEVEL_5);
/* manage 4-way handshake packets; this step completes the 802.1X authentication process (IEEE 802.11i-2004, pag. 85) */
/* message 1: Authenticator->Supplicant (Sec=0, Mic=0, Ack=1, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=ANonce, MIC=0) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 1", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 1, the Supplicant determines whether the Key Replay Counter field value has been */
/* used before with the current PMKSA. If the Key Replay Counter field value is less than or equal to the current */
/* local value, the Supplicant discards the message. */
/* -> not checked, the Authenticator will be send another Message 1 (hopefully!) */
/* This saves the sa since we are reauthenticating which will overwrite our current sa GCS*/
if( sa->handshake >= 2) {
tmp_sa= g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->validKey=FALSE;
sa->next=tmp_sa;
}
/* save ANonce (from authenticator) to derive the PTK with the SNonce (from the 2 message) */
memcpy(sa->wpa.nonce, data+offset+12, 32);
/* get the Key Descriptor Version (to select algorithm used in decryption -CCMP or TKIP-) */
sa->wpa.key_ver=AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1]);
sa->handshake=1;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* message 2|4: Supplicant->Authenticator (Sec=0|1, Mic=1, Ack=0, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=SNonce|0, MIC=MIC(KCK,EAPOL)) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==0 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
/* Check key data length to differentiate between message 2 or 4, same as in epan/dissectors/packet-ieee80211.c */
if (pntoh16(data+offset+92)) {
/* message 2 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 2", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 2, the Authenticator checks that the key replay counter corresponds to the */
/* outstanding Message 1. If not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, */
/* the Authenticator silently discards Message 2. */
/* -> not checked; the Supplicant will send another message 2 (hopefully!) */
/* now you can derive the PTK */
for (key_index=0; key_index<(INT)ctx->keys_nr || useCache; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
} else {
/* there is a cached key in the security association, if it's a WPA key try it... */
if (sa->key!=NULL &&
(sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try cached WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Cached key is of a wrong type, try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WPA keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)
{
if (tmp_key->KeyType == AIRPDCAP_KEY_TYPE_WPA_PWD && tmp_key->UserPwd.SsidLen == 0 && ctx->pkt_ssid_len > 0 && ctx->pkt_ssid_len <= AIRPDCAP_WPA_SSID_MAX_LEN) {
/* We have a "wildcard" SSID. Use the one from the packet. */
memcpy(&pkt_key, tmp_key, sizeof(pkt_key));
memcpy(&pkt_key.UserPwd.Ssid, ctx->pkt_ssid, ctx->pkt_ssid_len);
pkt_key.UserPwd.SsidLen = ctx->pkt_ssid_len;
AirPDcapRsnaPwd2Psk(pkt_key.UserPwd.Passphrase, pkt_key.UserPwd.Ssid,
pkt_key.UserPwd.SsidLen, pkt_key.KeyData.Wpa.Psk);
tmp_pkt_key = &pkt_key;
} else {
tmp_pkt_key = tmp_key;
}
/* derive the PTK from the BSSID, STA MAC, PMK, SNonce, ANonce */
AirPDcapRsnaPrfX(sa, /* authenticator nonce, bssid, station mac */
tmp_pkt_key->KeyData.Wpa.Psk, /* PSK == PMK */
data+offset+12, /* supplicant nonce */
512,
sa->wpa.ptk);
/* verify the MIC (compare the MIC in the packet included in this message with a MIC calculated with the PTK) */
eapol_len=pntoh16(data+offset-3)+4;
memcpy(eapol, &data[offset-5], (eapol_len<AIRPDCAP_EAPOL_MAX_LEN?eapol_len:AIRPDCAP_EAPOL_MAX_LEN));
ret_value=AirPDcapRsnaMicCheck(eapol, /* eapol frame (header also) */
eapol_len, /* eapol frame length */
sa->wpa.ptk, /* Key Confirmation Key */
AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1])); /* EAPOL-Key description version */
/* If the MIC is valid, the Authenticator checks that the RSN information element bit-wise matches */
/* that from the (Re)Association Request message. */
/* i) TODO If these are not exactly the same, the Authenticator uses MLME-DEAUTHENTICATE.request */
/* primitive to terminate the association. */
/* ii) If they do match bit-wise, the Authenticator constructs Message 3. */
}
if (!ret_value &&
(tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK))
{
/* the temporary key is the correct one, cached in the Security Association */
sa->key=tmp_key;
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
if (ret_value) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "handshake step failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
sa->handshake=2;
sa->validKey=TRUE; /* we can use the key to decode, even if we have not captured the other eapol packets */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* message 4 */
/* TODO "Note that when the 4-Way Handshake is first used Message 4 is sent in the clear." */
/* TODO check MIC and Replay Counter */
/* On reception of Message 4, the Authenticator verifies that the Key Replay Counter field value is one */
/* that it used on this 4-Way Handshake; if it is not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, the */
/* Authenticator silently discards Message 4. */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 4", AIRPDCAP_DEBUG_LEVEL_3);
sa->handshake=4;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
}
/* message 3: Authenticator->Supplicant (Sec=1, Mic=1, Ack=1, Inst=0/1, Key=1(pairwise), KeyRSC=???, Nonce=ANonce, MIC=1) */
if (AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
const EAPOL_RSN_KEY *pEAPKey;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 3", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 3, the Supplicant silently discards the message if the Key Replay Counter field */
/* value has already been used or if the ANonce value in Message 3 differs from the ANonce value in Message 1. */
/* -> not checked, the Authenticator will send another message 3 (hopefully!) */
/* TODO check page 88 (RNS) */
/* If using WPA2 PSK, message 3 will contain an RSN for the group key (GTK KDE).
In order to properly support decrypting WPA2-PSK packets, we need to parse this to get the group key. */
pEAPKey = (const EAPOL_RSN_KEY *)(&(data[offset-1]));
if (pEAPKey->type == AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR){
PAIRPDCAP_SEC_ASSOCIATION broadcast_sa;
AIRPDCAP_SEC_ASSOCIATION_ID id;
/* Get broadcacst SA for the current BSSID */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, sa->saId.bssid, AIRPDCAP_MAC_LEN);
broadcast_sa = AirPDcapGetSaPtr(ctx, &id);
if (broadcast_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sa->wpa.ptk+16, broadcast_sa, tot_len-offset+1));
}
}
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
static INT
AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
{
UCHAR mic[AIRPDCAP_WPA_MICKEY_LEN];
UCHAR c_mic[20]; /* MIC 16 byte, the HMAC-SHA1 use a buffer of 20 bytes */
/* copy the MIC from the EAPOL packet */
memcpy(mic, eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, AIRPDCAP_WPA_MICKEY_LEN);
/* set to 0 the MIC in the EAPOL packet (to calculate the MIC) */
memset(eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, 0, AIRPDCAP_WPA_MICKEY_LEN);
if (key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP) {
/* use HMAC-MD5 for the EAPOL-Key MIC */
md5_hmac(eapol, eapol_len, KCK, AIRPDCAP_WPA_KCK_LEN, c_mic);
} else if (key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP) {
/* use HMAC-SHA1-128 for the EAPOL-Key MIC */
sha1_hmac(KCK, AIRPDCAP_WPA_KCK_LEN, eapol, eapol_len, c_mic);
} else
/* key descriptor version not recognized */
return AIRPDCAP_RET_UNSUCCESS;
/* compare calculated MIC with the Key MIC and return result (0 means success) */
return memcmp(mic, c_mic, AIRPDCAP_WPA_MICKEY_LEN);
}
static INT
AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
{
size_t len;
UCHAR ret=TRUE;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
if (key==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "NULL key", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
return FALSE;
}
switch (key->KeyType) {
case AIRPDCAP_KEY_TYPE_WEP:
/* check key size limits */
len=key->KeyData.Wep.WepKeyLen;
if (len<AIRPDCAP_WEP_KEY_MINLEN || len>AIRPDCAP_WEP_KEY_MAXLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WEP key: key length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WEP_40:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_40_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WEP_104:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_104_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
/* check passphrase and SSID size limits */
len=strlen(key->UserPwd.Passphrase);
if (len<AIRPDCAP_WPA_PASSPHRASE_MIN_LEN || len>AIRPDCAP_WPA_PASSPHRASE_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: passphrase length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
len=key->UserPwd.SsidLen;
if (len>AIRPDCAP_WPA_SSID_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: ssid length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
break;
default:
ret=FALSE;
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapValidateKey");
return ret;
}
static INT
AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT sa_index;
if (ctx->sa_index!=-1) {
/* at least one association was stored */
/* search for the association from sa_index to 0 (most recent added) */
for (sa_index=ctx->sa_index; sa_index>=0; sa_index--) {
if (ctx->sa[sa_index].used) {
if (memcmp(id, &(ctx->sa[sa_index].saId), sizeof(AIRPDCAP_SEC_ASSOCIATION_ID))==0) {
ctx->index=sa_index;
return sa_index;
}
}
}
}
return -1;
}
static INT
AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT last_free;
if (ctx->first_free_index>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
if (ctx->sa[ctx->first_free_index].used) {
/* last addition was in the middle of the array (and the first_free_index was just incremented by 1) */
/* search for a free space from the first_free_index to AIRPDCAP_STA_INFOS_NR (to avoid free blocks in */
/* the middle) */
for (last_free=ctx->first_free_index; last_free<AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; last_free++)
if (!ctx->sa[last_free].used)
break;
if (last_free>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
/* store first free space index */
ctx->first_free_index=last_free;
}
/* use this info */
ctx->index=ctx->first_free_index;
/* reset the info structure */
memset(ctx->sa+ctx->index, 0, sizeof(AIRPDCAP_SEC_ASSOCIATION));
ctx->sa[ctx->index].used=1;
/* set the info structure */
memcpy(&(ctx->sa[ctx->index].saId), id, sizeof(AIRPDCAP_SEC_ASSOCIATION_ID));
/* increment by 1 the first_free_index (heuristic) */
ctx->first_free_index++;
/* set the sa_index if the added index is greater the the sa_index */
if (ctx->index > ctx->sa_index)
ctx->sa_index=ctx->index;
return ctx->index;
}
static INT
AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
if ((AIRPDCAP_TYPE(frame->fc[0])==AIRPDCAP_TYPE_DATA) &&
(AIRPDCAP_DS_BITS(frame->fc[1]) == 0) &&
(memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) != 0) &&
(memcmp(frame->addr1, frame->addr3, AIRPDCAP_MAC_LEN) != 0)) {
/* DATA frame with fromDS=0 ToDS=0 and neither RA or SA is BSSID
=> TDLS traffic. Use highest MAC address for bssid */
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id->sta, frame->addr1, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr2, AIRPDCAP_MAC_LEN);
} else {
memcpy(id->sta, frame->addr2, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr1, AIRPDCAP_MAC_LEN);
}
} else {
const UCHAR *addr;
/* Normal Case: SA between STA and AP */
if ((addr = AirPDcapGetBssidAddress(frame)) != NULL) {
memcpy(id->bssid, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
if ((addr = AirPDcapGetStaAddress(frame)) != NULL) {
memcpy(id->sta, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
}
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "BSSID_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->bssid[0],id->bssid[1],id->bssid[2],id->bssid[3],id->bssid[4],id->bssid[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
g_snprintf(msgbuf, MSGBUF_LEN, "STA_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->sta[0],id->sta[1],id->sta[2],id->sta[3],id->sta[4],id->sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
return AIRPDCAP_RET_SUCCESS;
}
/*
* AirPDcapGetBssidAddress() and AirPDcapGetBssidAddress() are used for
* key caching. In each case, it's more important to return a value than
* to return a _correct_ value, so we fudge addresses in some cases, e.g.
* the BSSID in bridged connections.
* FromDS ToDS Sta BSSID
* 0 0 addr1/2 addr3
* 0 1 addr2 addr1
* 1 0 addr1 addr2
* 1 1 addr2 addr1
*/
static const UCHAR *
AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
if (memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) == 0)
return frame->addr1;
else
return frame->addr2;
case 1:
return frame->addr2;
case 2:
return frame->addr1;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
static const UCHAR *
AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
return frame->addr3;
case 1:
return frame->addr1;
case 2:
return frame->addr2;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) > 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
/* Function used to derive the PTK. Refer to IEEE 802.11I-2004, pag. 74
* and IEEE 802.11i-2004, pag. 164 */
static void
AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
{
UINT8 i;
UCHAR R[100];
INT offset=sizeof("Pairwise key expansion");
UCHAR output[80]; /* allow for sha1 overflow. */
memset(R, 0, 100);
memcpy(R, "Pairwise key expansion", offset);
/* Min(AA, SPA) || Max(AA, SPA) */
if (memcmp(sa->saId.sta, sa->saId.bssid, AIRPDCAP_MAC_LEN) < 0)
{
memcpy(R + offset, sa->saId.sta, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.bssid, AIRPDCAP_MAC_LEN);
}
else
{
memcpy(R + offset, sa->saId.bssid, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.sta, AIRPDCAP_MAC_LEN);
}
offset+=AIRPDCAP_MAC_LEN*2;
/* Min(ANonce,SNonce) || Max(ANonce,SNonce) */
if( memcmp(snonce, sa->wpa.nonce, 32) < 0 )
{
memcpy(R + offset, snonce, 32);
memcpy(R + offset + 32, sa->wpa.nonce, 32);
}
else
{
memcpy(R + offset, sa->wpa.nonce, 32);
memcpy(R + offset + 32, snonce, 32);
}
offset+=32*2;
for(i = 0; i < (x+159)/160; i++)
{
R[offset] = i;
sha1_hmac(pmk, 32, R, 100, &output[20 * i]);
}
memcpy(ptk, output, x/8);
}
#define MAX_SSID_LENGTH 32 /* maximum SSID length */
static INT
AirPDcapRsnaPwd2PskStep(
const guint8 *ppBytes,
const guint ppLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
{
UCHAR digest[MAX_SSID_LENGTH+4]; /* SSID plus 4 bytes of count */
UCHAR digest1[SHA1_DIGEST_LEN];
INT i, j;
if (ssidLength > MAX_SSID_LENGTH) {
/* This "should not happen" */
return AIRPDCAP_RET_UNSUCCESS;
}
memset(digest, 0, sizeof digest);
memset(digest1, 0, sizeof digest1);
/* U1 = PRF(P, S || INT(i)) */
memcpy(digest, ssid, ssidLength);
digest[ssidLength] = (UCHAR)((count>>24) & 0xff);
digest[ssidLength+1] = (UCHAR)((count>>16) & 0xff);
digest[ssidLength+2] = (UCHAR)((count>>8) & 0xff);
digest[ssidLength+3] = (UCHAR)(count & 0xff);
sha1_hmac(ppBytes, ppLength, digest, (guint32) ssidLength+4, digest1);
/* output = U1 */
memcpy(output, digest1, SHA1_DIGEST_LEN);
for (i = 1; i < iterations; i++) {
/* Un = PRF(P, Un-1) */
sha1_hmac(ppBytes, ppLength, digest1, SHA1_DIGEST_LEN, digest);
memcpy(digest1, digest, SHA1_DIGEST_LEN);
/* output = output xor Un */
for (j = 0; j < SHA1_DIGEST_LEN; j++) {
output[j] ^= digest[j];
}
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
{
UCHAR m_output[2*SHA1_DIGEST_LEN];
GByteArray *pp_ba = g_byte_array_new();
memset(m_output, 0, 2*SHA1_DIGEST_LEN);
if (!uri_str_to_bytes(passphrase, pp_ba)) {
g_byte_array_free(pp_ba, TRUE);
return 0;
}
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 1, m_output);
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 2, &m_output[SHA1_DIGEST_LEN]);
memcpy(output, m_output, AIRPDCAP_WPA_PSK_LEN);
g_byte_array_free(pp_ba, TRUE);
return 0;
}
/*
* Returns the decryption_key_t struct given a string describing the key.
* Returns NULL if the input_string cannot be parsed.
*/
decryption_key_t*
parse_key_string(gchar* input_string, guint8 key_type)
{
gchar *key, *tmp_str;
gchar *ssid;
GString *key_string = NULL;
GByteArray *ssid_ba = NULL, *key_ba;
gboolean res;
gchar **tokens;
guint n = 0;
decryption_key_t *dk;
if(input_string == NULL)
return NULL;
/*
* Parse the input_string. WEP and WPA will be just a string
* of hexadecimal characters (if key is wrong, null will be
* returned...).
* WPA-PWD should be in the form
* <key data>[:<ssid>]
*/
switch(key_type)
{
case AIRPDCAP_KEY_TYPE_WEP:
case AIRPDCAP_KEY_TYPE_WEP_40:
case AIRPDCAP_KEY_TYPE_WEP_104:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
if (res && key_ba->len > 0) {
/* Key is correct! It was probably an 'old style' WEP key */
/* Create the decryption_key_t structure, fill it and return it*/
dk = (decryption_key_t *)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WEP;
/* XXX - The current key handling code in the GUI requires
* no separators and lower case */
tmp_str = bytes_to_str(NULL, key_ba->data, key_ba->len);
dk->key = g_string_new(tmp_str);
g_string_ascii_down(dk->key);
dk->bits = key_ba->len * 8;
dk->ssid = NULL;
wmem_free(NULL, tmp_str);
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Key doesn't work */
g_byte_array_free(key_ba, TRUE);
return NULL;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
tokens = g_strsplit(input_string,":",0);
/* Tokens is a null termiated array of strings ... */
while(tokens[n] != NULL)
n++;
if(n < 1)
{
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
/*
* The first token is the key
*/
key = g_strdup(tokens[0]);
ssid = NULL;
/* Maybe there is a second token (an ssid, if everything else is ok) */
if(n >= 2)
{
ssid = g_strdup(tokens[1]);
}
/* Create a new string */
key_string = g_string_new(key);
ssid_ba = NULL;
/* Two (or more) tokens mean that the user entered a WPA-PWD key ... */
if( ((key_string->len) > WPA_KEY_MAX_CHAR_SIZE) || ((key_string->len) < WPA_KEY_MIN_CHAR_SIZE))
{
g_string_free(key_string, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid != NULL) /* more than two tokens found, means that the user specified the ssid */
{
ssid_ba = g_byte_array_new();
if (! uri_str_to_bytes(ssid, ssid_ba)) {
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid_ba->len > WPA_SSID_MAX_CHAR_SIZE)
{
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PWD;
dk->key = g_string_new(key);
dk->bits = 256; /* This is the length of the array pf bytes that will be generated using key+ssid ...*/
dk->ssid = byte_array_dup(ssid_ba); /* NULL if ssid_ba is NULL */
g_string_free(key_string, TRUE);
if (ssid_ba != NULL)
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
if(ssid != NULL)
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return dk;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
/* Two tokens means that the user should have entered a WPA-BIN key ... */
if(!res || ((key_ba->len) != WPA_PSK_KEY_SIZE))
{
g_byte_array_free(key_ba, TRUE);
/* No ssid has been created ... */
return NULL;
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PSK;
dk->key = g_string_new(input_string);
dk->bits = (guint) dk->key->len * 4;
dk->ssid = NULL;
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Type not supported */
return NULL;
}
void
free_key_string(decryption_key_t *dk)
{
if (dk->key)
g_string_free(dk->key, TRUE);
if (dk->ssid)
g_byte_array_free(dk->ssid, TRUE);
g_free(dk);
}
/*
* Returns a newly allocated string representing the given decryption_key_t
* struct, or NULL if something is wrong...
*/
gchar*
get_key_string(decryption_key_t* dk)
{
gchar* output_string = NULL;
if(dk == NULL || dk->key == NULL)
return NULL;
switch(dk->type) {
case AIRPDCAP_KEY_TYPE_WEP:
output_string = g_strdup(dk->key->str);
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
if(dk->ssid == NULL)
output_string = g_strdup(dk->key->str);
else
output_string = g_strdup_printf("%s:%s",
dk->key->str, format_uri(dk->ssid, ":"));
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
output_string = g_strdup(dk->key->str);
break;
default:
return NULL;
}
return output_string;
}
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
{
sha256_hmac_context sha_ctx;
aes_cmac_ctx aes_ctx;
const guint8 *snonce, *anonce, *initiator, *responder, *bssid;
guint8 key_input[SHA256_DIGEST_LEN];
guint8 mic[16], iter[2], length[2], seq_num = action + 1;
/* Get key input */
anonce = &data[offset_fte + 20];
snonce = &data[offset_fte + 52];
sha256_starts(&(sha_ctx.ctx));
if (memcmp(anonce, snonce, AIRPDCAP_WPA_NONCE_LEN) < 0) {
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
} else {
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
}
sha256_finish(&(sha_ctx.ctx), key_input);
/* Derive key */
bssid = &data[offset_link + 2];
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
sha256_hmac_starts(&sha_ctx, key_input, SHA256_DIGEST_LEN);
iter[0] = 1;
iter[1] = 0;
sha256_hmac_update(&sha_ctx, (const guint8 *)&iter, 2);
sha256_hmac_update(&sha_ctx, "TDLS PMK", 8);
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
} else {
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
}
sha256_hmac_update(&sha_ctx, bssid, AIRPDCAP_MAC_LEN);
length[0] = 256 & 0xff;
length[1] = (256 >> 8) & 0xff;
sha256_hmac_update(&sha_ctx, (const guint8 *)&length, 2);
sha256_hmac_finish(&sha_ctx, key_input);
/* Check MIC */
aes_cmac_encrypt_starts(&aes_ctx, key_input, 16);
aes_cmac_encrypt_update(&aes_ctx, initiator, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, responder, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, &seq_num, 1);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_link], data[offset_link + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_rsne], data[offset_rsne + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_timeout], data[offset_timeout + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte], 4);
memset(mic, 0, 16);
aes_cmac_encrypt_update(&aes_ctx, mic, 16);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte + 20], data[offset_fte + 1] + 2 - 20);
aes_cmac_encrypt_finish(&aes_ctx, mic);
if (memcmp(mic, &data[offset_fte + 4],16)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verification failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
memcpy(AIRPDCAP_GET_TK(sa->wpa.ptk), &key_input[16], 16);
memcpy(sa->wpa.nonce, snonce, AIRPDCAP_WPA_NONCE_LEN);
sa->validKey = TRUE;
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verified", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5105_0 |
crossvul-cpp_data_good_2740_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% JJJ PPPP 222 %
% J P P 2 2 %
% J PPPP 22 %
% J J P 2 %
% JJ P 22222 %
% %
% %
% Read/Write JPEG-2000 Image Format %
% %
% Cristy %
% Nathan Brown %
% June 2001 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/semaphore.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
#include <openjpeg.h>
#endif
/*
Forward declarations.
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static MagickBooleanType
WriteJP2Image(const ImageInfo *,Image *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J 2 K %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJ2K() returns MagickTrue if the image format type, identified by the
% magick string, is J2K.
%
% The format of the IsJ2K method is:
%
% MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s J P 2 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsJP2() returns MagickTrue if the image format type, identified by the
% magick string, is JP2.
%
% The format of the IsJP2 method is:
%
% MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0)
return(MagickTrue);
if (length < 12)
return(MagickFalse);
if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000
% codestream (JPC) image file and returns it. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image or set of images.
%
% JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu.
%
% The format of the ReadJP2Image method is:
%
% Image *ReadJP2Image(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
static void JP2ErrorHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer);
if (count == 0)
return((OPJ_SIZE_T) -1);
return((OPJ_SIZE_T) count);
}
static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE);
}
static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context)
{
Image
*image;
image=(Image *) context;
return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset);
}
static void JP2WarningHandler(const char *message,void *client_data)
{
ExceptionInfo
*exception;
exception=(ExceptionInfo *) client_data;
(void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
message,"`%s'","OpenJP2");
}
static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context)
{
Image
*image;
ssize_t
count;
image=(Image *) context;
count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer);
return((OPJ_SIZE_T) count);
}
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
const char
*option;
Image
*image;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
opj_codestream_index_t
*codestream_index = (opj_codestream_index_t *) NULL;
opj_dparameters_t
parameters;
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned char
sans[4];
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize JP2 codec.
*/
if (ReadBlob(image,4,sans) != 4)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) SeekBlob(image,SEEK_SET,0);
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
else
if (IsJ2K(sans,4) != MagickFalse)
jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
opj_set_default_decoder_parameters(¶meters);
option=GetImageOption(image_info,"jp2:reduce-factor");
if (option != (const char *) NULL)
parameters.cp_reduce=StringToInteger(option);
option=GetImageOption(image_info,"jp2:quality-layers");
if (option == (const char *) NULL)
option=GetImageOption(image_info,"jp2:layer-number");
if (option != (const char *) NULL)
parameters.cp_layer=StringToInteger(option);
if (opj_setup_decoder(jp2_codec,¶meters) == 0)
{
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
}
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
jp2_status=1;
if ((image->columns != 0) && (image->rows != 0))
{
/*
Extract an area from the image.
*/
jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
(OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
(OPJ_INT32) image->extract_info.x+(ssize_t) image->columns,
(OPJ_INT32) image->extract_info.y+(ssize_t) image->rows);
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
}
if ((image_info->number_scenes != 0) && (image_info->scene != 0))
jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
(unsigned int) image_info->scene-1);
else
if (image->ping == MagickFalse)
{
jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
if (jp2_status != 0)
jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
}
if (jp2_status == 0)
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
}
opj_stream_destroy(jp2_stream);
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
(jp2_image->comps[0].dx != jp2_image->comps[i].dx) ||
(jp2_image->comps[0].dy != jp2_image->comps[i].dy) ||
(jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
(jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) ||
((image->ping == MagickFalse) && (jp2_image->comps[i].data == NULL)))
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
}
}
/*
Convert JP2 image.
*/
image->columns=(size_t) jp2_image->comps[0].w;
image->rows=(size_t) jp2_image->comps[0].h;
image->depth=jp2_image->comps[0].prec;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
image->compression=JPEG2000Compression;
if (jp2_image->color_space == 2)
{
SetImageColorspace(image,GRAYColorspace);
if (jp2_image->numcomps > 1)
image->matte=MagickTrue;
}
else
if (jp2_image->color_space == 3)
SetImageColorspace(image,Rec601YCbCrColorspace);
if (jp2_image->numcomps > 3)
image->matte=MagickTrue;
if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
{
StringInfo
*profile;
profile=BlobToStringInfo(jp2_image->icc_profile_buf,
jp2_image->icc_profile_len);
if (profile != (StringInfo *) NULL)
SetImageProfile(image,"icc",profile);
}
if (image->ping != MagickFalse)
{
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
return(GetFirstImageInList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register PixelPacket
*magick_restrict q;
register ssize_t
x;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
{
double
pixel,
scale;
scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
(jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
switch (i)
{
case 0:
{
q->red=ClampToQuantum(pixel);
q->green=q->red;
q->blue=q->red;
q->opacity=OpaqueOpacity;
break;
}
case 1:
{
if (jp2_image->numcomps == 2)
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
q->green=ClampToQuantum(pixel);
break;
}
case 2:
{
q->blue=ClampToQuantum(pixel);
break;
}
case 3:
{
q->opacity=ClampToQuantum(QuantumRange-pixel);
break;
}
}
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
/*
Free resources.
*/
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
opj_destroy_cstr_index(&codestream_index);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterJP2Image() adds attributes for the JP2 image format to the list of
% supported formats. The attributes include the image format tag, a method
% method to read and/or write the format, whether the format supports the
% saving of more than one frame to the same file or blob, whether the format
% supports native in-memory I/O, and a brief description of the format.
%
% The format of the RegisterJP2Image method is:
%
% size_t RegisterJP2Image(void)
%
*/
ModuleExport size_t RegisterJP2Image(void)
{
char
version[MaxTextExtent];
MagickInfo
*entry;
*version='\0';
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
(void) FormatLocaleString(version,MaxTextExtent,"%s",opj_version());
#endif
entry=SetMagickInfo("JP2");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2C");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("J2K");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJ2K;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPM");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPT");
entry->description=ConstantString("JPEG-2000 File Format Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("JPC");
entry->description=ConstantString("JPEG-2000 Code Stream Syntax");
if (*version != '\0')
entry->version=ConstantString(version);
entry->mime_type=ConstantString("image/jp2");
entry->module=ConstantString("JP2");
entry->magick=(IsImageFormatHandler *) IsJP2;
entry->adjoin=MagickFalse;
entry->seekable_stream=MagickTrue;
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadJP2Image;
entry->encoder=(EncodeImageHandler *) WriteJP2Image;
#endif
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterJP2Image() removes format registrations made by the JP2 module
% from the list of supported formats.
%
% The format of the UnregisterJP2Image method is:
%
% UnregisterJP2Image(void)
%
*/
ModuleExport void UnregisterJP2Image(void)
{
(void) UnregisterMagickInfo("JPC");
(void) UnregisterMagickInfo("JPT");
(void) UnregisterMagickInfo("JPM");
(void) UnregisterMagickInfo("JP2");
(void) UnregisterMagickInfo("J2K");
}
#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e J P 2 I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteJP2Image() writes an image in the JPEG 2000 image format.
%
% JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
%
% The format of the WriteJP2Image method is:
%
% MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static void CinemaProfileCompliance(const opj_image_t *jp2_image,
opj_cparameters_t *parameters)
{
/*
Digital Cinema 4K profile compliant codestream.
*/
parameters->tile_size_on=OPJ_FALSE;
parameters->cp_tdx=1;
parameters->cp_tdy=1;
parameters->tp_flag='C';
parameters->tp_on=1;
parameters->cp_tx0=0;
parameters->cp_ty0=0;
parameters->image_offset_x0=0;
parameters->image_offset_y0=0;
parameters->cblockw_init=32;
parameters->cblockh_init=32;
parameters->csty|=0x01;
parameters->prog_order=OPJ_CPRL;
parameters->roi_compno=(-1);
parameters->subsampling_dx=1;
parameters->subsampling_dy=1;
parameters->irreversible=1;
if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080))
{
/*
Digital Cinema 2K.
*/
parameters->cp_cinema=OPJ_CINEMA2K_24;
parameters->cp_rsiz=OPJ_CINEMA2K;
parameters->max_comp_size=1041666;
if (parameters->numresolution > 6)
parameters->numresolution=6;
}
if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160))
{
/*
Digital Cinema 4K.
*/
parameters->cp_cinema=OPJ_CINEMA4K_24;
parameters->cp_rsiz=OPJ_CINEMA4K;
parameters->max_comp_size=1041666;
if (parameters->numresolution < 1)
parameters->numresolution=1;
if (parameters->numresolution > 7)
parameters->numresolution=7;
parameters->numpocs=2;
parameters->POC[0].tile=1;
parameters->POC[0].resno0=0;
parameters->POC[0].compno0=0;
parameters->POC[0].layno1=1;
parameters->POC[0].resno1=parameters->numresolution-1;
parameters->POC[0].compno1=3;
parameters->POC[0].prg1=OPJ_CPRL;
parameters->POC[1].tile=1;
parameters->POC[1].resno0=parameters->numresolution-1;
parameters->POC[1].compno0=0;
parameters->POC[1].layno1=1;
parameters->POC[1].resno1=parameters->numresolution;
parameters->POC[1].compno1=3;
parameters->POC[1].prg1=OPJ_CPRL;
}
parameters->tcp_numlayers=1;
parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w*
jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size*
8*jp2_image->comps[0].dx*jp2_image->comps[0].dy);
parameters->cp_disto_alloc=1;
}
static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image)
{
const char
*option,
*property;
int
jp2_status;
MagickBooleanType
status;
opj_codec_t
*jp2_codec;
OPJ_COLOR_SPACE
jp2_colorspace;
opj_cparameters_t
parameters;
opj_image_cmptparm_t
jp2_info[5];
opj_image_t
*jp2_image;
opj_stream_t
*jp2_stream;
register ssize_t
i;
ssize_t
y;
unsigned int
channels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
/*
Initialize JPEG 2000 encoder parameters.
*/
opj_set_default_encoder_parameters(¶meters);
for (i=1; i < 6; i++)
if (((size_t) (1 << (i+2)) > image->columns) &&
((size_t) (1 << (i+2)) > image->rows))
break;
parameters.numresolution=i;
option=GetImageOption(image_info,"jp2:number-resolutions");
if (option != (const char *) NULL)
parameters.numresolution=StringToInteger(option);
parameters.tcp_numlayers=1;
parameters.tcp_rates[0]=0; /* lossless */
parameters.cp_disto_alloc=1;
if ((image_info->quality != 0) && (image_info->quality != 100))
{
parameters.tcp_distoratio[0]=(double) image_info->quality;
parameters.cp_fixed_quality=OPJ_TRUE;
}
if (image_info->extract != (char *) NULL)
{
RectangleInfo
geometry;
int
flags;
/*
Set tile size.
*/
flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
parameters.cp_tdx=(int) geometry.width;
parameters.cp_tdy=(int) geometry.width;
if ((flags & HeightValue) != 0)
parameters.cp_tdy=(int) geometry.height;
if ((flags & XValue) != 0)
parameters.cp_tx0=geometry.x;
if ((flags & YValue) != 0)
parameters.cp_ty0=geometry.y;
parameters.tile_size_on=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:quality");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set quality PSNR.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_distoratio[i]) == 1; i++)
{
if (i >= 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_fixed_quality=OPJ_TRUE;
}
option=GetImageOption(image_info,"jp2:progression-order");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"LRCP") == 0)
parameters.prog_order=OPJ_LRCP;
if (LocaleCompare(option,"RLCP") == 0)
parameters.prog_order=OPJ_RLCP;
if (LocaleCompare(option,"RPCL") == 0)
parameters.prog_order=OPJ_RPCL;
if (LocaleCompare(option,"PCRL") == 0)
parameters.prog_order=OPJ_PCRL;
if (LocaleCompare(option,"CPRL") == 0)
parameters.prog_order=OPJ_CPRL;
}
option=GetImageOption(image_info,"jp2:rate");
if (option != (const char *) NULL)
{
register const char
*p;
/*
Set compression rate.
*/
p=option;
for (i=0; sscanf(p,"%f",¶meters.tcp_rates[i]) == 1; i++)
{
if (i > 100)
break;
while ((*p != '\0') && (*p != ','))
p++;
if (*p == '\0')
break;
p++;
}
parameters.tcp_numlayers=i+1;
parameters.cp_disto_alloc=OPJ_TRUE;
}
if (image_info->sampling_factor != (const char *) NULL)
(void) sscanf(image_info->sampling_factor,"%d,%d",
¶meters.subsampling_dx,¶meters.subsampling_dy);
property=GetImageProperty(image,"comment");
if (property != (const char *) NULL)
parameters.cp_comment=ConstantString(property);
channels=3;
jp2_colorspace=OPJ_CLRSPC_SRGB;
if (image->colorspace == YUVColorspace)
{
jp2_colorspace=OPJ_CLRSPC_SYCC;
parameters.subsampling_dx=2;
}
else
{
if (IsGrayColorspace(image->colorspace) != MagickFalse)
{
channels=1;
jp2_colorspace=OPJ_CLRSPC_GRAY;
}
else
(void) TransformImageColorspace(image,sRGBColorspace);
if (image->matte != MagickFalse)
channels++;
}
parameters.tcp_mct=channels == 3 ? 1 : 0;
ResetMagickMemory(jp2_info,0,sizeof(jp2_info));
for (i=0; i < (ssize_t) channels; i++)
{
jp2_info[i].prec=(unsigned int) image->depth;
jp2_info[i].bpp=(unsigned int) image->depth;
if ((image->depth == 1) &&
((LocaleCompare(image_info->magick,"JPT") == 0) ||
(LocaleCompare(image_info->magick,"JP2") == 0)))
{
jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */
jp2_info[i].bpp++;
}
jp2_info[i].sgnd=0;
jp2_info[i].dx=parameters.subsampling_dx;
jp2_info[i].dy=parameters.subsampling_dy;
jp2_info[i].w=(unsigned int) image->columns;
jp2_info[i].h=(unsigned int) image->rows;
}
jp2_image=opj_image_create(channels,jp2_info,jp2_colorspace);
if (jp2_image == (opj_image_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_image->x0=parameters.image_offset_x0;
jp2_image->y0=parameters.image_offset_y0;
jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)*
parameters.subsampling_dx+1);
jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)*
parameters.subsampling_dx+1);
if ((image->depth == 12) &&
((image->columns == 2048) || (image->rows == 1080) ||
(image->columns == 4096) || (image->rows == 2160)))
CinemaProfileCompliance(jp2_image,¶meters);
if (channels == 4)
jp2_image->comps[3].alpha=1;
else
if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY))
jp2_image->comps[1].alpha=1;
/*
Convert to JP2 pixels.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
register const PixelPacket
*p;
ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) channels; i++)
{
double
scale;
register int
*q;
scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
switch (i)
{
case 0:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*GetPixelLuma(image,p));
break;
}
*q=(int) (scale*p->red);
break;
}
case 1:
{
if (jp2_colorspace == OPJ_CLRSPC_GRAY)
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
*q=(int) (scale*p->green);
break;
}
case 2:
{
*q=(int) (scale*p->blue);
break;
}
case 3:
{
*q=(int) (scale*(QuantumRange-p->opacity));
break;
}
}
}
p++;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
if (LocaleCompare(image_info->magick,"JPT") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
else
if (LocaleCompare(image_info->magick,"J2K") == 0)
jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
else
jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
opj_set_warning_handler(jp2_codec,JP2WarningHandler,&image->exception);
opj_set_error_handler(jp2_codec,JP2ErrorHandler,&image->exception);
opj_setup_encoder(jp2_codec,¶meters,jp2_image);
jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
opj_stream_set_user_data(jp2_stream,image,NULL);
if (jp2_stream == (opj_stream_t *) NULL)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
if (jp2_status == 0)
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
if ((opj_encode(jp2_codec,jp2_stream) == 0) ||
(opj_end_compress(jp2_codec,jp2_stream) == 0))
{
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
}
/*
Free resources.
*/
opj_stream_destroy(jp2_stream);
opj_destroy_codec(jp2_codec);
opj_image_destroy(jp2_image);
(void) CloseBlob(image);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2740_0 |
crossvul-cpp_data_good_5844_0 | /*
* IEEE 802.15.4 dgram socket interface
*
* Copyright 2007, 2008 Siemens AG
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Written by:
* Sergey Lapin <slapin@ossfans.org>
* Dmitry Eremin-Solenikov <dbaryshkov@gmail.com>
*/
#include <linux/net.h>
#include <linux/module.h>
#include <linux/if_arp.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <net/af_ieee802154.h>
#include <net/ieee802154.h>
#include <net/ieee802154_netdev.h>
#include <asm/ioctls.h>
#include "af802154.h"
static HLIST_HEAD(dgram_head);
static DEFINE_RWLOCK(dgram_lock);
struct dgram_sock {
struct sock sk;
struct ieee802154_addr src_addr;
struct ieee802154_addr dst_addr;
unsigned int bound:1;
unsigned int want_ack:1;
};
static inline struct dgram_sock *dgram_sk(const struct sock *sk)
{
return container_of(sk, struct dgram_sock, sk);
}
static void dgram_hash(struct sock *sk)
{
write_lock_bh(&dgram_lock);
sk_add_node(sk, &dgram_head);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
write_unlock_bh(&dgram_lock);
}
static void dgram_unhash(struct sock *sk)
{
write_lock_bh(&dgram_lock);
if (sk_del_node_init(sk))
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&dgram_lock);
}
static int dgram_init(struct sock *sk)
{
struct dgram_sock *ro = dgram_sk(sk);
ro->dst_addr.addr_type = IEEE802154_ADDR_LONG;
ro->dst_addr.pan_id = 0xffff;
ro->want_ack = 1;
memset(&ro->dst_addr.hwaddr, 0xff, sizeof(ro->dst_addr.hwaddr));
return 0;
}
static void dgram_close(struct sock *sk, long timeout)
{
sk_common_release(sk);
}
static int dgram_bind(struct sock *sk, struct sockaddr *uaddr, int len)
{
struct sockaddr_ieee802154 *addr = (struct sockaddr_ieee802154 *)uaddr;
struct dgram_sock *ro = dgram_sk(sk);
int err = -EINVAL;
struct net_device *dev;
lock_sock(sk);
ro->bound = 0;
if (len < sizeof(*addr))
goto out;
if (addr->family != AF_IEEE802154)
goto out;
dev = ieee802154_get_dev(sock_net(sk), &addr->addr);
if (!dev) {
err = -ENODEV;
goto out;
}
if (dev->type != ARPHRD_IEEE802154) {
err = -ENODEV;
goto out_put;
}
memcpy(&ro->src_addr, &addr->addr, sizeof(struct ieee802154_addr));
ro->bound = 1;
err = 0;
out_put:
dev_put(dev);
out:
release_sock(sk);
return err;
}
static int dgram_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
struct sk_buff *skb;
unsigned long amount;
amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL) {
/*
* We will only return the amount
* of this packet since that is all
* that will be read.
*/
/* FIXME: parse the header for more correct value */
amount = skb->len - (3+8+8);
}
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
}
return -ENOIOCTLCMD;
}
/* FIXME: autobind */
static int dgram_connect(struct sock *sk, struct sockaddr *uaddr,
int len)
{
struct sockaddr_ieee802154 *addr = (struct sockaddr_ieee802154 *)uaddr;
struct dgram_sock *ro = dgram_sk(sk);
int err = 0;
if (len < sizeof(*addr))
return -EINVAL;
if (addr->family != AF_IEEE802154)
return -EINVAL;
lock_sock(sk);
if (!ro->bound) {
err = -ENETUNREACH;
goto out;
}
memcpy(&ro->dst_addr, &addr->addr, sizeof(struct ieee802154_addr));
out:
release_sock(sk);
return err;
}
static int dgram_disconnect(struct sock *sk, int flags)
{
struct dgram_sock *ro = dgram_sk(sk);
lock_sock(sk);
ro->dst_addr.addr_type = IEEE802154_ADDR_LONG;
memset(&ro->dst_addr.hwaddr, 0xff, sizeof(ro->dst_addr.hwaddr));
release_sock(sk);
return 0;
}
static int dgram_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t size)
{
struct net_device *dev;
unsigned int mtu;
struct sk_buff *skb;
struct dgram_sock *ro = dgram_sk(sk);
int hlen, tlen;
int err;
if (msg->msg_flags & MSG_OOB) {
pr_debug("msg->msg_flags = 0x%x\n", msg->msg_flags);
return -EOPNOTSUPP;
}
if (!ro->bound)
dev = dev_getfirstbyhwtype(sock_net(sk), ARPHRD_IEEE802154);
else
dev = ieee802154_get_dev(sock_net(sk), &ro->src_addr);
if (!dev) {
pr_debug("no dev\n");
err = -ENXIO;
goto out;
}
mtu = dev->mtu;
pr_debug("name = %s, mtu = %u\n", dev->name, mtu);
if (size > mtu) {
pr_debug("size = %Zu, mtu = %u\n", size, mtu);
err = -EINVAL;
goto out_dev;
}
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
skb = sock_alloc_send_skb(sk, hlen + tlen + size,
msg->msg_flags & MSG_DONTWAIT,
&err);
if (!skb)
goto out_dev;
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
mac_cb(skb)->flags = IEEE802154_FC_TYPE_DATA;
if (ro->want_ack)
mac_cb(skb)->flags |= MAC_CB_FLAG_ACKREQ;
mac_cb(skb)->seq = ieee802154_mlme_ops(dev)->get_dsn(dev);
err = dev_hard_header(skb, dev, ETH_P_IEEE802154, &ro->dst_addr,
ro->bound ? &ro->src_addr : NULL, size);
if (err < 0)
goto out_skb;
skb_reset_mac_header(skb);
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err < 0)
goto out_skb;
skb->dev = dev;
skb->sk = sk;
skb->protocol = htons(ETH_P_IEEE802154);
dev_put(dev);
err = dev_queue_xmit(skb);
if (err > 0)
err = net_xmit_errno(err);
return err ?: size;
out_skb:
kfree_skb(skb);
out_dev:
dev_put(dev);
out:
return err;
}
static int dgram_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len, int noblock, int flags,
int *addr_len)
{
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sk_buff *skb;
struct sockaddr_ieee802154 *saddr;
saddr = (struct sockaddr_ieee802154 *)msg->msg_name;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* FIXME: skip headers if necessary ?! */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
if (saddr) {
saddr->family = AF_IEEE802154;
saddr->addr = mac_cb(skb)->sa;
*addr_len = sizeof(*saddr);
}
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
static int dgram_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
if (sock_queue_rcv_skb(sk, skb) < 0) {
kfree_skb(skb);
return NET_RX_DROP;
}
return NET_RX_SUCCESS;
}
static inline int ieee802154_match_sock(u8 *hw_addr, u16 pan_id,
u16 short_addr, struct dgram_sock *ro)
{
if (!ro->bound)
return 1;
if (ro->src_addr.addr_type == IEEE802154_ADDR_LONG &&
!memcmp(ro->src_addr.hwaddr, hw_addr, IEEE802154_ADDR_LEN))
return 1;
if (ro->src_addr.addr_type == IEEE802154_ADDR_SHORT &&
pan_id == ro->src_addr.pan_id &&
short_addr == ro->src_addr.short_addr)
return 1;
return 0;
}
int ieee802154_dgram_deliver(struct net_device *dev, struct sk_buff *skb)
{
struct sock *sk, *prev = NULL;
int ret = NET_RX_SUCCESS;
u16 pan_id, short_addr;
/* Data frame processing */
BUG_ON(dev->type != ARPHRD_IEEE802154);
pan_id = ieee802154_mlme_ops(dev)->get_pan_id(dev);
short_addr = ieee802154_mlme_ops(dev)->get_short_addr(dev);
read_lock(&dgram_lock);
sk_for_each(sk, &dgram_head) {
if (ieee802154_match_sock(dev->dev_addr, pan_id, short_addr,
dgram_sk(sk))) {
if (prev) {
struct sk_buff *clone;
clone = skb_clone(skb, GFP_ATOMIC);
if (clone)
dgram_rcv_skb(prev, clone);
}
prev = sk;
}
}
if (prev)
dgram_rcv_skb(prev, skb);
else {
kfree_skb(skb);
ret = NET_RX_DROP;
}
read_unlock(&dgram_lock);
return ret;
}
static int dgram_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct dgram_sock *ro = dgram_sk(sk);
int val, len;
if (level != SOL_IEEE802154)
return -EOPNOTSUPP;
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
switch (optname) {
case WPAN_WANTACK:
val = ro->want_ack;
break;
default:
return -ENOPROTOOPT;
}
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &val, len))
return -EFAULT;
return 0;
}
static int dgram_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct dgram_sock *ro = dgram_sk(sk);
int val;
int err = 0;
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case WPAN_WANTACK:
ro->want_ack = !!val;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
struct proto ieee802154_dgram_prot = {
.name = "IEEE-802.15.4-MAC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct dgram_sock),
.init = dgram_init,
.close = dgram_close,
.bind = dgram_bind,
.sendmsg = dgram_sendmsg,
.recvmsg = dgram_recvmsg,
.hash = dgram_hash,
.unhash = dgram_unhash,
.connect = dgram_connect,
.disconnect = dgram_disconnect,
.ioctl = dgram_ioctl,
.getsockopt = dgram_getsockopt,
.setsockopt = dgram_setsockopt,
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5844_0 |
crossvul-cpp_data_bad_5411_6 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5411_6 |
crossvul-cpp_data_bad_727_0 | // SPDX-License-Identifier: BSD-2-Clause
/*
* Copyright (c) 2016, Linaro Limited
* Copyright (c) 2014, STMicroelectronics International N.V.
*/
#include <arm.h>
#include <assert.h>
#include <kernel/panic.h>
#include <kernel/spinlock.h>
#include <kernel/tee_common.h>
#include <kernel/tee_misc.h>
#include <kernel/tlb_helpers.h>
#include <mm/core_memprot.h>
#include <mm/core_mmu.h>
#include <mm/mobj.h>
#include <mm/pgt_cache.h>
#include <mm/tee_mm.h>
#include <mm/tee_mmu.h>
#include <mm/tee_mmu_types.h>
#include <mm/tee_pager.h>
#include <sm/optee_smc.h>
#include <stdlib.h>
#include <tee_api_defines_extensions.h>
#include <tee_api_types.h>
#include <trace.h>
#include <types_ext.h>
#include <user_ta_header.h>
#include <util.h>
#ifdef CFG_PL310
#include <kernel/tee_l2cc_mutex.h>
#endif
#define TEE_MMU_UDATA_ATTR (TEE_MATTR_VALID_BLOCK | \
TEE_MATTR_PRW | TEE_MATTR_URW | \
TEE_MATTR_SECURE)
#define TEE_MMU_UCODE_ATTR (TEE_MATTR_VALID_BLOCK | \
TEE_MATTR_PRW | TEE_MATTR_URWX | \
TEE_MATTR_SECURE)
#define TEE_MMU_UCACHE_DEFAULT_ATTR (TEE_MATTR_CACHE_CACHED << \
TEE_MATTR_CACHE_SHIFT)
static vaddr_t select_va_in_range(vaddr_t prev_end, uint32_t prev_attr,
vaddr_t next_begin, uint32_t next_attr,
const struct vm_region *reg)
{
size_t granul;
const uint32_t a = TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT;
size_t pad;
vaddr_t begin_va;
vaddr_t end_va;
/*
* Insert an unmapped entry to separate regions with differing
* TEE_MATTR_EPHEMERAL TEE_MATTR_PERMANENT bits as they never are
* to be contiguous with another region.
*/
if (prev_attr && (prev_attr & a) != (reg->attr & a))
pad = SMALL_PAGE_SIZE;
else
pad = 0;
granul = SMALL_PAGE_SIZE;
#ifndef CFG_WITH_LPAE
if ((prev_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE))
granul = CORE_MMU_PGDIR_SIZE;
#endif
begin_va = ROUNDUP(prev_end + pad, granul);
if (reg->va) {
if (reg->va < begin_va)
return 0;
begin_va = reg->va;
}
if (next_attr && (next_attr & a) != (reg->attr & a))
pad = SMALL_PAGE_SIZE;
else
pad = 0;
granul = SMALL_PAGE_SIZE;
#ifndef CFG_WITH_LPAE
if ((next_attr & TEE_MATTR_SECURE) != (reg->attr & TEE_MATTR_SECURE))
granul = CORE_MMU_PGDIR_SIZE;
#endif
end_va = ROUNDUP(begin_va + reg->size + pad, granul);
if (end_va <= next_begin) {
assert(!reg->va || reg->va == begin_va);
return begin_va;
}
return 0;
}
static size_t get_num_req_pgts(struct user_ta_ctx *utc, vaddr_t *begin,
vaddr_t *end)
{
vaddr_t b;
vaddr_t e;
if (TAILQ_EMPTY(&utc->vm_info->regions)) {
core_mmu_get_user_va_range(&b, NULL);
e = b;
} else {
struct vm_region *r;
b = TAILQ_FIRST(&utc->vm_info->regions)->va;
r = TAILQ_LAST(&utc->vm_info->regions, vm_region_head);
e = r->va + r->size;
b = ROUNDDOWN(b, CORE_MMU_PGDIR_SIZE);
e = ROUNDUP(e, CORE_MMU_PGDIR_SIZE);
}
if (begin)
*begin = b;
if (end)
*end = e;
return (e - b) >> CORE_MMU_PGDIR_SHIFT;
}
static TEE_Result alloc_pgt(struct user_ta_ctx *utc)
{
struct thread_specific_data *tsd __maybe_unused;
vaddr_t b;
vaddr_t e;
size_t ntbl;
ntbl = get_num_req_pgts(utc, &b, &e);
if (!pgt_check_avail(ntbl)) {
EMSG("%zu page tables not available", ntbl);
return TEE_ERROR_OUT_OF_MEMORY;
}
#ifdef CFG_PAGED_USER_TA
tsd = thread_get_tsd();
if (&utc->ctx == tsd->ctx) {
/*
* The supplied utc is the current active utc, allocate the
* page tables too as the pager needs to use them soon.
*/
pgt_alloc(&tsd->pgt_cache, &utc->ctx, b, e - 1);
}
#endif
return TEE_SUCCESS;
}
static void free_pgt(struct user_ta_ctx *utc, vaddr_t base, size_t size)
{
struct thread_specific_data *tsd = thread_get_tsd();
struct pgt_cache *pgt_cache = NULL;
if (&utc->ctx == tsd->ctx)
pgt_cache = &tsd->pgt_cache;
pgt_flush_ctx_range(pgt_cache, &utc->ctx, base, base + size);
}
static TEE_Result umap_add_region(struct vm_info *vmi, struct vm_region *reg)
{
struct vm_region *r;
struct vm_region *prev_r;
vaddr_t va_range_base;
size_t va_range_size;
vaddr_t va;
core_mmu_get_user_va_range(&va_range_base, &va_range_size);
/* Check alignment, it has to be at least SMALL_PAGE based */
if ((reg->va | reg->size) & SMALL_PAGE_MASK)
return TEE_ERROR_ACCESS_CONFLICT;
/* Check that the mobj is defined for the entire range */
if ((reg->offset + reg->size) >
ROUNDUP(reg->mobj->size, SMALL_PAGE_SIZE))
return TEE_ERROR_BAD_PARAMETERS;
prev_r = NULL;
TAILQ_FOREACH(r, &vmi->regions, link) {
if (TAILQ_FIRST(&vmi->regions) == r) {
va = select_va_in_range(va_range_base, 0,
r->va, r->attr, reg);
if (va) {
reg->va = va;
TAILQ_INSERT_HEAD(&vmi->regions, reg, link);
return TEE_SUCCESS;
}
} else {
va = select_va_in_range(prev_r->va + prev_r->size,
prev_r->attr, r->va, r->attr,
reg);
if (va) {
reg->va = va;
TAILQ_INSERT_BEFORE(r, reg, link);
return TEE_SUCCESS;
}
}
prev_r = r;
}
r = TAILQ_LAST(&vmi->regions, vm_region_head);
if (r) {
va = select_va_in_range(r->va + r->size, r->attr,
va_range_base + va_range_size, 0, reg);
if (va) {
reg->va = va;
TAILQ_INSERT_TAIL(&vmi->regions, reg, link);
return TEE_SUCCESS;
}
} else {
va = select_va_in_range(va_range_base, 0,
va_range_base + va_range_size, 0, reg);
if (va) {
reg->va = va;
TAILQ_INSERT_HEAD(&vmi->regions, reg, link);
return TEE_SUCCESS;
}
}
return TEE_ERROR_ACCESS_CONFLICT;
}
TEE_Result vm_map(struct user_ta_ctx *utc, vaddr_t *va, size_t len,
uint32_t prot, struct mobj *mobj, size_t offs)
{
TEE_Result res;
struct vm_region *reg = calloc(1, sizeof(*reg));
uint32_t attr = 0;
const uint32_t prot_mask = TEE_MATTR_PROT_MASK | TEE_MATTR_PERMANENT |
TEE_MATTR_EPHEMERAL;
if (!reg)
return TEE_ERROR_OUT_OF_MEMORY;
if (prot & ~prot_mask) {
res = TEE_ERROR_BAD_PARAMETERS;
goto err_free_reg;
}
if (!mobj_is_paged(mobj)) {
uint32_t cattr;
res = mobj_get_cattr(mobj, &cattr);
if (res)
goto err_free_reg;
attr |= cattr << TEE_MATTR_CACHE_SHIFT;
}
attr |= TEE_MATTR_VALID_BLOCK;
if (mobj_is_secure(mobj))
attr |= TEE_MATTR_SECURE;
reg->mobj = mobj;
reg->offset = offs;
reg->va = *va;
reg->size = ROUNDUP(len, SMALL_PAGE_SIZE);
reg->attr = attr | prot;
res = umap_add_region(utc->vm_info, reg);
if (res)
goto err_free_reg;
res = alloc_pgt(utc);
if (res)
goto err_rem_reg;
if (!(reg->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT)) &&
mobj_is_paged(mobj)) {
if (!tee_pager_add_uta_area(utc, reg->va, reg->size)) {
res = TEE_ERROR_GENERIC;
goto err_rem_reg;
}
}
/*
* If the context currently is active set it again to update
* the mapping.
*/
if (thread_get_tsd()->ctx == &utc->ctx)
tee_mmu_set_ctx(&utc->ctx);
*va = reg->va;
return TEE_SUCCESS;
err_rem_reg:
TAILQ_REMOVE(&utc->vm_info->regions, reg, link);
err_free_reg:
free(reg);
return res;
}
TEE_Result vm_set_prot(struct user_ta_ctx *utc, vaddr_t va, size_t len,
uint32_t prot)
{
struct vm_region *r;
/*
* To keep thing simple: specified va and len has to match exactly
* with an already registered region.
*/
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (core_is_buffer_intersect(r->va, r->size, va, len)) {
if (r->va != va || r->size != len)
return TEE_ERROR_BAD_PARAMETERS;
if (mobj_is_paged(r->mobj)) {
if (!tee_pager_set_uta_area_attr(utc, va, len,
prot))
return TEE_ERROR_GENERIC;
} else if ((prot & TEE_MATTR_UX) &&
(r->attr & (TEE_MATTR_UW | TEE_MATTR_PW))) {
cache_op_inner(DCACHE_AREA_CLEAN,
(void *)va, len);
cache_op_inner(ICACHE_AREA_INVALIDATE,
(void *)va, len);
}
r->attr &= ~TEE_MATTR_PROT_MASK;
r->attr |= prot & TEE_MATTR_PROT_MASK;
return TEE_SUCCESS;
}
}
return TEE_ERROR_ITEM_NOT_FOUND;
}
static TEE_Result map_kinit(struct user_ta_ctx *utc __maybe_unused)
{
TEE_Result res;
struct mobj *mobj;
size_t offs;
vaddr_t va;
size_t sz;
thread_get_user_kcode(&mobj, &offs, &va, &sz);
if (sz) {
res = vm_map(utc, &va, sz, TEE_MATTR_PRX | TEE_MATTR_PERMANENT,
mobj, offs);
if (res)
return res;
}
thread_get_user_kdata(&mobj, &offs, &va, &sz);
if (sz)
return vm_map(utc, &va, sz, TEE_MATTR_PRW | TEE_MATTR_PERMANENT,
mobj, offs);
return TEE_SUCCESS;
}
TEE_Result vm_info_init(struct user_ta_ctx *utc)
{
TEE_Result res;
uint32_t asid = asid_alloc();
if (!asid) {
DMSG("Failed to allocate ASID");
return TEE_ERROR_GENERIC;
}
utc->vm_info = calloc(1, sizeof(*utc->vm_info));
if (!utc->vm_info) {
asid_free(asid);
return TEE_ERROR_OUT_OF_MEMORY;
}
TAILQ_INIT(&utc->vm_info->regions);
utc->vm_info->asid = asid;
res = map_kinit(utc);
if (res)
vm_info_final(utc);
return res;
}
static void umap_remove_region(struct vm_info *vmi, struct vm_region *reg)
{
TAILQ_REMOVE(&vmi->regions, reg, link);
free(reg);
}
static void clear_param_map(struct user_ta_ctx *utc)
{
struct vm_region *next_r;
struct vm_region *r;
TAILQ_FOREACH_SAFE(r, &utc->vm_info->regions, link, next_r)
if (r->attr & TEE_MATTR_EPHEMERAL)
umap_remove_region(utc->vm_info, r);
}
static TEE_Result param_mem_to_user_va(struct user_ta_ctx *utc,
struct param_mem *mem, void **user_va)
{
struct vm_region *region;
TAILQ_FOREACH(region, &utc->vm_info->regions, link) {
vaddr_t va;
size_t phys_offs;
if (!(region->attr & TEE_MATTR_EPHEMERAL))
continue;
if (mem->mobj != region->mobj)
continue;
if (mem->offs < region->offset)
continue;
if (mem->offs >= (region->offset + region->size))
continue;
phys_offs = mobj_get_phys_offs(mem->mobj,
CORE_MMU_USER_PARAM_SIZE);
va = region->va + mem->offs + phys_offs - region->offset;
*user_va = (void *)va;
return TEE_SUCCESS;
}
return TEE_ERROR_GENERIC;
}
static int cmp_param_mem(const void *a0, const void *a1)
{
const struct param_mem *m1 = a1;
const struct param_mem *m0 = a0;
int ret;
/* Make sure that invalid param_mem are placed last in the array */
if (!m0->size && !m1->size)
return 0;
if (!m0->size)
return 1;
if (!m1->size)
return -1;
ret = CMP_TRILEAN(mobj_is_secure(m0->mobj), mobj_is_secure(m1->mobj));
if (ret)
return ret;
ret = CMP_TRILEAN((vaddr_t)m0->mobj, (vaddr_t)m1->mobj);
if (ret)
return ret;
ret = CMP_TRILEAN(m0->offs, m1->offs);
if (ret)
return ret;
return CMP_TRILEAN(m0->size, m1->size);
}
TEE_Result tee_mmu_map_param(struct user_ta_ctx *utc,
struct tee_ta_param *param, void *param_va[TEE_NUM_PARAMS])
{
TEE_Result res = TEE_SUCCESS;
size_t n;
size_t m;
struct param_mem mem[TEE_NUM_PARAMS];
memset(mem, 0, sizeof(mem));
for (n = 0; n < TEE_NUM_PARAMS; n++) {
uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n);
size_t phys_offs;
if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_INOUT)
continue;
phys_offs = mobj_get_phys_offs(param->u[n].mem.mobj,
CORE_MMU_USER_PARAM_SIZE);
mem[n].mobj = param->u[n].mem.mobj;
mem[n].offs = ROUNDDOWN(phys_offs + param->u[n].mem.offs,
CORE_MMU_USER_PARAM_SIZE);
mem[n].size = ROUNDUP(phys_offs + param->u[n].mem.offs -
mem[n].offs + param->u[n].mem.size,
CORE_MMU_USER_PARAM_SIZE);
}
/*
* Sort arguments so size = 0 is last, secure mobjs first, then by
* mobj pointer value since those entries can't be merged either,
* finally by offset.
*
* This should result in a list where all mergeable entries are
* next to each other and unused/invalid entries are at the end.
*/
qsort(mem, TEE_NUM_PARAMS, sizeof(struct param_mem), cmp_param_mem);
for (n = 1, m = 0; n < TEE_NUM_PARAMS && mem[n].size; n++) {
if (mem[n].mobj == mem[m].mobj &&
(mem[n].offs == (mem[m].offs + mem[m].size) ||
core_is_buffer_intersect(mem[m].offs, mem[m].size,
mem[n].offs, mem[n].size))) {
mem[m].size = mem[n].offs + mem[n].size - mem[m].offs;
continue;
}
m++;
if (n != m)
mem[m] = mem[n];
}
/*
* We'd like 'm' to be the number of valid entries. Here 'm' is the
* index of the last valid entry if the first entry is valid, else
* 0.
*/
if (mem[0].size)
m++;
/* Clear all the param entries as they can hold old information */
clear_param_map(utc);
for (n = 0; n < m; n++) {
vaddr_t va = 0;
const uint32_t prot = TEE_MATTR_PRW | TEE_MATTR_URW |
TEE_MATTR_EPHEMERAL;
res = vm_map(utc, &va, mem[n].size, prot, mem[n].mobj,
mem[n].offs);
if (res)
return res;
}
for (n = 0; n < TEE_NUM_PARAMS; n++) {
uint32_t param_type = TEE_PARAM_TYPE_GET(param->types, n);
if (param_type != TEE_PARAM_TYPE_MEMREF_INPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_OUTPUT &&
param_type != TEE_PARAM_TYPE_MEMREF_INOUT)
continue;
if (param->u[n].mem.size == 0)
continue;
res = param_mem_to_user_va(utc, ¶m->u[n].mem, param_va + n);
if (res != TEE_SUCCESS)
return res;
}
return alloc_pgt(utc);
}
TEE_Result tee_mmu_add_rwmem(struct user_ta_ctx *utc, struct mobj *mobj,
vaddr_t *va)
{
TEE_Result res;
struct vm_region *reg = calloc(1, sizeof(*reg));
if (!reg)
return TEE_ERROR_OUT_OF_MEMORY;
reg->mobj = mobj;
reg->offset = 0;
reg->va = 0;
reg->size = ROUNDUP(mobj->size, SMALL_PAGE_SIZE);
if (mobj_is_secure(mobj))
reg->attr = TEE_MATTR_SECURE;
else
reg->attr = 0;
res = umap_add_region(utc->vm_info, reg);
if (res) {
free(reg);
return res;
}
res = alloc_pgt(utc);
if (res)
umap_remove_region(utc->vm_info, reg);
else
*va = reg->va;
return res;
}
void tee_mmu_rem_rwmem(struct user_ta_ctx *utc, struct mobj *mobj, vaddr_t va)
{
struct vm_region *reg;
TAILQ_FOREACH(reg, &utc->vm_info->regions, link) {
if (reg->mobj == mobj && reg->va == va) {
free_pgt(utc, reg->va, reg->size);
umap_remove_region(utc->vm_info, reg);
return;
}
}
}
void vm_info_final(struct user_ta_ctx *utc)
{
if (!utc->vm_info)
return;
/* clear MMU entries to avoid clash when asid is reused */
tlbi_asid(utc->vm_info->asid);
asid_free(utc->vm_info->asid);
while (!TAILQ_EMPTY(&utc->vm_info->regions))
umap_remove_region(utc->vm_info,
TAILQ_FIRST(&utc->vm_info->regions));
free(utc->vm_info);
utc->vm_info = NULL;
}
/* return true only if buffer fits inside TA private memory */
bool tee_mmu_is_vbuf_inside_ta_private(const struct user_ta_ctx *utc,
const void *va, size_t size)
{
struct vm_region *r;
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT))
continue;
if (core_is_buffer_inside(va, size, r->va, r->size))
return true;
}
return false;
}
/* return true only if buffer intersects TA private memory */
bool tee_mmu_is_vbuf_intersect_ta_private(const struct user_ta_ctx *utc,
const void *va, size_t size)
{
struct vm_region *r;
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (r->attr & (TEE_MATTR_EPHEMERAL | TEE_MATTR_PERMANENT))
continue;
if (core_is_buffer_intersect(va, size, r->va, r->size))
return true;
}
return false;
}
TEE_Result tee_mmu_vbuf_to_mobj_offs(const struct user_ta_ctx *utc,
const void *va, size_t size,
struct mobj **mobj, size_t *offs)
{
struct vm_region *r;
TAILQ_FOREACH(r, &utc->vm_info->regions, link) {
if (!r->mobj)
continue;
if (core_is_buffer_inside(va, size, r->va, r->size)) {
size_t poffs;
poffs = mobj_get_phys_offs(r->mobj,
CORE_MMU_USER_PARAM_SIZE);
*mobj = r->mobj;
*offs = (vaddr_t)va - r->va + r->offset - poffs;
return TEE_SUCCESS;
}
}
return TEE_ERROR_BAD_PARAMETERS;
}
static TEE_Result tee_mmu_user_va2pa_attr(const struct user_ta_ctx *utc,
void *ua, paddr_t *pa, uint32_t *attr)
{
struct vm_region *region;
TAILQ_FOREACH(region, &utc->vm_info->regions, link) {
if (!core_is_buffer_inside(ua, 1, region->va, region->size))
continue;
if (pa) {
TEE_Result res;
paddr_t p;
size_t offset;
size_t granule;
/*
* mobj and input user address may each include
* a specific offset-in-granule position.
* Drop both to get target physical page base
* address then apply only user address
* offset-in-granule.
* Mapping lowest granule is the small page.
*/
granule = MAX(region->mobj->phys_granule,
(size_t)SMALL_PAGE_SIZE);
assert(!granule || IS_POWER_OF_TWO(granule));
offset = region->offset +
ROUNDDOWN((vaddr_t)ua - region->va, granule);
res = mobj_get_pa(region->mobj, offset, granule, &p);
if (res != TEE_SUCCESS)
return res;
*pa = p | ((vaddr_t)ua & (granule - 1));
}
if (attr)
*attr = region->attr;
return TEE_SUCCESS;
}
return TEE_ERROR_ACCESS_DENIED;
}
TEE_Result tee_mmu_user_va2pa_helper(const struct user_ta_ctx *utc, void *ua,
paddr_t *pa)
{
return tee_mmu_user_va2pa_attr(utc, ua, pa, NULL);
}
/* */
TEE_Result tee_mmu_user_pa2va_helper(const struct user_ta_ctx *utc,
paddr_t pa, void **va)
{
TEE_Result res;
paddr_t p;
struct vm_region *region;
TAILQ_FOREACH(region, &utc->vm_info->regions, link) {
size_t granule;
size_t size;
size_t ofs;
/* pa2va is expected only for memory tracked through mobj */
if (!region->mobj)
continue;
/* Physically granulated memory object must be scanned */
granule = region->mobj->phys_granule;
assert(!granule || IS_POWER_OF_TWO(granule));
for (ofs = region->offset; ofs < region->size; ofs += size) {
if (granule) {
/* From current offset to buffer/granule end */
size = granule - (ofs & (granule - 1));
if (size > (region->size - ofs))
size = region->size - ofs;
} else
size = region->size;
res = mobj_get_pa(region->mobj, ofs, granule, &p);
if (res != TEE_SUCCESS)
return res;
if (core_is_buffer_inside(pa, 1, p, size)) {
/* Remove region offset (mobj phys offset) */
ofs -= region->offset;
/* Get offset-in-granule */
p = pa - p;
*va = (void *)(region->va + ofs + (vaddr_t)p);
return TEE_SUCCESS;
}
}
}
return TEE_ERROR_ACCESS_DENIED;
}
TEE_Result tee_mmu_check_access_rights(const struct user_ta_ctx *utc,
uint32_t flags, uaddr_t uaddr,
size_t len)
{
uaddr_t a;
size_t addr_incr = MIN(CORE_MMU_USER_CODE_SIZE,
CORE_MMU_USER_PARAM_SIZE);
if (ADD_OVERFLOW(uaddr, len, &a))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_NONSECURE) &&
(flags & TEE_MEMORY_ACCESS_SECURE))
return TEE_ERROR_ACCESS_DENIED;
/*
* Rely on TA private memory test to check if address range is private
* to TA or not.
*/
if (!(flags & TEE_MEMORY_ACCESS_ANY_OWNER) &&
!tee_mmu_is_vbuf_inside_ta_private(utc, (void *)uaddr, len))
return TEE_ERROR_ACCESS_DENIED;
for (a = uaddr; a < (uaddr + len); a += addr_incr) {
uint32_t attr;
TEE_Result res;
res = tee_mmu_user_va2pa_attr(utc, (void *)a, NULL, &attr);
if (res != TEE_SUCCESS)
return res;
if ((flags & TEE_MEMORY_ACCESS_NONSECURE) &&
(attr & TEE_MATTR_SECURE))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_SECURE) &&
!(attr & TEE_MATTR_SECURE))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_WRITE) && !(attr & TEE_MATTR_UW))
return TEE_ERROR_ACCESS_DENIED;
if ((flags & TEE_MEMORY_ACCESS_READ) && !(attr & TEE_MATTR_UR))
return TEE_ERROR_ACCESS_DENIED;
}
return TEE_SUCCESS;
}
void tee_mmu_set_ctx(struct tee_ta_ctx *ctx)
{
struct thread_specific_data *tsd = thread_get_tsd();
core_mmu_set_user_map(NULL);
/*
* No matter what happens below, the current user TA will not be
* current any longer. Make sure pager is in sync with that.
* This function has to be called before there's a chance that
* pgt_free_unlocked() is called.
*
* Save translation tables in a cache if it's a user TA.
*/
pgt_free(&tsd->pgt_cache, tsd->ctx && is_user_ta_ctx(tsd->ctx));
if (ctx && is_user_ta_ctx(ctx)) {
struct core_mmu_user_map map;
struct user_ta_ctx *utc = to_user_ta_ctx(ctx);
core_mmu_create_user_map(utc, &map);
core_mmu_set_user_map(&map);
tee_pager_assign_uta_tables(utc);
}
tsd->ctx = ctx;
}
struct tee_ta_ctx *tee_mmu_get_ctx(void)
{
return thread_get_tsd()->ctx;
}
void teecore_init_ta_ram(void)
{
vaddr_t s;
vaddr_t e;
paddr_t ps;
paddr_t pe;
/* get virtual addr/size of RAM where TA are loaded/executedNSec
* shared mem allcated from teecore */
core_mmu_get_mem_by_type(MEM_AREA_TA_RAM, &s, &e);
ps = virt_to_phys((void *)s);
pe = virt_to_phys((void *)(e - 1)) + 1;
if (!ps || (ps & CORE_MMU_USER_CODE_MASK) ||
!pe || (pe & CORE_MMU_USER_CODE_MASK))
panic("invalid TA RAM");
/* extra check: we could rely on core_mmu_get_mem_by_type() */
if (!tee_pbuf_is_sec(ps, pe - ps))
panic("TA RAM is not secure");
if (!tee_mm_is_empty(&tee_mm_sec_ddr))
panic("TA RAM pool is not empty");
/* remove previous config and init TA ddr memory pool */
tee_mm_final(&tee_mm_sec_ddr);
tee_mm_init(&tee_mm_sec_ddr, ps, pe, CORE_MMU_USER_CODE_SHIFT,
TEE_MM_POOL_NO_FLAGS);
}
void teecore_init_pub_ram(void)
{
vaddr_t s;
vaddr_t e;
/* get virtual addr/size of NSec shared mem allcated from teecore */
core_mmu_get_mem_by_type(MEM_AREA_NSEC_SHM, &s, &e);
if (s >= e || s & SMALL_PAGE_MASK || e & SMALL_PAGE_MASK)
panic("invalid PUB RAM");
/* extra check: we could rely on core_mmu_get_mem_by_type() */
if (!tee_vbuf_is_non_sec(s, e - s))
panic("PUB RAM is not non-secure");
#ifdef CFG_PL310
/* Allocate statically the l2cc mutex */
tee_l2cc_store_mutex_boot_pa(virt_to_phys((void *)s));
s += sizeof(uint32_t); /* size of a pl310 mutex */
s = ROUNDUP(s, SMALL_PAGE_SIZE); /* keep required alignment */
#endif
default_nsec_shm_paddr = virt_to_phys((void *)s);
default_nsec_shm_size = e - s;
}
uint32_t tee_mmu_user_get_cache_attr(struct user_ta_ctx *utc, void *va)
{
uint32_t attr;
if (tee_mmu_user_va2pa_attr(utc, va, NULL, &attr) != TEE_SUCCESS)
panic("cannot get attr");
return (attr >> TEE_MATTR_CACHE_SHIFT) & TEE_MATTR_CACHE_MASK;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_727_0 |
crossvul-cpp_data_bad_721_1 | /* Copyright (C) 2012 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \ingroup decode
*
* @{
*/
/**
* \file
*
* \author Eric Leblond <eric@regit.org>
*
* Decode Teredo Tunneling protocol.
*
* This implementation is based upon RFC 4380: http://www.ietf.org/rfc/rfc4380.txt
*/
#include "suricata-common.h"
#include "decode.h"
#include "decode-ipv6.h"
#include "decode-teredo.h"
#include "util-debug.h"
#include "conf.h"
#define TEREDO_ORIG_INDICATION_LENGTH 8
static bool g_teredo_enabled = true;
void DecodeTeredoConfig(void)
{
int enabled = 0;
if (ConfGetBool("decoder.teredo.enabled", &enabled) == 1) {
if (enabled) {
g_teredo_enabled = true;
} else {
g_teredo_enabled = false;
}
}
}
/**
* \brief Function to decode Teredo packets
*
* \retval TM_ECODE_FAILED if packet is not a Teredo packet, TM_ECODE_OK if it is
*/
int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
if (!g_teredo_enabled)
return TM_ECODE_FAILED;
uint8_t *start = pkt;
/* Is this packet to short to contain an IPv6 packet ? */
if (len < IPV6_HEADER_LEN)
return TM_ECODE_FAILED;
/* Teredo encapsulate IPv6 in UDP and can add some custom message
* part before the IPv6 packet. In our case, we just want to get
* over an ORIGIN indication. So we just make one offset if needed. */
if (start[0] == 0x0) {
switch (start[1]) {
/* origin indication: compatible with tunnel */
case 0x0:
/* offset is coherent with len and presence of an IPv6 header */
if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN)
start += TEREDO_ORIG_INDICATION_LENGTH;
else
return TM_ECODE_FAILED;
break;
/* authentication: negotiation not real tunnel */
case 0x1:
return TM_ECODE_FAILED;
/* this case is not possible in Teredo: not that protocol */
default:
return TM_ECODE_FAILED;
}
}
/* There is no specific field that we can check to prove that the packet
* is a Teredo packet. We've zapped here all the possible Teredo header
* and we should have an IPv6 packet at the start pointer.
* We then can only do two checks before sending the encapsulated packets
* to decoding:
* - The packet has a protocol version which is IPv6.
* - The IPv6 length of the packet matches what remains in buffer.
*/
if (IP_GET_RAW_VER(start) == 6) {
IPV6Hdr *thdr = (IPV6Hdr *)start;
if (len == IPV6_HEADER_LEN +
IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) {
if (pq != NULL) {
int blen = len - (start - pkt);
/* spawn off tunnel packet */
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen,
DECODE_TUNNEL_IPV6, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO);
/* add the tp to the packet queue. */
PacketEnqueue(pq,tp);
StatsIncr(tv, dtv->counter_teredo);
return TM_ECODE_OK;
}
}
}
return TM_ECODE_FAILED;
}
return TM_ECODE_FAILED;
}
/**
* @}
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_721_1 |
crossvul-cpp_data_bad_2174_1 | /*
* Copyright (c) Christos Zoulas 2003.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: readelf.c,v 1.102 2014/03/11 21:00:13 christos Exp $")
#endif
#ifdef BUILTIN_ELF
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "readelf.h"
#include "magic.h"
#ifdef ELFCORE
private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int *);
#endif
private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int *, int);
private int doshn(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int *, int, int);
private size_t donote(struct magic_set *, void *, size_t, size_t, int,
int, size_t, int *);
#define ELF_ALIGN(a) ((((a) + align - 1) / align) * align)
#define isquote(c) (strchr("'\"`", (c)) != NULL)
private uint16_t getu16(int, uint16_t);
private uint32_t getu32(int, uint32_t);
private uint64_t getu64(int, uint64_t);
private uint16_t
getu16(int swap, uint16_t value)
{
union {
uint16_t ui;
char c[2];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[1];
retval.c[1] = tmpval.c[0];
return retval.ui;
} else
return value;
}
private uint32_t
getu32(int swap, uint32_t value)
{
union {
uint32_t ui;
char c[4];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[3];
retval.c[1] = tmpval.c[2];
retval.c[2] = tmpval.c[1];
retval.c[3] = tmpval.c[0];
return retval.ui;
} else
return value;
}
private uint64_t
getu64(int swap, uint64_t value)
{
union {
uint64_t ui;
char c[8];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[7];
retval.c[1] = tmpval.c[6];
retval.c[2] = tmpval.c[5];
retval.c[3] = tmpval.c[4];
retval.c[4] = tmpval.c[3];
retval.c[5] = tmpval.c[2];
retval.c[6] = tmpval.c[1];
retval.c[7] = tmpval.c[0];
return retval.ui;
} else
return value;
}
#define elf_getu16(swap, value) getu16(swap, value)
#define elf_getu32(swap, value) getu32(swap, value)
#define elf_getu64(swap, value) getu64(swap, value)
#define xsh_addr (clazz == ELFCLASS32 \
? (void *)&sh32 \
: (void *)&sh64)
#define xsh_sizeof (clazz == ELFCLASS32 \
? sizeof(sh32) \
: sizeof(sh64))
#define xsh_size (size_t)(clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_size) \
: elf_getu64(swap, sh64.sh_size))
#define xsh_offset (off_t)(clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_offset) \
: elf_getu64(swap, sh64.sh_offset))
#define xsh_type (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_type) \
: elf_getu32(swap, sh64.sh_type))
#define xsh_name (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_name) \
: elf_getu32(swap, sh64.sh_name))
#define xph_addr (clazz == ELFCLASS32 \
? (void *) &ph32 \
: (void *) &ph64)
#define xph_sizeof (clazz == ELFCLASS32 \
? sizeof(ph32) \
: sizeof(ph64))
#define xph_type (clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_type) \
: elf_getu32(swap, ph64.p_type))
#define xph_offset (off_t)(clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_offset) \
: elf_getu64(swap, ph64.p_offset))
#define xph_align (size_t)((clazz == ELFCLASS32 \
? (off_t) (ph32.p_align ? \
elf_getu32(swap, ph32.p_align) : 4) \
: (off_t) (ph64.p_align ? \
elf_getu64(swap, ph64.p_align) : 4)))
#define xph_filesz (size_t)((clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_filesz) \
: elf_getu64(swap, ph64.p_filesz)))
#define xnh_addr (clazz == ELFCLASS32 \
? (void *)&nh32 \
: (void *)&nh64)
#define xph_memsz (size_t)((clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_memsz) \
: elf_getu64(swap, ph64.p_memsz)))
#define xnh_sizeof (clazz == ELFCLASS32 \
? sizeof nh32 \
: sizeof nh64)
#define xnh_type (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_type) \
: elf_getu32(swap, nh64.n_type))
#define xnh_namesz (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_namesz) \
: elf_getu32(swap, nh64.n_namesz))
#define xnh_descsz (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_descsz) \
: elf_getu32(swap, nh64.n_descsz))
#define prpsoffsets(i) (clazz == ELFCLASS32 \
? prpsoffsets32[i] \
: prpsoffsets64[i])
#define xcap_addr (clazz == ELFCLASS32 \
? (void *)&cap32 \
: (void *)&cap64)
#define xcap_sizeof (clazz == ELFCLASS32 \
? sizeof cap32 \
: sizeof cap64)
#define xcap_tag (clazz == ELFCLASS32 \
? elf_getu32(swap, cap32.c_tag) \
: elf_getu64(swap, cap64.c_tag))
#define xcap_val (clazz == ELFCLASS32 \
? elf_getu32(swap, cap32.c_un.c_val) \
: elf_getu64(swap, cap64.c_un.c_val))
#ifdef ELFCORE
/*
* Try larger offsets first to avoid false matches
* from earlier data that happen to look like strings.
*/
static const size_t prpsoffsets32[] = {
#ifdef USE_NT_PSINFO
104, /* SunOS 5.x (command line) */
88, /* SunOS 5.x (short name) */
#endif /* USE_NT_PSINFO */
100, /* SunOS 5.x (command line) */
84, /* SunOS 5.x (short name) */
44, /* Linux (command line) */
28, /* Linux 2.0.36 (short name) */
8, /* FreeBSD */
};
static const size_t prpsoffsets64[] = {
#ifdef USE_NT_PSINFO
152, /* SunOS 5.x (command line) */
136, /* SunOS 5.x (short name) */
#endif /* USE_NT_PSINFO */
136, /* SunOS 5.x, 64-bit (command line) */
120, /* SunOS 5.x, 64-bit (short name) */
56, /* Linux (command line) */
40, /* Linux (tested on core from 2.4.x, short name) */
16, /* FreeBSD, 64-bit */
};
#define NOFFSETS32 (sizeof prpsoffsets32 / sizeof prpsoffsets32[0])
#define NOFFSETS64 (sizeof prpsoffsets64 / sizeof prpsoffsets64[0])
#define NOFFSETS (clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64)
/*
* Look through the program headers of an executable image, searching
* for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or
* "FreeBSD"; if one is found, try looking in various places in its
* contents for a 16-character string containing only printable
* characters - if found, that string should be the name of the program
* that dropped core. Note: right after that 16-character string is,
* at least in SunOS 5.x (and possibly other SVR4-flavored systems) and
* Linux, a longer string (80 characters, in 5.x, probably other
* SVR4-flavored systems, and Linux) containing the start of the
* command line for that program.
*
* SunOS 5.x core files contain two PT_NOTE sections, with the types
* NT_PRPSINFO (old) and NT_PSINFO (new). These structs contain the
* same info about the command name and command line, so it probably
* isn't worthwhile to look for NT_PSINFO, but the offsets are provided
* above (see USE_NT_PSINFO), in case we ever decide to do so. The
* NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent;
* the SunOS 5.x file command relies on this (and prefers the latter).
*
* The signal number probably appears in a section of type NT_PRSTATUS,
* but that's also rather OS-dependent, in ways that are harder to
* dissect with heuristics, so I'm not bothering with the signal number.
* (I suppose the signal number could be of interest in situations where
* you don't have the binary of the program that dropped core; if you
* *do* have that binary, the debugger will probably tell you what
* signal it was.)
*/
#define OS_STYLE_SVR4 0
#define OS_STYLE_FREEBSD 1
#define OS_STYLE_NETBSD 2
private const char os_style_names[][8] = {
"SVR4",
"FreeBSD",
"NetBSD",
};
#define FLAGS_DID_CORE 0x01
#define FLAGS_DID_NOTE 0x02
#define FLAGS_DID_BUILD_ID 0x04
#define FLAGS_DID_CORE_STYLE 0x08
#define FLAGS_IS_CORE 0x10
private int
dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) == -1) {
file_badread(ms);
return -1;
}
off += size;
if (xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags);
if (offset == 0)
break;
}
}
return 0;
}
#endif
static void
do_note_netbsd_version(struct magic_set *ms, int swap, void *v)
{
uint32_t desc;
(void)memcpy(&desc, v, sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, ", for NetBSD") == -1)
return;
/*
* The version number used to be stuck as 199905, and was thus
* basically content-free. Newer versions of NetBSD have fixed
* this and now use the encoding of __NetBSD_Version__:
*
* MMmmrrpp00
*
* M = major version
* m = minor version
* r = release ["",A-Z,Z[A-Z] but numeric]
* p = patchlevel
*/
if (desc > 100000000U) {
uint32_t ver_patch = (desc / 100) % 100;
uint32_t ver_rel = (desc / 10000) % 100;
uint32_t ver_min = (desc / 1000000) % 100;
uint32_t ver_maj = desc / 100000000;
if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1)
return;
if (ver_rel == 0 && ver_patch != 0) {
if (file_printf(ms, ".%u", ver_patch) == -1)
return;
} else if (ver_rel != 0) {
while (ver_rel > 26) {
if (file_printf(ms, "Z") == -1)
return;
ver_rel -= 26;
}
if (file_printf(ms, "%c", 'A' + ver_rel - 1)
== -1)
return;
}
}
}
static void
do_note_freebsd_version(struct magic_set *ms, int swap, void *v)
{
uint32_t desc;
(void)memcpy(&desc, v, sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, ", for FreeBSD") == -1)
return;
/*
* Contents is __FreeBSD_version, whose relation to OS
* versions is defined by a huge table in the Porter's
* Handbook. This is the general scheme:
*
* Releases:
* Mmp000 (before 4.10)
* Mmi0p0 (before 5.0)
* Mmm0p0
*
* Development branches:
* Mmpxxx (before 4.6)
* Mmp1xx (before 4.10)
* Mmi1xx (before 5.0)
* M000xx (pre-M.0)
* Mmm1xx
*
* M = major version
* m = minor version
* i = minor version increment (491000 -> 4.10)
* p = patchlevel
* x = revision
*
* The first release of FreeBSD to use ELF by default
* was version 3.0.
*/
if (desc == 460002) {
if (file_printf(ms, " 4.6.2") == -1)
return;
} else if (desc < 460100) {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 10000 % 10) == -1)
return;
if (desc / 1000 % 10 > 0)
if (file_printf(ms, ".%d", desc / 1000 % 10) == -1)
return;
if ((desc % 1000 > 0) || (desc % 100000 == 0))
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc < 500000) {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 10000 % 10 + desc / 1000 % 10) == -1)
return;
if (desc / 100 % 10 > 0) {
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc / 10 % 10 > 0) {
if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
return;
}
} else {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 1000 % 100) == -1)
return;
if ((desc / 100 % 10 > 0) ||
(desc % 100000 / 100 == 0)) {
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc / 10 % 10 > 0) {
if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
return;
}
}
}
private size_t
donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
#ifdef ELFCORE
int os_style = -1;
#endif
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return offset;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return offset;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
(FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
goto core;
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 2) {
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
(void)memcpy(desc, &nbuf[doff], sizeof(desc));
if (file_printf(ms, ", for GNU/") == -1)
return size;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return size;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return size;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return size;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return size;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return size;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return size;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return size;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return size;
*flags |= FLAGS_DID_BUILD_ID;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
xnh_type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return size;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return size;
}
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
if (descsz == 4) {
do_note_netbsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
break;
case NT_NETBSD_MARCH:
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
do_note_freebsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
if (file_printf(ms, ", for OpenBSD") == -1)
return size;
/* Content of note is always 0 */
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
if (file_printf(ms, ", for DragonFly") == -1)
return size;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
core:
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
#ifdef ELFCORE
if ((*flags & FLAGS_DID_CORE) != 0)
return size;
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return size;
*flags |= FLAGS_DID_CORE_STYLE;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
uint32_t signo;
/*
* Extract the program name. It is at
* offset 0x7c, and is up to 32-bytes,
* including the terminating NUL.
*/
if (file_printf(ms, ", from '%.31s'",
&nbuf[doff + 0x7c]) == -1)
return size;
/*
* Extract the signal number. It is at
* offset 0x08.
*/
(void)memcpy(&signo, &nbuf[doff + 0x08],
sizeof(signo));
if (file_printf(ms, " (signal %u)",
elf_getu32(swap, signo)) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
}
break;
default:
if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS ; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
tryanother:
;
}
}
break;
}
#endif
return offset;
}
/* SunOS 5.x hardware capability descriptions */
typedef struct cap_desc {
uint64_t cd_mask;
const char *cd_name;
} cap_desc_t;
static const cap_desc_t cap_desc_sparc[] = {
{ AV_SPARC_MUL32, "MUL32" },
{ AV_SPARC_DIV32, "DIV32" },
{ AV_SPARC_FSMULD, "FSMULD" },
{ AV_SPARC_V8PLUS, "V8PLUS" },
{ AV_SPARC_POPC, "POPC" },
{ AV_SPARC_VIS, "VIS" },
{ AV_SPARC_VIS2, "VIS2" },
{ AV_SPARC_ASI_BLK_INIT, "ASI_BLK_INIT" },
{ AV_SPARC_FMAF, "FMAF" },
{ AV_SPARC_FJFMAU, "FJFMAU" },
{ AV_SPARC_IMA, "IMA" },
{ 0, NULL }
};
static const cap_desc_t cap_desc_386[] = {
{ AV_386_FPU, "FPU" },
{ AV_386_TSC, "TSC" },
{ AV_386_CX8, "CX8" },
{ AV_386_SEP, "SEP" },
{ AV_386_AMD_SYSC, "AMD_SYSC" },
{ AV_386_CMOV, "CMOV" },
{ AV_386_MMX, "MMX" },
{ AV_386_AMD_MMX, "AMD_MMX" },
{ AV_386_AMD_3DNow, "AMD_3DNow" },
{ AV_386_AMD_3DNowx, "AMD_3DNowx" },
{ AV_386_FXSR, "FXSR" },
{ AV_386_SSE, "SSE" },
{ AV_386_SSE2, "SSE2" },
{ AV_386_PAUSE, "PAUSE" },
{ AV_386_SSE3, "SSE3" },
{ AV_386_MON, "MON" },
{ AV_386_CX16, "CX16" },
{ AV_386_AHF, "AHF" },
{ AV_386_TSCP, "TSCP" },
{ AV_386_AMD_SSE4A, "AMD_SSE4A" },
{ AV_386_POPCNT, "POPCNT" },
{ AV_386_AMD_LZCNT, "AMD_LZCNT" },
{ AV_386_SSSE3, "SSSE3" },
{ AV_386_SSE4_1, "SSE4.1" },
{ AV_386_SSE4_2, "SSE4.2" },
{ 0, NULL }
};
private int
doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,
size_t size, off_t fsize, int *flags, int mach, int strtab)
{
Elf32_Shdr sh32;
Elf64_Shdr sh64;
int stripped = 1;
void *nbuf;
off_t noff, coff, name_off;
uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */
uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */
char name[50];
if (size != xsh_sizeof) {
if (file_printf(ms, ", corrupted section header size") == -1)
return -1;
return 0;
}
/* Read offset of name section to be able to read section names later */
if (pread(fd, xsh_addr, xsh_sizeof, off + size * strtab) == -1) {
file_badread(ms);
return -1;
}
name_off = xsh_offset;
for ( ; num; num--) {
/* Read the name of this section. */
if (pread(fd, name, sizeof(name), name_off + xsh_name) == -1) {
file_badread(ms);
return -1;
}
name[sizeof(name) - 1] = '\0';
if (strcmp(name, ".debug_info") == 0)
stripped = 0;
if (pread(fd, xsh_addr, xsh_sizeof, off) == -1) {
file_badread(ms);
return -1;
}
off += size;
/* Things we can determine before we seek */
switch (xsh_type) {
case SHT_SYMTAB:
#if 0
case SHT_DYNSYM:
#endif
stripped = 0;
break;
default:
if (xsh_offset > fsize) {
/* Perhaps warn here */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xsh_type) {
case SHT_NOTE:
if ((nbuf = malloc(xsh_size)) == NULL) {
file_error(ms, errno, "Cannot allocate memory"
" for note");
return -1;
}
if (pread(fd, nbuf, xsh_size, xsh_offset) == -1) {
file_badread(ms);
free(nbuf);
return -1;
}
noff = 0;
for (;;) {
if (noff >= (off_t)xsh_size)
break;
noff = donote(ms, nbuf, (size_t)noff,
xsh_size, clazz, swap, 4, flags);
if (noff == 0)
break;
}
free(nbuf);
break;
case SHT_SUNW_cap:
switch (mach) {
case EM_SPARC:
case EM_SPARCV9:
case EM_IA_64:
case EM_386:
case EM_AMD64:
break;
default:
goto skip;
}
if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) {
file_badseek(ms);
return -1;
}
coff = 0;
for (;;) {
Elf32_Cap cap32;
Elf64_Cap cap64;
char cbuf[/*CONSTCOND*/
MAX(sizeof cap32, sizeof cap64)];
if ((coff += xcap_sizeof) > (off_t)xsh_size)
break;
if (read(fd, cbuf, (size_t)xcap_sizeof) !=
(ssize_t)xcap_sizeof) {
file_badread(ms);
return -1;
}
if (cbuf[0] == 'A') {
#ifdef notyet
char *p = cbuf + 1;
uint32_t len, tag;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (memcmp("gnu", p, 3) != 0) {
if (file_printf(ms,
", unknown capability %.3s", p)
== -1)
return -1;
break;
}
p += strlen(p) + 1;
tag = *p++;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (tag != 1) {
if (file_printf(ms, ", unknown gnu"
" capability tag %d", tag)
== -1)
return -1;
break;
}
// gnu attributes
#endif
break;
}
(void)memcpy(xcap_addr, cbuf, xcap_sizeof);
switch (xcap_tag) {
case CA_SUNW_NULL:
break;
case CA_SUNW_HW_1:
cap_hw1 |= xcap_val;
break;
case CA_SUNW_SF_1:
cap_sf1 |= xcap_val;
break;
default:
if (file_printf(ms,
", with unknown capability "
"0x%" INT64_T_FORMAT "x = 0x%"
INT64_T_FORMAT "x",
(unsigned long long)xcap_tag,
(unsigned long long)xcap_val) == -1)
return -1;
break;
}
}
/*FALLTHROUGH*/
skip:
default:
break;
}
}
if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1)
return -1;
if (cap_hw1) {
const cap_desc_t *cdp;
switch (mach) {
case EM_SPARC:
case EM_SPARC32PLUS:
case EM_SPARCV9:
cdp = cap_desc_sparc;
break;
case EM_386:
case EM_IA_64:
case EM_AMD64:
cdp = cap_desc_386;
break;
default:
cdp = NULL;
break;
}
if (file_printf(ms, ", uses") == -1)
return -1;
if (cdp) {
while (cdp->cd_name) {
if (cap_hw1 & cdp->cd_mask) {
if (file_printf(ms,
" %s", cdp->cd_name) == -1)
return -1;
cap_hw1 &= ~cdp->cd_mask;
}
++cdp;
}
if (cap_hw1)
if (file_printf(ms,
" unknown hardware capability 0x%"
INT64_T_FORMAT "x",
(unsigned long long)cap_hw1) == -1)
return -1;
} else {
if (file_printf(ms,
" hardware capability 0x%" INT64_T_FORMAT "x",
(unsigned long long)cap_hw1) == -1)
return -1;
}
}
if (cap_sf1) {
if (cap_sf1 & SF1_SUNW_FPUSED) {
if (file_printf(ms,
(cap_sf1 & SF1_SUNW_FPKNWN)
? ", uses frame pointer"
: ", not known to use frame pointer") == -1)
return -1;
}
cap_sf1 &= ~SF1_SUNW_MASK;
if (cap_sf1)
if (file_printf(ms,
", with unknown software capability 0x%"
INT64_T_FORMAT "x",
(unsigned long long)cap_sf1) == -1)
return -1;
}
return 0;
}
/*
* Look through the program headers of an executable image, searching
* for a PT_INTERP section; if one is found, it's dynamically linked,
* otherwise it's statically linked.
*/
private int
dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, int sh_num)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *shared_libraries = "";
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) == -1) {
file_badread(ms);
return -1;
}
off += size;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_INTERP:
shared_libraries = " (uses shared libs)";
break;
default:
if (xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_NOTE:
if ((align = xph_align) & 0x80000000UL) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
if (sh_num)
break;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked%s", linking_style, shared_libraries)
== -1)
return -1;
return 0;
}
protected int
file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf,
size_t nbytes)
{
union {
int32_t l;
char c[sizeof (int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) && (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
fsize = st.st_size;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2174_1 |
crossvul-cpp_data_good_5613_1 | /*
* Kernel-based Virtual Machine driver for Linux
*
* This module enables machines with Intel VT-x extensions to run virtual
* machines without emulation or binary translation.
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include "iodev.h"
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/percpu.h>
#include <linux/mm.h>
#include <linux/miscdevice.h>
#include <linux/vmalloc.h>
#include <linux/reboot.h>
#include <linux/debugfs.h>
#include <linux/highmem.h>
#include <linux/file.h>
#include <linux/syscore_ops.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/cpumask.h>
#include <linux/smp.h>
#include <linux/anon_inodes.h>
#include <linux/profile.h>
#include <linux/kvm_para.h>
#include <linux/pagemap.h>
#include <linux/mman.h>
#include <linux/swap.h>
#include <linux/bitops.h>
#include <linux/spinlock.h>
#include <linux/compat.h>
#include <linux/srcu.h>
#include <linux/hugetlb.h>
#include <linux/slab.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include "coalesced_mmio.h"
#include "async_pf.h"
#define CREATE_TRACE_POINTS
#include <trace/events/kvm.h>
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
/*
* Ordering of locks:
*
* kvm->lock --> kvm->slots_lock --> kvm->irq_lock
*/
DEFINE_RAW_SPINLOCK(kvm_lock);
LIST_HEAD(vm_list);
static cpumask_var_t cpus_hardware_enabled;
static int kvm_usage_count = 0;
static atomic_t hardware_enable_failed;
struct kmem_cache *kvm_vcpu_cache;
EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
static __read_mostly struct preempt_ops kvm_preempt_ops;
struct dentry *kvm_debugfs_dir;
static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg);
static int hardware_enable_all(void);
static void hardware_disable_all(void);
static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
bool kvm_rebooting;
EXPORT_SYMBOL_GPL(kvm_rebooting);
static bool largepages_enabled = true;
static struct page *hwpoison_page;
static pfn_t hwpoison_pfn;
static struct page *fault_page;
static pfn_t fault_pfn;
inline int kvm_is_mmio_pfn(pfn_t pfn)
{
if (pfn_valid(pfn)) {
int reserved;
struct page *tail = pfn_to_page(pfn);
struct page *head = compound_trans_head(tail);
reserved = PageReserved(head);
if (head != tail) {
/*
* "head" is not a dangling pointer
* (compound_trans_head takes care of that)
* but the hugepage may have been splitted
* from under us (and we may not hold a
* reference count on the head page so it can
* be reused before we run PageReferenced), so
* we've to check PageTail before returning
* what we just read.
*/
smp_rmb();
if (PageTail(tail))
return reserved;
}
return PageReserved(tail);
}
return true;
}
/*
* Switches to specified vcpu, until a matching vcpu_put()
*/
void vcpu_load(struct kvm_vcpu *vcpu)
{
int cpu;
mutex_lock(&vcpu->mutex);
if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
/* The thread running this VCPU changed. */
struct pid *oldpid = vcpu->pid;
struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
rcu_assign_pointer(vcpu->pid, newpid);
synchronize_rcu();
put_pid(oldpid);
}
cpu = get_cpu();
preempt_notifier_register(&vcpu->preempt_notifier);
kvm_arch_vcpu_load(vcpu, cpu);
put_cpu();
}
void vcpu_put(struct kvm_vcpu *vcpu)
{
preempt_disable();
kvm_arch_vcpu_put(vcpu);
preempt_notifier_unregister(&vcpu->preempt_notifier);
preempt_enable();
mutex_unlock(&vcpu->mutex);
}
static void ack_flush(void *_completed)
{
}
static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
{
int i, cpu, me;
cpumask_var_t cpus;
bool called = true;
struct kvm_vcpu *vcpu;
zalloc_cpumask_var(&cpus, GFP_ATOMIC);
me = get_cpu();
kvm_for_each_vcpu(i, vcpu, kvm) {
kvm_make_request(req, vcpu);
cpu = vcpu->cpu;
/* Set ->requests bit before we read ->mode */
smp_mb();
if (cpus != NULL && cpu != -1 && cpu != me &&
kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
cpumask_set_cpu(cpu, cpus);
}
if (unlikely(cpus == NULL))
smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
else if (!cpumask_empty(cpus))
smp_call_function_many(cpus, ack_flush, NULL, 1);
else
called = false;
put_cpu();
free_cpumask_var(cpus);
return called;
}
void kvm_flush_remote_tlbs(struct kvm *kvm)
{
int dirty_count = kvm->tlbs_dirty;
smp_mb();
if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
++kvm->stat.remote_tlb_flush;
cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
}
void kvm_reload_remote_mmus(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
}
int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
{
struct page *page;
int r;
mutex_init(&vcpu->mutex);
vcpu->cpu = -1;
vcpu->kvm = kvm;
vcpu->vcpu_id = id;
vcpu->pid = NULL;
init_waitqueue_head(&vcpu->wq);
kvm_async_pf_vcpu_init(vcpu);
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->run = page_address(page);
r = kvm_arch_vcpu_init(vcpu);
if (r < 0)
goto fail_free_run;
return 0;
fail_free_run:
free_page((unsigned long)vcpu->run);
fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_vcpu_init);
void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
{
put_pid(vcpu->pid);
kvm_arch_vcpu_uninit(vcpu);
free_page((unsigned long)vcpu->run);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
{
return container_of(mn, struct kvm, mmu_notifier);
}
static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush, idx;
/*
* When ->invalidate_page runs, the linux pte has been zapped
* already but the page is still allocated until
* ->invalidate_page returns. So if we increase the sequence
* here the kvm page fault will notice if the spte can't be
* established because the page is going to be freed. If
* instead the kvm page fault establishes the spte before
* ->invalidate_page runs, kvm_unmap_hva will release it
* before returning.
*
* The sequence increase only need to be seen at spin_unlock
* time, and not at spin_lock time.
*
* Increasing the sequence after the spin_unlock would be
* unsafe because the kvm page fault could then establish the
* pte after kvm_unmap_hva returned, without noticing the page
* is going to be freed.
*/
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
}
static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address,
pte_t pte)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
kvm_set_spte_hva(kvm, address, pte);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush = 0, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
/*
* The count increase must become visible at unlock time as no
* spte can be established without taking the mmu_lock and
* count is also read inside the mmu_lock critical section.
*/
kvm->mmu_notifier_count++;
for (; start < end; start += PAGE_SIZE)
need_tlb_flush |= kvm_unmap_hva(kvm, start);
need_tlb_flush |= kvm->tlbs_dirty;
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
}
static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
spin_lock(&kvm->mmu_lock);
/*
* This sequence increase will notify the kvm page fault that
* the page that is going to be mapped in the spte could have
* been freed.
*/
kvm->mmu_notifier_seq++;
/*
* The above sequence increase must be visible before the
* below count decrease but both values are read by the kvm
* page fault under mmu_lock spinlock so we don't need to add
* a smb_wmb() here in between the two.
*/
kvm->mmu_notifier_count--;
spin_unlock(&kvm->mmu_lock);
BUG_ON(kvm->mmu_notifier_count < 0);
}
static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_age_hva(kvm, address);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
if (young)
kvm_flush_remote_tlbs(kvm);
return young;
}
static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_test_age_hva(kvm, address);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
return young;
}
static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
struct mm_struct *mm)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
kvm_arch_flush_shadow(kvm);
srcu_read_unlock(&kvm->srcu, idx);
}
static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
.invalidate_page = kvm_mmu_notifier_invalidate_page,
.invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
.invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
.clear_flush_young = kvm_mmu_notifier_clear_flush_young,
.test_young = kvm_mmu_notifier_test_young,
.change_pte = kvm_mmu_notifier_change_pte,
.release = kvm_mmu_notifier_release,
};
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
}
#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
return 0;
}
#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
static struct kvm *kvm_create_vm(void)
{
int r, i;
struct kvm *kvm = kvm_arch_alloc_vm();
if (!kvm)
return ERR_PTR(-ENOMEM);
r = kvm_arch_init_vm(kvm);
if (r)
goto out_err_nodisable;
r = hardware_enable_all();
if (r)
goto out_err_nodisable;
#ifdef CONFIG_HAVE_KVM_IRQCHIP
INIT_HLIST_HEAD(&kvm->mask_notifier_list);
INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
#endif
r = -ENOMEM;
kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!kvm->memslots)
goto out_err_nosrcu;
if (init_srcu_struct(&kvm->srcu))
goto out_err_nosrcu;
for (i = 0; i < KVM_NR_BUSES; i++) {
kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
GFP_KERNEL);
if (!kvm->buses[i])
goto out_err;
}
r = kvm_init_mmu_notifier(kvm);
if (r)
goto out_err;
kvm->mm = current->mm;
atomic_inc(&kvm->mm->mm_count);
spin_lock_init(&kvm->mmu_lock);
kvm_eventfd_init(kvm);
mutex_init(&kvm->lock);
mutex_init(&kvm->irq_lock);
mutex_init(&kvm->slots_lock);
atomic_set(&kvm->users_count, 1);
raw_spin_lock(&kvm_lock);
list_add(&kvm->vm_list, &vm_list);
raw_spin_unlock(&kvm_lock);
return kvm;
out_err:
cleanup_srcu_struct(&kvm->srcu);
out_err_nosrcu:
hardware_disable_all();
out_err_nodisable:
for (i = 0; i < KVM_NR_BUSES; i++)
kfree(kvm->buses[i]);
kfree(kvm->memslots);
kvm_arch_free_vm(kvm);
return ERR_PTR(r);
}
static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
{
if (!memslot->dirty_bitmap)
return;
if (2 * kvm_dirty_bitmap_bytes(memslot) > PAGE_SIZE)
vfree(memslot->dirty_bitmap_head);
else
kfree(memslot->dirty_bitmap_head);
memslot->dirty_bitmap = NULL;
memslot->dirty_bitmap_head = NULL;
}
/*
* Free any memory in @free but not in @dont.
*/
static void kvm_free_physmem_slot(struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
int i;
if (!dont || free->rmap != dont->rmap)
vfree(free->rmap);
if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
kvm_destroy_dirty_bitmap(free);
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
if (!dont || free->lpage_info[i] != dont->lpage_info[i]) {
vfree(free->lpage_info[i]);
free->lpage_info[i] = NULL;
}
}
free->npages = 0;
free->rmap = NULL;
}
void kvm_free_physmem(struct kvm *kvm)
{
int i;
struct kvm_memslots *slots = kvm->memslots;
for (i = 0; i < slots->nmemslots; ++i)
kvm_free_physmem_slot(&slots->memslots[i], NULL);
kfree(kvm->memslots);
}
static void kvm_destroy_vm(struct kvm *kvm)
{
int i;
struct mm_struct *mm = kvm->mm;
kvm_arch_sync_events(kvm);
raw_spin_lock(&kvm_lock);
list_del(&kvm->vm_list);
raw_spin_unlock(&kvm_lock);
kvm_free_irq_routing(kvm);
for (i = 0; i < KVM_NR_BUSES; i++)
kvm_io_bus_destroy(kvm->buses[i]);
kvm_coalesced_mmio_free(kvm);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
#else
kvm_arch_flush_shadow(kvm);
#endif
kvm_arch_destroy_vm(kvm);
kvm_free_physmem(kvm);
cleanup_srcu_struct(&kvm->srcu);
kvm_arch_free_vm(kvm);
hardware_disable_all();
mmdrop(mm);
}
void kvm_get_kvm(struct kvm *kvm)
{
atomic_inc(&kvm->users_count);
}
EXPORT_SYMBOL_GPL(kvm_get_kvm);
void kvm_put_kvm(struct kvm *kvm)
{
if (atomic_dec_and_test(&kvm->users_count))
kvm_destroy_vm(kvm);
}
EXPORT_SYMBOL_GPL(kvm_put_kvm);
static int kvm_vm_release(struct inode *inode, struct file *filp)
{
struct kvm *kvm = filp->private_data;
kvm_irqfd_release(kvm);
kvm_put_kvm(kvm);
return 0;
}
#ifndef CONFIG_S390
/*
* Allocation size is twice as large as the actual dirty bitmap size.
* This makes it possible to do double buffering: see x86's
* kvm_vm_ioctl_get_dirty_log().
*/
static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
{
unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
if (dirty_bytes > PAGE_SIZE)
memslot->dirty_bitmap = vzalloc(dirty_bytes);
else
memslot->dirty_bitmap = kzalloc(dirty_bytes, GFP_KERNEL);
if (!memslot->dirty_bitmap)
return -ENOMEM;
memslot->dirty_bitmap_head = memslot->dirty_bitmap;
return 0;
}
#endif /* !CONFIG_S390 */
/*
* Allocate some memory and give it an address in the guest physical address
* space.
*
* Discontiguous memory is allowed, mostly for framebuffers.
*
* Must be called holding mmap_sem for write.
*/
int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
gfn_t base_gfn;
unsigned long npages;
unsigned long i;
struct kvm_memory_slot *memslot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots, *old_memslots;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if (user_alloc &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE, mem->userspace_addr, mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
memslot = &kvm->memslots->memslots[mem->slot];
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *memslot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
/* Disallow changing a memory slot's size. */
r = -EINVAL;
if (npages && old.npages && npages != old.npages)
goto out_free;
/* Check for overlaps */
r = -EEXIST;
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *s = &kvm->memslots->memslots[i];
if (s == memslot || !s->npages)
continue;
if (!((base_gfn + npages <= s->base_gfn) ||
(base_gfn >= s->base_gfn + s->npages)))
goto out_free;
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
/* Allocate if a slot is being created */
#ifndef CONFIG_S390
if (npages && !new.rmap) {
new.rmap = vzalloc(npages * sizeof(*new.rmap));
if (!new.rmap)
goto out_free;
new.user_alloc = user_alloc;
new.userspace_addr = mem->userspace_addr;
}
if (!npages)
goto skip_lpage;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i) {
unsigned long ugfn;
unsigned long j;
int lpages;
int level = i + 2;
/* Avoid unused variable warning if no large pages */
(void)level;
if (new.lpage_info[i])
continue;
lpages = 1 + ((base_gfn + npages - 1)
>> KVM_HPAGE_GFN_SHIFT(level));
lpages -= base_gfn >> KVM_HPAGE_GFN_SHIFT(level);
new.lpage_info[i] = vzalloc(lpages * sizeof(*new.lpage_info[i]));
if (!new.lpage_info[i])
goto out_free;
if (base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][0].write_count = 1;
if ((base_gfn+npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
new.lpage_info[i][lpages - 1].write_count = 1;
ugfn = new.userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!largepages_enabled)
for (j = 0; j < lpages; ++j)
new.lpage_info[i][j].write_count = 1;
}
skip_lpage:
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
/* destroy any largepage mappings for dirty tracking */
}
#else /* not defined CONFIG_S390 */
new.user_alloc = user_alloc;
if (user_alloc)
new.userspace_addr = mem->userspace_addr;
#endif /* not defined CONFIG_S390 */
if (!npages) {
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
slots->memslots[mem->slot].flags |= KVM_MEMSLOT_INVALID;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
/* From this point no new shadow pages pointing to a deleted
* memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow(kvm);
kfree(old_memslots);
}
r = kvm_arch_prepare_memory_region(kvm, &new, old, mem, user_alloc);
if (r)
goto out_free;
/* map the pages in iommu page table */
if (npages) {
r = kvm_iommu_map_pages(kvm, &new);
if (r)
goto out_free;
}
r = -ENOMEM;
slots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!slots)
goto out_free;
memcpy(slots, kvm->memslots, sizeof(struct kvm_memslots));
if (mem->slot >= slots->nmemslots)
slots->nmemslots = mem->slot + 1;
slots->generation++;
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (!npages) {
new.rmap = NULL;
new.dirty_bitmap = NULL;
for (i = 0; i < KVM_NR_PAGE_SIZES - 1; ++i)
new.lpage_info[i] = NULL;
}
slots->memslots[mem->slot] = new;
old_memslots = kvm->memslots;
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_commit_memory_region(kvm, mem, old, user_alloc);
kvm_free_physmem_slot(&old, &new);
kfree(old_memslots);
return 0;
out_free:
kvm_free_physmem_slot(&new, &old);
out:
return r;
}
EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
int kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
int user_alloc)
{
int r;
mutex_lock(&kvm->slots_lock);
r = __kvm_set_memory_region(kvm, mem, user_alloc);
mutex_unlock(&kvm->slots_lock);
return r;
}
EXPORT_SYMBOL_GPL(kvm_set_memory_region);
int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
struct
kvm_userspace_memory_region *mem,
int user_alloc)
{
if (mem->slot >= KVM_MEMORY_SLOTS)
return -EINVAL;
return kvm_set_memory_region(kvm, mem, user_alloc);
}
int kvm_get_dirty_log(struct kvm *kvm,
struct kvm_dirty_log *log, int *is_dirty)
{
struct kvm_memory_slot *memslot;
int r, i;
unsigned long n;
unsigned long any = 0;
r = -EINVAL;
if (log->slot >= KVM_MEMORY_SLOTS)
goto out;
memslot = &kvm->memslots->memslots[log->slot];
r = -ENOENT;
if (!memslot->dirty_bitmap)
goto out;
n = kvm_dirty_bitmap_bytes(memslot);
for (i = 0; !any && i < n/sizeof(long); ++i)
any = memslot->dirty_bitmap[i];
r = -EFAULT;
if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
goto out;
if (any)
*is_dirty = 1;
r = 0;
out:
return r;
}
void kvm_disable_largepages(void)
{
largepages_enabled = false;
}
EXPORT_SYMBOL_GPL(kvm_disable_largepages);
int is_error_page(struct page *page)
{
return page == bad_page || page == hwpoison_page || page == fault_page;
}
EXPORT_SYMBOL_GPL(is_error_page);
int is_error_pfn(pfn_t pfn)
{
return pfn == bad_pfn || pfn == hwpoison_pfn || pfn == fault_pfn;
}
EXPORT_SYMBOL_GPL(is_error_pfn);
int is_hwpoison_pfn(pfn_t pfn)
{
return pfn == hwpoison_pfn;
}
EXPORT_SYMBOL_GPL(is_hwpoison_pfn);
int is_fault_pfn(pfn_t pfn)
{
return pfn == fault_pfn;
}
EXPORT_SYMBOL_GPL(is_fault_pfn);
static inline unsigned long bad_hva(void)
{
return PAGE_OFFSET;
}
int kvm_is_error_hva(unsigned long addr)
{
return addr == bad_hva();
}
EXPORT_SYMBOL_GPL(kvm_is_error_hva);
static struct kvm_memory_slot *__gfn_to_memslot(struct kvm_memslots *slots,
gfn_t gfn)
{
int i;
for (i = 0; i < slots->nmemslots; ++i) {
struct kvm_memory_slot *memslot = &slots->memslots[i];
if (gfn >= memslot->base_gfn
&& gfn < memslot->base_gfn + memslot->npages)
return memslot;
}
return NULL;
}
struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_memslot(kvm_memslots(kvm), gfn);
}
EXPORT_SYMBOL_GPL(gfn_to_memslot);
int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
{
int i;
struct kvm_memslots *slots = kvm_memslots(kvm);
for (i = 0; i < KVM_MEMORY_SLOTS; ++i) {
struct kvm_memory_slot *memslot = &slots->memslots[i];
if (memslot->flags & KVM_MEMSLOT_INVALID)
continue;
if (gfn >= memslot->base_gfn
&& gfn < memslot->base_gfn + memslot->npages)
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
{
struct vm_area_struct *vma;
unsigned long addr, size;
size = PAGE_SIZE;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return PAGE_SIZE;
down_read(¤t->mm->mmap_sem);
vma = find_vma(current->mm, addr);
if (!vma)
goto out;
size = vma_kernel_pagesize(vma);
out:
up_read(¤t->mm->mmap_sem);
return size;
}
static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
gfn_t *nr_pages)
{
if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
return bad_hva();
if (nr_pages)
*nr_pages = slot->npages - (gfn - slot->base_gfn);
return gfn_to_hva_memslot(slot, gfn);
}
unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
{
return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_hva);
static pfn_t get_fault_pfn(void)
{
get_page(fault_page);
return fault_pfn;
}
int get_user_page_nowait(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, int write, struct page **page)
{
int flags = FOLL_TOUCH | FOLL_NOWAIT | FOLL_HWPOISON | FOLL_GET;
if (write)
flags |= FOLL_WRITE;
return __get_user_pages(tsk, mm, start, 1, flags, page, NULL, NULL);
}
static inline int check_user_page_hwpoison(unsigned long addr)
{
int rc, flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_WRITE;
rc = __get_user_pages(current, current->mm, addr, 1,
flags, NULL, NULL, NULL);
return rc == -EHWPOISON;
}
static pfn_t hva_to_pfn(struct kvm *kvm, unsigned long addr, bool atomic,
bool *async, bool write_fault, bool *writable)
{
struct page *page[1];
int npages = 0;
pfn_t pfn;
/* we can do it either atomically or asynchronously, not both */
BUG_ON(atomic && async);
BUG_ON(!write_fault && !writable);
if (writable)
*writable = true;
if (atomic || async)
npages = __get_user_pages_fast(addr, 1, 1, page);
if (unlikely(npages != 1) && !atomic) {
might_sleep();
if (writable)
*writable = write_fault;
if (async) {
down_read(¤t->mm->mmap_sem);
npages = get_user_page_nowait(current, current->mm,
addr, write_fault, page);
up_read(¤t->mm->mmap_sem);
} else
npages = get_user_pages_fast(addr, 1, write_fault,
page);
/* map read fault as writable if possible */
if (unlikely(!write_fault) && npages == 1) {
struct page *wpage[1];
npages = __get_user_pages_fast(addr, 1, 1, wpage);
if (npages == 1) {
*writable = true;
put_page(page[0]);
page[0] = wpage[0];
}
npages = 1;
}
}
if (unlikely(npages != 1)) {
struct vm_area_struct *vma;
if (atomic)
return get_fault_pfn();
down_read(¤t->mm->mmap_sem);
if (npages == -EHWPOISON ||
(!async && check_user_page_hwpoison(addr))) {
up_read(¤t->mm->mmap_sem);
get_page(hwpoison_page);
return page_to_pfn(hwpoison_page);
}
vma = find_vma_intersection(current->mm, addr, addr+1);
if (vma == NULL)
pfn = get_fault_pfn();
else if ((vma->vm_flags & VM_PFNMAP)) {
pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
vma->vm_pgoff;
BUG_ON(!kvm_is_mmio_pfn(pfn));
} else {
if (async && (vma->vm_flags & VM_WRITE))
*async = true;
pfn = get_fault_pfn();
}
up_read(¤t->mm->mmap_sem);
} else
pfn = page_to_pfn(page[0]);
return pfn;
}
pfn_t hva_to_pfn_atomic(struct kvm *kvm, unsigned long addr)
{
return hva_to_pfn(kvm, addr, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(hva_to_pfn_atomic);
static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
bool write_fault, bool *writable)
{
unsigned long addr;
if (async)
*async = false;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr)) {
get_page(bad_page);
return page_to_pfn(bad_page);
}
return hva_to_pfn(kvm, addr, atomic, async, write_fault, writable);
}
pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
bool write_fault, bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn);
pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
pfn_t gfn_to_pfn_memslot(struct kvm *kvm,
struct kvm_memory_slot *slot, gfn_t gfn)
{
unsigned long addr = gfn_to_hva_memslot(slot, gfn);
return hva_to_pfn(kvm, addr, false, NULL, true, NULL);
}
int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
int nr_pages)
{
unsigned long addr;
gfn_t entry;
addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
if (kvm_is_error_hva(addr))
return -1;
if (entry < nr_pages)
return 0;
return __get_user_pages_fast(addr, nr_pages, 1, pages);
}
EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
{
pfn_t pfn;
pfn = gfn_to_pfn(kvm, gfn);
if (!kvm_is_mmio_pfn(pfn))
return pfn_to_page(pfn);
WARN_ON(kvm_is_mmio_pfn(pfn));
get_page(bad_page);
return bad_page;
}
EXPORT_SYMBOL_GPL(gfn_to_page);
void kvm_release_page_clean(struct page *page)
{
kvm_release_pfn_clean(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_clean);
void kvm_release_pfn_clean(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
put_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
void kvm_release_page_dirty(struct page *page)
{
kvm_release_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
void kvm_release_pfn_dirty(pfn_t pfn)
{
kvm_set_pfn_dirty(pfn);
kvm_release_pfn_clean(pfn);
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
void kvm_set_page_dirty(struct page *page)
{
kvm_set_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
void kvm_set_pfn_dirty(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn)) {
struct page *page = pfn_to_page(pfn);
if (!PageReserved(page))
SetPageDirty(page);
}
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
void kvm_set_pfn_accessed(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
mark_page_accessed(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
void kvm_get_pfn(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
get_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_get_pfn);
static int next_segment(unsigned long len, int offset)
{
if (len > PAGE_SIZE - offset)
return PAGE_SIZE - offset;
else
return len;
}
int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = __copy_from_user(data, (void __user *)addr + offset, len);
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest_page);
int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest);
int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
unsigned long len)
{
int r;
unsigned long addr;
gfn_t gfn = gpa >> PAGE_SHIFT;
int offset = offset_in_page(gpa);
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
pagefault_disable();
r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
pagefault_enable();
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL(kvm_read_guest_atomic);
int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
int offset, int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = copy_to_user((void __user *)addr + offset, data, len);
if (r)
return -EFAULT;
mark_page_dirty(kvm, gfn);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_page);
int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
gpa_t gpa)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int offset = offset_in_page(gpa);
gfn_t gfn = gpa >> PAGE_SHIFT;
ghc->gpa = gpa;
ghc->generation = slots->generation;
ghc->memslot = __gfn_to_memslot(slots, gfn);
ghc->hva = gfn_to_hva_many(ghc->memslot, gfn, NULL);
if (!kvm_is_error_hva(ghc->hva))
ghc->hva += offset;
else
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
void *data, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int r;
if (slots->generation != ghc->generation)
kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
r = copy_to_user((void __user *)ghc->hva, data, len);
if (r)
return -EFAULT;
mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
{
return kvm_write_guest_page(kvm, gfn, (const void *) empty_zero_page,
offset, len);
}
EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_clear_guest);
void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
gfn_t gfn)
{
if (memslot && memslot->dirty_bitmap) {
unsigned long rel_gfn = gfn - memslot->base_gfn;
__set_bit_le(rel_gfn, memslot->dirty_bitmap);
}
}
void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *memslot;
memslot = gfn_to_memslot(kvm, gfn);
mark_page_dirty_in_slot(kvm, memslot, gfn);
}
/*
* The vCPU has executed a HLT instruction with in-kernel mode enabled.
*/
void kvm_vcpu_block(struct kvm_vcpu *vcpu)
{
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
if (kvm_arch_vcpu_runnable(vcpu)) {
kvm_make_request(KVM_REQ_UNHALT, vcpu);
break;
}
if (kvm_cpu_has_pending_timer(vcpu))
break;
if (signal_pending(current))
break;
schedule();
}
finish_wait(&vcpu->wq, &wait);
}
void kvm_resched(struct kvm_vcpu *vcpu)
{
if (!need_resched())
return;
cond_resched();
}
EXPORT_SYMBOL_GPL(kvm_resched);
void kvm_vcpu_on_spin(struct kvm_vcpu *me)
{
struct kvm *kvm = me->kvm;
struct kvm_vcpu *vcpu;
int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
int yielded = 0;
int pass;
int i;
/*
* We boost the priority of a VCPU that is runnable but not
* currently running, because it got preempted by something
* else and called schedule in __vcpu_run. Hopefully that
* VCPU is holding the lock that we need and will release it.
* We approximate round-robin by starting at the last boosted VCPU.
*/
for (pass = 0; pass < 2 && !yielded; pass++) {
kvm_for_each_vcpu(i, vcpu, kvm) {
struct task_struct *task = NULL;
struct pid *pid;
if (!pass && i < last_boosted_vcpu) {
i = last_boosted_vcpu;
continue;
} else if (pass && i > last_boosted_vcpu)
break;
if (vcpu == me)
continue;
if (waitqueue_active(&vcpu->wq))
continue;
rcu_read_lock();
pid = rcu_dereference(vcpu->pid);
if (pid)
task = get_pid_task(vcpu->pid, PIDTYPE_PID);
rcu_read_unlock();
if (!task)
continue;
if (task->flags & PF_VCPU) {
put_task_struct(task);
continue;
}
if (yield_to(task, 1)) {
put_task_struct(task);
kvm->last_boosted_vcpu = i;
yielded = 1;
break;
}
put_task_struct(task);
}
}
}
EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct kvm_vcpu *vcpu = vma->vm_file->private_data;
struct page *page;
if (vmf->pgoff == 0)
page = virt_to_page(vcpu->run);
#ifdef CONFIG_X86
else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
page = virt_to_page(vcpu->arch.pio_data);
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
#endif
else
return VM_FAULT_SIGBUS;
get_page(page);
vmf->page = page;
return 0;
}
static const struct vm_operations_struct kvm_vcpu_vm_ops = {
.fault = kvm_vcpu_fault,
};
static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
{
vma->vm_ops = &kvm_vcpu_vm_ops;
return 0;
}
static int kvm_vcpu_release(struct inode *inode, struct file *filp)
{
struct kvm_vcpu *vcpu = filp->private_data;
kvm_put_kvm(vcpu->kvm);
return 0;
}
static struct file_operations kvm_vcpu_fops = {
.release = kvm_vcpu_release,
.unlocked_ioctl = kvm_vcpu_ioctl,
.compat_ioctl = kvm_vcpu_ioctl,
.mmap = kvm_vcpu_mmap,
.llseek = noop_llseek,
};
/*
* Allocates an inode for the vcpu.
*/
static int create_vcpu_fd(struct kvm_vcpu *vcpu)
{
return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR);
}
/*
* Creates some virtual cpus. Good luck creating more than one.
*/
static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
return r;
mutex_lock(&kvm->lock);
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
if (kvm->bsp_vcpu_id == id)
kvm->bsp_vcpu = vcpu;
#endif
mutex_unlock(&kvm->lock);
return r;
vcpu_destroy:
mutex_unlock(&kvm->lock);
kvm_arch_vcpu_destroy(vcpu);
return r;
}
static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
{
if (sigset) {
sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
vcpu->sigset_active = 1;
vcpu->sigset = *sigset;
} else
vcpu->sigset_active = 0;
return 0;
}
static long kvm_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
struct kvm_fpu *fpu = NULL;
struct kvm_sregs *kvm_sregs = NULL;
if (vcpu->kvm->mm != current->mm)
return -EIO;
#if defined(CONFIG_S390) || defined(CONFIG_PPC)
/*
* Special cases: vcpu ioctls that are asynchronous to vcpu execution,
* so vcpu_load() would break it.
*/
if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
#endif
vcpu_load(vcpu);
switch (ioctl) {
case KVM_RUN:
r = -EINVAL;
if (arg)
goto out;
r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
break;
case KVM_GET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
if (!kvm_regs)
goto out;
r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
if (r)
goto out_free1;
r = -EFAULT;
if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
goto out_free1;
r = 0;
out_free1:
kfree(kvm_regs);
break;
}
case KVM_SET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
if (!kvm_regs)
goto out;
r = -EFAULT;
if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs)))
goto out_free2;
r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
if (r)
goto out_free2;
r = 0;
out_free2:
kfree(kvm_regs);
break;
}
case KVM_GET_SREGS: {
kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
r = -ENOMEM;
if (!kvm_sregs)
goto out;
r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
goto out;
r = 0;
break;
}
case KVM_SET_SREGS: {
kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
r = -ENOMEM;
if (!kvm_sregs)
goto out;
r = -EFAULT;
if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs)))
goto out;
r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
if (r)
goto out;
r = 0;
break;
}
case KVM_GET_MP_STATE: {
struct kvm_mp_state mp_state;
r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &mp_state, sizeof mp_state))
goto out;
r = 0;
break;
}
case KVM_SET_MP_STATE: {
struct kvm_mp_state mp_state;
r = -EFAULT;
if (copy_from_user(&mp_state, argp, sizeof mp_state))
goto out;
r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
if (r)
goto out;
r = 0;
break;
}
case KVM_TRANSLATE: {
struct kvm_translation tr;
r = -EFAULT;
if (copy_from_user(&tr, argp, sizeof tr))
goto out;
r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &tr, sizeof tr))
goto out;
r = 0;
break;
}
case KVM_SET_GUEST_DEBUG: {
struct kvm_guest_debug dbg;
r = -EFAULT;
if (copy_from_user(&dbg, argp, sizeof dbg))
goto out;
r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
if (r)
goto out;
r = 0;
break;
}
case KVM_SET_SIGNAL_MASK: {
struct kvm_signal_mask __user *sigmask_arg = argp;
struct kvm_signal_mask kvm_sigmask;
sigset_t sigset, *p;
p = NULL;
if (argp) {
r = -EFAULT;
if (copy_from_user(&kvm_sigmask, argp,
sizeof kvm_sigmask))
goto out;
r = -EINVAL;
if (kvm_sigmask.len != sizeof sigset)
goto out;
r = -EFAULT;
if (copy_from_user(&sigset, sigmask_arg->sigset,
sizeof sigset))
goto out;
p = &sigset;
}
r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
break;
}
case KVM_GET_FPU: {
fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
r = -ENOMEM;
if (!fpu)
goto out;
r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
goto out;
r = 0;
break;
}
case KVM_SET_FPU: {
fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
r = -ENOMEM;
if (!fpu)
goto out;
r = -EFAULT;
if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu)))
goto out;
r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
if (r)
goto out;
r = 0;
break;
}
default:
r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
}
out:
vcpu_put(vcpu);
kfree(fpu);
kfree(kvm_sregs);
return r;
}
static long kvm_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_CREATE_VCPU:
r = kvm_vm_ioctl_create_vcpu(kvm, arg);
if (r < 0)
goto out;
break;
case KVM_SET_USER_MEMORY_REGION: {
struct kvm_userspace_memory_region kvm_userspace_mem;
r = -EFAULT;
if (copy_from_user(&kvm_userspace_mem, argp,
sizeof kvm_userspace_mem))
goto out;
r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 1);
if (r)
goto out;
break;
}
case KVM_GET_DIRTY_LOG: {
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&log, argp, sizeof log))
goto out;
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
if (r)
goto out;
break;
}
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
case KVM_REGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
if (r)
goto out;
r = 0;
break;
}
case KVM_UNREGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
if (r)
goto out;
r = 0;
break;
}
#endif
case KVM_IRQFD: {
struct kvm_irqfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_irqfd(kvm, data.fd, data.gsi, data.flags);
break;
}
case KVM_IOEVENTFD: {
struct kvm_ioeventfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_ioeventfd(kvm, &data);
break;
}
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_SET_BOOT_CPU_ID:
r = 0;
mutex_lock(&kvm->lock);
if (atomic_read(&kvm->online_vcpus) != 0)
r = -EBUSY;
else
kvm->bsp_vcpu_id = arg;
mutex_unlock(&kvm->lock);
break;
#endif
default:
r = kvm_arch_vm_ioctl(filp, ioctl, arg);
if (r == -ENOTTY)
r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
}
out:
return r;
}
#ifdef CONFIG_COMPAT
struct compat_kvm_dirty_log {
__u32 slot;
__u32 padding1;
union {
compat_uptr_t dirty_bitmap; /* one bit per page */
__u64 padding2;
};
};
static long kvm_vm_compat_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_GET_DIRTY_LOG: {
struct compat_kvm_dirty_log compat_log;
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&compat_log, (void __user *)arg,
sizeof(compat_log)))
goto out;
log.slot = compat_log.slot;
log.padding1 = compat_log.padding1;
log.padding2 = compat_log.padding2;
log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
if (r)
goto out;
break;
}
default:
r = kvm_vm_ioctl(filp, ioctl, arg);
}
out:
return r;
}
#endif
static int kvm_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page[1];
unsigned long addr;
int npages;
gfn_t gfn = vmf->pgoff;
struct kvm *kvm = vma->vm_file->private_data;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return VM_FAULT_SIGBUS;
npages = get_user_pages(current, current->mm, addr, 1, 1, 0, page,
NULL);
if (unlikely(npages != 1))
return VM_FAULT_SIGBUS;
vmf->page = page[0];
return 0;
}
static const struct vm_operations_struct kvm_vm_vm_ops = {
.fault = kvm_vm_fault,
};
static int kvm_vm_mmap(struct file *file, struct vm_area_struct *vma)
{
vma->vm_ops = &kvm_vm_vm_ops;
return 0;
}
static struct file_operations kvm_vm_fops = {
.release = kvm_vm_release,
.unlocked_ioctl = kvm_vm_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_vm_compat_ioctl,
#endif
.mmap = kvm_vm_mmap,
.llseek = noop_llseek,
};
static int kvm_dev_ioctl_create_vm(void)
{
int r;
struct kvm *kvm;
kvm = kvm_create_vm();
if (IS_ERR(kvm))
return PTR_ERR(kvm);
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r = kvm_coalesced_mmio_init(kvm);
if (r < 0) {
kvm_put_kvm(kvm);
return r;
}
#endif
r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
if (r < 0)
kvm_put_kvm(kvm);
return r;
}
static long kvm_dev_ioctl_check_extension_generic(long arg)
{
switch (arg) {
case KVM_CAP_USER_MEMORY:
case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_CAP_SET_BOOT_CPU_ID:
#endif
case KVM_CAP_INTERNAL_ERROR_DATA:
return 1;
#ifdef CONFIG_HAVE_KVM_IRQCHIP
case KVM_CAP_IRQ_ROUTING:
return KVM_MAX_IRQ_ROUTES;
#endif
default:
break;
}
return kvm_dev_ioctl_check_extension(arg);
}
static long kvm_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
long r = -EINVAL;
switch (ioctl) {
case KVM_GET_API_VERSION:
r = -EINVAL;
if (arg)
goto out;
r = KVM_API_VERSION;
break;
case KVM_CREATE_VM:
r = -EINVAL;
if (arg)
goto out;
r = kvm_dev_ioctl_create_vm();
break;
case KVM_CHECK_EXTENSION:
r = kvm_dev_ioctl_check_extension_generic(arg);
break;
case KVM_GET_VCPU_MMAP_SIZE:
r = -EINVAL;
if (arg)
goto out;
r = PAGE_SIZE; /* struct kvm_run */
#ifdef CONFIG_X86
r += PAGE_SIZE; /* pio data page */
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r += PAGE_SIZE; /* coalesced mmio ring page */
#endif
break;
case KVM_TRACE_ENABLE:
case KVM_TRACE_PAUSE:
case KVM_TRACE_DISABLE:
r = -EOPNOTSUPP;
break;
default:
return kvm_arch_dev_ioctl(filp, ioctl, arg);
}
out:
return r;
}
static struct file_operations kvm_chardev_ops = {
.unlocked_ioctl = kvm_dev_ioctl,
.compat_ioctl = kvm_dev_ioctl,
.llseek = noop_llseek,
};
static struct miscdevice kvm_dev = {
KVM_MINOR,
"kvm",
&kvm_chardev_ops,
};
static void hardware_enable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
int r;
if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_set_cpu(cpu, cpus_hardware_enabled);
r = kvm_arch_hardware_enable(NULL);
if (r) {
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
atomic_inc(&hardware_enable_failed);
printk(KERN_INFO "kvm: enabling virtualization on "
"CPU%d failed\n", cpu);
}
}
static void hardware_enable(void *junk)
{
raw_spin_lock(&kvm_lock);
hardware_enable_nolock(junk);
raw_spin_unlock(&kvm_lock);
}
static void hardware_disable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
kvm_arch_hardware_disable(NULL);
}
static void hardware_disable(void *junk)
{
raw_spin_lock(&kvm_lock);
hardware_disable_nolock(junk);
raw_spin_unlock(&kvm_lock);
}
static void hardware_disable_all_nolock(void)
{
BUG_ON(!kvm_usage_count);
kvm_usage_count--;
if (!kvm_usage_count)
on_each_cpu(hardware_disable_nolock, NULL, 1);
}
static void hardware_disable_all(void)
{
raw_spin_lock(&kvm_lock);
hardware_disable_all_nolock();
raw_spin_unlock(&kvm_lock);
}
static int hardware_enable_all(void)
{
int r = 0;
raw_spin_lock(&kvm_lock);
kvm_usage_count++;
if (kvm_usage_count == 1) {
atomic_set(&hardware_enable_failed, 0);
on_each_cpu(hardware_enable_nolock, NULL, 1);
if (atomic_read(&hardware_enable_failed)) {
hardware_disable_all_nolock();
r = -EBUSY;
}
}
raw_spin_unlock(&kvm_lock);
return r;
}
static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
void *v)
{
int cpu = (long)v;
if (!kvm_usage_count)
return NOTIFY_OK;
val &= ~CPU_TASKS_FROZEN;
switch (val) {
case CPU_DYING:
printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
cpu);
hardware_disable(NULL);
break;
case CPU_STARTING:
printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
cpu);
hardware_enable(NULL);
break;
}
return NOTIFY_OK;
}
asmlinkage void kvm_spurious_fault(void)
{
/* Fault while not rebooting. We want the trace. */
BUG();
}
EXPORT_SYMBOL_GPL(kvm_spurious_fault);
static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
void *v)
{
/*
* Some (well, at least mine) BIOSes hang on reboot if
* in vmx root mode.
*
* And Intel TXT required VMX off for all cpu when system shutdown.
*/
printk(KERN_INFO "kvm: exiting hardware virtualization\n");
kvm_rebooting = true;
on_each_cpu(hardware_disable_nolock, NULL, 1);
return NOTIFY_OK;
}
static struct notifier_block kvm_reboot_notifier = {
.notifier_call = kvm_reboot,
.priority = 0,
};
static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
{
int i;
for (i = 0; i < bus->dev_count; i++) {
struct kvm_io_device *pos = bus->devs[i];
kvm_iodevice_destructor(pos);
}
kfree(bus);
}
/* kvm_io_bus_write - called under kvm->slots_lock */
int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, const void *val)
{
int i;
struct kvm_io_bus *bus;
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
for (i = 0; i < bus->dev_count; i++)
if (!kvm_iodevice_write(bus->devs[i], addr, len, val))
return 0;
return -EOPNOTSUPP;
}
/* kvm_io_bus_read - called under kvm->slots_lock */
int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, void *val)
{
int i;
struct kvm_io_bus *bus;
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
for (i = 0; i < bus->dev_count; i++)
if (!kvm_iodevice_read(bus->devs[i], addr, len, val))
return 0;
return -EOPNOTSUPP;
}
/* Caller must hold slots_lock. */
int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx,
struct kvm_io_device *dev)
{
struct kvm_io_bus *new_bus, *bus;
bus = kvm->buses[bus_idx];
if (bus->dev_count > NR_IOBUS_DEVS-1)
return -ENOSPC;
new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
new_bus->devs[new_bus->dev_count++] = dev;
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return 0;
}
/* Caller must hold slots_lock. */
int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
struct kvm_io_device *dev)
{
int i, r;
struct kvm_io_bus *new_bus, *bus;
new_bus = kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
bus = kvm->buses[bus_idx];
memcpy(new_bus, bus, sizeof(struct kvm_io_bus));
r = -ENOENT;
for (i = 0; i < new_bus->dev_count; i++)
if (new_bus->devs[i] == dev) {
r = 0;
new_bus->devs[i] = new_bus->devs[--new_bus->dev_count];
break;
}
if (r) {
kfree(new_bus);
return r;
}
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return r;
}
static struct notifier_block kvm_cpu_notifier = {
.notifier_call = kvm_cpu_hotplug,
};
static int vm_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
*val = 0;
raw_spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
*val += *(u32 *)((void *)kvm + offset);
raw_spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
static int vcpu_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
*val = 0;
raw_spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
kvm_for_each_vcpu(i, vcpu, kvm)
*val += *(u32 *)((void *)vcpu + offset);
raw_spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
static const struct file_operations *stat_fops[] = {
[KVM_STAT_VCPU] = &vcpu_stat_fops,
[KVM_STAT_VM] = &vm_stat_fops,
};
static void kvm_init_debug(void)
{
struct kvm_stats_debugfs_item *p;
kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
for (p = debugfs_entries; p->name; ++p)
p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
(void *)(long)p->offset,
stat_fops[p->kind]);
}
static void kvm_exit_debug(void)
{
struct kvm_stats_debugfs_item *p;
for (p = debugfs_entries; p->name; ++p)
debugfs_remove(p->dentry);
debugfs_remove(kvm_debugfs_dir);
}
static int kvm_suspend(void)
{
if (kvm_usage_count)
hardware_disable_nolock(NULL);
return 0;
}
static void kvm_resume(void)
{
if (kvm_usage_count) {
WARN_ON(raw_spin_is_locked(&kvm_lock));
hardware_enable_nolock(NULL);
}
}
static struct syscore_ops kvm_syscore_ops = {
.suspend = kvm_suspend,
.resume = kvm_resume,
};
struct page *bad_page;
pfn_t bad_pfn;
static inline
struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
{
return container_of(pn, struct kvm_vcpu, preempt_notifier);
}
static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
kvm_arch_vcpu_load(vcpu, cpu);
}
static void kvm_sched_out(struct preempt_notifier *pn,
struct task_struct *next)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
kvm_arch_vcpu_put(vcpu);
}
int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
struct module *module)
{
int r;
int cpu;
r = kvm_arch_init(opaque);
if (r)
goto out_fail;
bad_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (bad_page == NULL) {
r = -ENOMEM;
goto out;
}
bad_pfn = page_to_pfn(bad_page);
hwpoison_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (hwpoison_page == NULL) {
r = -ENOMEM;
goto out_free_0;
}
hwpoison_pfn = page_to_pfn(hwpoison_page);
fault_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (fault_page == NULL) {
r = -ENOMEM;
goto out_free_0;
}
fault_pfn = page_to_pfn(fault_page);
if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
r = -ENOMEM;
goto out_free_0;
}
r = kvm_arch_hardware_setup();
if (r < 0)
goto out_free_0a;
for_each_online_cpu(cpu) {
smp_call_function_single(cpu,
kvm_arch_check_processor_compat,
&r, 1);
if (r < 0)
goto out_free_1;
}
r = register_cpu_notifier(&kvm_cpu_notifier);
if (r)
goto out_free_2;
register_reboot_notifier(&kvm_reboot_notifier);
/* A kmem cache lets us meet the alignment requirements of fx_save. */
if (!vcpu_align)
vcpu_align = __alignof__(struct kvm_vcpu);
kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
0, NULL);
if (!kvm_vcpu_cache) {
r = -ENOMEM;
goto out_free_3;
}
r = kvm_async_pf_init();
if (r)
goto out_free;
kvm_chardev_ops.owner = module;
kvm_vm_fops.owner = module;
kvm_vcpu_fops.owner = module;
r = misc_register(&kvm_dev);
if (r) {
printk(KERN_ERR "kvm: misc device register failed\n");
goto out_unreg;
}
register_syscore_ops(&kvm_syscore_ops);
kvm_preempt_ops.sched_in = kvm_sched_in;
kvm_preempt_ops.sched_out = kvm_sched_out;
kvm_init_debug();
return 0;
out_unreg:
kvm_async_pf_deinit();
out_free:
kmem_cache_destroy(kvm_vcpu_cache);
out_free_3:
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
out_free_2:
out_free_1:
kvm_arch_hardware_unsetup();
out_free_0a:
free_cpumask_var(cpus_hardware_enabled);
out_free_0:
if (fault_page)
__free_page(fault_page);
if (hwpoison_page)
__free_page(hwpoison_page);
__free_page(bad_page);
out:
kvm_arch_exit();
out_fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_init);
void kvm_exit(void)
{
kvm_exit_debug();
misc_deregister(&kvm_dev);
kmem_cache_destroy(kvm_vcpu_cache);
kvm_async_pf_deinit();
unregister_syscore_ops(&kvm_syscore_ops);
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
on_each_cpu(hardware_disable_nolock, NULL, 1);
kvm_arch_hardware_unsetup();
kvm_arch_exit();
free_cpumask_var(cpus_hardware_enabled);
__free_page(hwpoison_page);
__free_page(bad_page);
}
EXPORT_SYMBOL_GPL(kvm_exit);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5613_1 |
crossvul-cpp_data_bad_874_0 | /* bubblewrap
* Copyright (C) 2016 Alexander Larsson
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <poll.h>
#include <sched.h>
#include <pwd.h>
#include <grp.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/eventfd.h>
#include <sys/fsuid.h>
#include <sys/signalfd.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/filter.h>
#include "utils.h"
#include "network.h"
#include "bind-mount.h"
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */
#endif
/* Globals to avoid having to use getuid(), since the uid/gid changes during runtime */
static uid_t real_uid;
static gid_t real_gid;
static uid_t overflow_uid;
static gid_t overflow_gid;
static bool is_privileged; /* See acquire_privs() */
static const char *argv0;
static const char *host_tty_dev;
static int proc_fd = -1;
static const char *opt_exec_label = NULL;
static const char *opt_file_label = NULL;
static bool opt_as_pid_1;
const char *opt_chdir_path = NULL;
bool opt_unshare_user = FALSE;
bool opt_unshare_user_try = FALSE;
bool opt_unshare_pid = FALSE;
bool opt_unshare_ipc = FALSE;
bool opt_unshare_net = FALSE;
bool opt_unshare_uts = FALSE;
bool opt_unshare_cgroup = FALSE;
bool opt_unshare_cgroup_try = FALSE;
bool opt_needs_devpts = FALSE;
bool opt_new_session = FALSE;
bool opt_die_with_parent = FALSE;
uid_t opt_sandbox_uid = -1;
gid_t opt_sandbox_gid = -1;
int opt_sync_fd = -1;
int opt_block_fd = -1;
int opt_userns_block_fd = -1;
int opt_info_fd = -1;
int opt_json_status_fd = -1;
int opt_seccomp_fd = -1;
const char *opt_sandbox_hostname = NULL;
char *opt_args_data = NULL; /* owned */
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
typedef enum {
SETUP_BIND_MOUNT,
SETUP_RO_BIND_MOUNT,
SETUP_DEV_BIND_MOUNT,
SETUP_MOUNT_PROC,
SETUP_MOUNT_DEV,
SETUP_MOUNT_TMPFS,
SETUP_MOUNT_MQUEUE,
SETUP_MAKE_DIR,
SETUP_MAKE_FILE,
SETUP_MAKE_BIND_FILE,
SETUP_MAKE_RO_BIND_FILE,
SETUP_MAKE_SYMLINK,
SETUP_REMOUNT_RO_NO_RECURSIVE,
SETUP_SET_HOSTNAME,
} SetupOpType;
typedef enum {
NO_CREATE_DEST = (1 << 0),
ALLOW_NOTEXIST = (2 << 0),
} SetupOpFlag;
typedef struct _SetupOp SetupOp;
struct _SetupOp
{
SetupOpType type;
const char *source;
const char *dest;
int fd;
SetupOpFlag flags;
SetupOp *next;
};
typedef struct _LockFile LockFile;
struct _LockFile
{
const char *path;
int fd;
LockFile *next;
};
static SetupOp *ops = NULL;
static SetupOp *last_op = NULL;
static LockFile *lock_files = NULL;
static LockFile *last_lock_file = NULL;
enum {
PRIV_SEP_OP_DONE,
PRIV_SEP_OP_BIND_MOUNT,
PRIV_SEP_OP_PROC_MOUNT,
PRIV_SEP_OP_TMPFS_MOUNT,
PRIV_SEP_OP_DEVPTS_MOUNT,
PRIV_SEP_OP_MQUEUE_MOUNT,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE,
PRIV_SEP_OP_SET_HOSTNAME,
};
typedef struct
{
uint32_t op;
uint32_t flags;
uint32_t arg1_offset;
uint32_t arg2_offset;
} PrivSepOp;
static SetupOp *
setup_op_new (SetupOpType type)
{
SetupOp *op = xcalloc (sizeof (SetupOp));
op->type = type;
op->fd = -1;
op->flags = 0;
if (last_op != NULL)
last_op->next = op;
else
ops = op;
last_op = op;
return op;
}
static LockFile *
lock_file_new (const char *path)
{
LockFile *lock = xcalloc (sizeof (LockFile));
lock->path = path;
if (last_lock_file != NULL)
last_lock_file->next = lock;
else
lock_files = lock;
last_lock_file = lock;
return lock;
}
static void
usage (int ecode, FILE *out)
{
fprintf (out, "usage: %s [OPTIONS...] [--] COMMAND [ARGS...]\n\n", argv0);
fprintf (out,
" --help Print this help\n"
" --version Print version\n"
" --args FD Parse NUL-separated args from FD\n"
" --unshare-all Unshare every namespace we support by default\n"
" --share-net Retain the network namespace (can only combine with --unshare-all)\n"
" --unshare-user Create new user namespace (may be automatically implied if not setuid)\n"
" --unshare-user-try Create new user namespace if possible else continue by skipping it\n"
" --unshare-ipc Create new ipc namespace\n"
" --unshare-pid Create new pid namespace\n"
" --unshare-net Create new network namespace\n"
" --unshare-uts Create new uts namespace\n"
" --unshare-cgroup Create new cgroup namespace\n"
" --unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it\n"
" --uid UID Custom uid in the sandbox (requires --unshare-user)\n"
" --gid GID Custom gid in the sandbox (requires --unshare-user)\n"
" --hostname NAME Custom hostname in the sandbox (requires --unshare-uts)\n"
" --chdir DIR Change directory to DIR\n"
" --setenv VAR VALUE Set an environment variable\n"
" --unsetenv VAR Unset an environment variable\n"
" --lock-file DEST Take a lock on DEST while sandbox is running\n"
" --sync-fd FD Keep this fd open while sandbox is running\n"
" --bind SRC DEST Bind mount the host path SRC on DEST\n"
" --bind-try SRC DEST Equal to --bind but ignores non-existent SRC\n"
" --dev-bind SRC DEST Bind mount the host path SRC on DEST, allowing device access\n"
" --dev-bind-try SRC DEST Equal to --dev-bind but ignores non-existent SRC\n"
" --ro-bind SRC DEST Bind mount the host path SRC readonly on DEST\n"
" --ro-bind-try SRC DEST Equal to --ro-bind but ignores non-existent SRC\n"
" --remount-ro DEST Remount DEST as readonly; does not recursively remount\n"
" --exec-label LABEL Exec label for the sandbox\n"
" --file-label LABEL File label for temporary sandbox content\n"
" --proc DEST Mount new procfs on DEST\n"
" --dev DEST Mount new dev on DEST\n"
" --tmpfs DEST Mount new tmpfs on DEST\n"
" --mqueue DEST Mount new mqueue on DEST\n"
" --dir DEST Create dir at DEST\n"
" --file FD DEST Copy from FD to destination DEST\n"
" --bind-data FD DEST Copy from FD to file which is bind-mounted on DEST\n"
" --ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST\n"
" --symlink SRC DEST Create symlink at DEST with target SRC\n"
" --seccomp FD Load and use seccomp rules from FD\n"
" --block-fd FD Block on FD until some data to read is available\n"
" --userns-block-fd FD Block on FD until the user namespace is ready\n"
" --info-fd FD Write information about the running container to FD\n"
" --json-status-fd FD Write container status to FD as multiple JSON documents\n"
" --new-session Create a new terminal session\n"
" --die-with-parent Kills with SIGKILL child process (COMMAND) when bwrap or bwrap's parent dies.\n"
" --as-pid-1 Do not install a reaper process with PID=1\n"
" --cap-add CAP Add cap CAP when running as privileged user\n"
" --cap-drop CAP Drop cap CAP when running as privileged user\n"
);
exit (ecode);
}
/* If --die-with-parent was specified, use PDEATHSIG to ensure SIGKILL
* is sent to the current process when our parent dies.
*/
static void
handle_die_with_parent (void)
{
if (opt_die_with_parent && prctl (PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) != 0)
die_with_error ("prctl");
}
static void
block_sigchild (void)
{
sigset_t mask;
int status;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_BLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
/* Reap any outstanding zombies that we may have inherited */
while (waitpid (-1, &status, WNOHANG) > 0)
;
}
static void
unblock_sigchild (void)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_UNBLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
}
/* Closes all fd:s except 0,1,2 and the passed in array of extra fds */
static int
close_extra_fds (void *data, int fd)
{
int *extra_fds = (int *) data;
int i;
for (i = 0; extra_fds[i] != -1; i++)
if (fd == extra_fds[i])
return 0;
if (fd <= 2)
return 0;
close (fd);
return 0;
}
static int
propagate_exit_status (int status)
{
if (WIFEXITED (status))
return WEXITSTATUS (status);
/* The process died of a signal, we can't really report that, but we
* can at least be bash-compatible. The bash manpage says:
* The return value of a simple command is its
* exit status, or 128+n if the command is
* terminated by signal n.
*/
if (WIFSIGNALED (status))
return 128 + WTERMSIG (status);
/* Weird? */
return 255;
}
static void
dump_info (int fd, const char *output, bool exit_on_error)
{
size_t len = strlen (output);
if (write_to_fd (fd, output, len))
{
if (exit_on_error)
die_with_error ("Write to info_fd");
}
}
static void
report_child_exit_status (int exitc, int setup_finished_fd)
{
ssize_t s;
char data[2];
cleanup_free char *output = NULL;
if (opt_json_status_fd == -1 || setup_finished_fd == -1)
return;
s = TEMP_FAILURE_RETRY (read (setup_finished_fd, data, sizeof data));
if (s == -1 && errno != EAGAIN)
die_with_error ("read eventfd");
if (s != 1) // Is 0 if pipe closed before exec, is 2 if closed after exec.
return;
output = xasprintf ("{ \"exit-code\": %i }\n", exitc);
dump_info (opt_json_status_fd, output, FALSE);
close (opt_json_status_fd);
opt_json_status_fd = -1;
close (setup_finished_fd);
}
/* This stays around for as long as the initial process in the app does
* and when that exits it exits, propagating the exit status. We do this
* by having pid 1 in the sandbox detect this exit and tell the monitor
* the exit status via a eventfd. We also track the exit of the sandbox
* pid 1 via a signalfd for SIGCHLD, and exit with an error in this case.
* This is to catch e.g. problems during setup. */
static int
monitor_child (int event_fd, pid_t child_pid, int setup_finished_fd)
{
int res;
uint64_t val;
ssize_t s;
int signal_fd;
sigset_t mask;
struct pollfd fds[2];
int num_fds;
struct signalfd_siginfo fdsi;
int dont_close[] = {-1, -1, -1, -1};
int j = 0;
int exitc;
pid_t died_pid;
int died_status;
/* Close all extra fds in the monitoring process.
Any passed in fds have been passed on to the child anyway. */
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_json_status_fd != -1)
dont_close[j++] = opt_json_status_fd;
if (setup_finished_fd != -1)
dont_close[j++] = setup_finished_fd;
assert (j < sizeof(dont_close)/sizeof(*dont_close));
fdwalk (proc_fd, close_extra_fds, dont_close);
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
signal_fd = signalfd (-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
if (signal_fd == -1)
die_with_error ("Can't create signalfd");
num_fds = 1;
fds[0].fd = signal_fd;
fds[0].events = POLLIN;
if (event_fd != -1)
{
fds[1].fd = event_fd;
fds[1].events = POLLIN;
num_fds++;
}
while (1)
{
fds[0].revents = fds[1].revents = 0;
res = poll (fds, num_fds, -1);
if (res == -1 && errno != EINTR)
die_with_error ("poll");
/* Always read from the eventfd first, if pid 2 died then pid 1 often
* dies too, and we could race, reporting that first and we'd lose
* the real exit status. */
if (event_fd != -1)
{
s = read (event_fd, &val, 8);
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read eventfd");
else if (s == 8)
{
exitc = (int) val - 1;
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
/* We need to read the signal_fd, or it will keep polling as read,
* however we ignore the details as we get them from waitpid
* below anyway */
s = read (signal_fd, &fdsi, sizeof (struct signalfd_siginfo));
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read signalfd");
/* We may actually get several sigchld compressed into one
SIGCHLD, so we have to handle all of them. */
while ((died_pid = waitpid (-1, &died_status, WNOHANG)) > 0)
{
/* We may be getting sigchild from other children too. For instance if
someone created a child process, and then exec:ed bubblewrap. Ignore them */
if (died_pid == child_pid)
{
exitc = propagate_exit_status (died_status);
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
}
die ("Should not be reached");
return 0;
}
/* This is pid 1 in the app sandbox. It is needed because we're using
* pid namespaces, and someone has to reap zombies in it. We also detect
* when the initial process (pid 2) dies and report its exit status to
* the monitor so that it can return it to the original spawner.
*
* When there are no other processes in the sandbox the wait will return
* ECHILD, and we then exit pid 1 to clean up the sandbox. */
static int
do_init (int event_fd, pid_t initial_pid, struct sock_fprog *seccomp_prog)
{
int initial_exit_status = 1;
LockFile *lock;
for (lock = lock_files; lock != NULL; lock = lock->next)
{
int fd = open (lock->path, O_RDONLY | O_CLOEXEC);
if (fd == -1)
die_with_error ("Unable to open lock file %s", lock->path);
struct flock l = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
if (fcntl (fd, F_SETLK, &l) < 0)
die_with_error ("Unable to lock file %s", lock->path);
/* Keep fd open to hang on to lock */
lock->fd = fd;
}
/* Optionally bind our lifecycle to that of the caller */
handle_die_with_parent ();
if (seccomp_prog != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
while (TRUE)
{
pid_t child;
int status;
child = wait (&status);
if (child == initial_pid && event_fd != -1)
{
uint64_t val;
int res UNUSED;
initial_exit_status = propagate_exit_status (status);
val = initial_exit_status + 1;
res = write (event_fd, &val, 8);
/* Ignore res, if e.g. the parent died and closed event_fd
we don't want to error out here */
}
if (child == -1 && errno != EINTR)
{
if (errno != ECHILD)
die_with_error ("init wait()");
break;
}
}
/* Close FDs. */
for (lock = lock_files; lock != NULL; lock = lock->next)
{
if (lock->fd >= 0)
{
close (lock->fd);
lock->fd = -1;
}
}
return initial_exit_status;
}
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
/* Set if --cap-add or --cap-drop were used */
static bool opt_cap_add_or_drop_used;
/* The capability set we'll target, used if above is true */
static uint32_t requested_caps[2] = {0, 0};
/* low 32bit caps needed */
#define REQUIRED_CAPS_0 (CAP_TO_MASK_0 (CAP_SYS_ADMIN) | CAP_TO_MASK_0 (CAP_SYS_CHROOT) | CAP_TO_MASK_0 (CAP_NET_ADMIN) | CAP_TO_MASK_0 (CAP_SETUID) | CAP_TO_MASK_0 (CAP_SETGID))
/* high 32bit caps needed */
#define REQUIRED_CAPS_1 0
static void
set_required_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
/* Drop all non-require capabilities */
data[0].effective = REQUIRED_CAPS_0;
data[0].permitted = REQUIRED_CAPS_0;
data[0].inheritable = 0;
data[1].effective = REQUIRED_CAPS_1;
data[1].permitted = REQUIRED_CAPS_1;
data[1].inheritable = 0;
if (capset (&hdr, data) < 0)
die_with_error ("capset failed");
}
static void
drop_all_caps (bool keep_requested_caps)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (keep_requested_caps)
{
/* Avoid calling capset() unless we need to; currently
* systemd-nspawn at least is known to install a seccomp
* policy denying capset() for dubious reasons.
* <https://github.com/projectatomic/bubblewrap/pull/122>
*/
if (!opt_cap_add_or_drop_used && real_uid == 0)
{
assert (!is_privileged);
return;
}
data[0].effective = requested_caps[0];
data[0].permitted = requested_caps[0];
data[0].inheritable = requested_caps[0];
data[1].effective = requested_caps[1];
data[1].permitted = requested_caps[1];
data[1].inheritable = requested_caps[1];
}
if (capset (&hdr, data) < 0)
{
/* While the above logic ensures we don't call capset() for the primary
* process unless configured to do so, we still try to drop privileges for
* the init process unconditionally. Since due to the systemd seccomp
* filter that will fail, let's just ignore it.
*/
if (errno == EPERM && real_uid == 0 && !is_privileged)
return;
else
die_with_error ("capset failed");
}
}
static bool
has_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget failed");
return data[0].permitted != 0 || data[1].permitted != 0;
}
/* Most of the code here is used both to add caps to the ambient capabilities
* and drop caps from the bounding set. Handle both cases here and add
* drop_cap_bounding_set/set_ambient_capabilities wrappers to facilitate its usage.
*/
static void
prctl_caps (uint32_t *caps, bool do_cap_bounding, bool do_set_ambient)
{
unsigned long cap;
/* We ignore both EINVAL and EPERM, as we are actually relying
* on PR_SET_NO_NEW_PRIVS to ensure the right capabilities are
* available. EPERM in particular can happen with old, buggy
* kernels. See:
* https://github.com/projectatomic/bubblewrap/pull/175#issuecomment-278051373
* https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/security/commoncap.c?id=160da84dbb39443fdade7151bc63a88f8e953077
*/
for (cap = 0; cap <= CAP_LAST_CAP; cap++)
{
bool keep = FALSE;
if (cap < 32)
{
if (CAP_TO_MASK_0 (cap) & caps[0])
keep = TRUE;
}
else
{
if (CAP_TO_MASK_1 (cap) & caps[1])
keep = TRUE;
}
if (keep && do_set_ambient)
{
#ifdef PR_CAP_AMBIENT
int res = prctl (PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Adding ambient capability %ld", cap);
#else
/* We ignore the EINVAL that results from not having PR_CAP_AMBIENT
* in the current kernel at runtime, so also ignore not having it
* in the current kernel headers at compile-time */
#endif
}
if (!keep && do_cap_bounding)
{
int res = prctl (PR_CAPBSET_DROP, cap, 0, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Dropping capability %ld from bounds", cap);
}
}
}
static void
drop_cap_bounding_set (bool drop_all)
{
if (!drop_all)
prctl_caps (requested_caps, TRUE, FALSE);
else
{
uint32_t no_caps[2] = {0, 0};
prctl_caps (no_caps, TRUE, FALSE);
}
}
static void
set_ambient_capabilities (void)
{
if (is_privileged)
return;
prctl_caps (requested_caps, FALSE, TRUE);
}
/* This acquires the privileges that the bwrap will need it to work.
* If bwrap is not setuid, then this does nothing, and it relies on
* unprivileged user namespaces to be used. This case is
* "is_privileged = FALSE".
*
* If bwrap is setuid, then we do things in phases.
* The first part is run as euid 0, but with fsuid as the real user.
* The second part, inside the child, is run as the real user but with
* capabilities.
* And finally we drop all capabilities.
* The reason for the above dance is to avoid having the setup phase
* being able to read files the user can't, while at the same time
* working around various kernel issues. See below for details.
*/
static void
acquire_privs (void)
{
uid_t euid, new_fsuid;
euid = geteuid ();
/* Are we setuid ? */
if (real_uid != euid)
{
if (euid != 0)
die ("Unexpected setuid user %d, should be 0", euid);
is_privileged = TRUE;
/* We want to keep running as euid=0 until at the clone()
* operation because doing so will make the user namespace be
* owned by root, which makes it not ptrace:able by the user as
* it otherwise would be. After that we will run fully as the
* user, which is necessary e.g. to be able to read from a fuse
* mount from the user.
*
* However, we don't want to accidentally mis-use euid=0 for
* escalated filesystem access before the clone(), so we set
* fsuid to the uid.
*/
if (setfsuid (real_uid) < 0)
die_with_error ("Unable to set fsuid");
/* setfsuid can't properly report errors, check that it worked (as per manpage) */
new_fsuid = setfsuid (-1);
if (new_fsuid != real_uid)
die ("Unable to set fsuid (was %d)", (int)new_fsuid);
/* We never need capabilities after execve(), so lets drop everything from the bounding set */
drop_cap_bounding_set (TRUE);
/* Keep only the required capabilities for setup */
set_required_caps ();
}
else if (real_uid != 0 && has_caps ())
{
/* We have some capabilities in the non-setuid case, which should not happen.
Probably caused by the binary being setcap instead of setuid which we
don't support anymore */
die ("Unexpected capabilities but not setuid, old file caps config?");
}
else if (real_uid == 0)
{
/* If our uid is 0, default to inheriting all caps; the caller
* can drop them via --cap-drop. This is used by at least rpm-ostree.
* Note this needs to happen before the argument parsing of --cap-drop.
*/
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget (for uid == 0) failed");
requested_caps[0] = data[0].effective;
requested_caps[1] = data[1].effective;
}
/* Else, we try unprivileged user namespaces */
}
/* This is called once we're inside the namespace */
static void
switch_to_user_with_privs (void)
{
/* If we're in a new user namespace, we got back the bounding set, clear it again */
if (opt_unshare_user)
drop_cap_bounding_set (FALSE);
if (!is_privileged)
return;
/* Tell kernel not clear capabilities when later dropping root uid */
if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_KEEPCAPS) failed");
if (setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
/* Regain effective required capabilities from permitted */
set_required_caps ();
}
/* Call setuid() and use capset() to adjust capabilities */
static void
drop_privs (bool keep_requested_caps)
{
assert (!keep_requested_caps || !is_privileged);
/* Drop root uid */
if (getuid () == 0 && setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
drop_all_caps (keep_requested_caps);
}
static char *
get_newroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/newroot/", path);
}
static char *
get_oldroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/oldroot/", path);
}
static void
write_uid_gid_map (uid_t sandbox_uid,
uid_t parent_uid,
uid_t sandbox_gid,
uid_t parent_gid,
pid_t pid,
bool deny_groups,
bool map_root)
{
cleanup_free char *uid_map = NULL;
cleanup_free char *gid_map = NULL;
cleanup_free char *dir = NULL;
cleanup_fd int dir_fd = -1;
uid_t old_fsuid = -1;
if (pid == -1)
dir = xstrdup ("self");
else
dir = xasprintf ("%d", pid);
dir_fd = openat (proc_fd, dir, O_PATH);
if (dir_fd < 0)
die_with_error ("open /proc/%s failed", dir);
if (map_root && parent_uid != 0 && sandbox_uid != 0)
uid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_uid, sandbox_uid, parent_uid);
else
uid_map = xasprintf ("%d %d 1\n", sandbox_uid, parent_uid);
if (map_root && parent_gid != 0 && sandbox_gid != 0)
gid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_gid, sandbox_gid, parent_gid);
else
gid_map = xasprintf ("%d %d 1\n", sandbox_gid, parent_gid);
/* We have to be root to be allowed to write to the uid map
* for setuid apps, so temporary set fsuid to 0 */
if (is_privileged)
old_fsuid = setfsuid (0);
if (write_file_at (dir_fd, "uid_map", uid_map) != 0)
die_with_error ("setting up uid map");
if (deny_groups &&
write_file_at (dir_fd, "setgroups", "deny\n") != 0)
{
/* If /proc/[pid]/setgroups does not exist, assume we are
* running a linux kernel < 3.19, i.e. we live with the
* vulnerability known as CVE-2014-8989 in older kernels
* where setgroups does not exist.
*/
if (errno != ENOENT)
die_with_error ("error writing to setgroups");
}
if (write_file_at (dir_fd, "gid_map", gid_map) != 0)
die_with_error ("setting up gid map");
if (is_privileged)
{
setfsuid (old_fsuid);
if (setfsuid (-1) != real_uid)
die ("Unable to re-set fsuid");
}
}
static void
privileged_op (int privileged_op_socket,
uint32_t op,
uint32_t flags,
const char *arg1,
const char *arg2)
{
if (privileged_op_socket != -1)
{
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
PrivSepOp *op_buffer = (PrivSepOp *) buffer;
size_t buffer_size = sizeof (PrivSepOp);
uint32_t arg1_offset = 0, arg2_offset = 0;
/* We're unprivileged, send this request to the privileged part */
if (arg1 != NULL)
{
arg1_offset = buffer_size;
buffer_size += strlen (arg1) + 1;
}
if (arg2 != NULL)
{
arg2_offset = buffer_size;
buffer_size += strlen (arg2) + 1;
}
if (buffer_size >= sizeof (buffer))
die ("privilege separation operation to large");
op_buffer->op = op;
op_buffer->flags = flags;
op_buffer->arg1_offset = arg1_offset;
op_buffer->arg2_offset = arg2_offset;
if (arg1 != NULL)
strcpy ((char *) buffer + arg1_offset, arg1);
if (arg2 != NULL)
strcpy ((char *) buffer + arg2_offset, arg2);
if (write (privileged_op_socket, buffer, buffer_size) != buffer_size)
die ("Can't write to privileged_op_socket");
if (read (privileged_op_socket, buffer, 1) != 1)
die ("Can't read from privileged_op_socket");
return;
}
/*
* This runs a privileged request for the unprivileged setup
* code. Note that since the setup code is unprivileged it is not as
* trusted, so we need to verify that all requests only affect the
* child namespace as set up by the privileged parts of the setup,
* and that all the code is very careful about handling input.
*
* This means:
* * Bind mounts are safe, since we always use filesystem namespace. They
* must be recursive though, as otherwise you can use a non-recursive bind
* mount to access an otherwise over-mounted mountpoint.
* * Mounting proc, tmpfs, mqueue, devpts in the child namespace is assumed to
* be safe.
* * Remounting RO (even non-recursive) is safe because it decreases privileges.
* * sethostname() is safe only if we set up a UTS namespace
*/
switch (op)
{
case PRIV_SEP_OP_DONE:
break;
case PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE:
if (bind_mount (proc_fd, NULL, arg2, BIND_READONLY) != 0)
die_with_error ("Can't remount readonly on %s", arg2);
break;
case PRIV_SEP_OP_BIND_MOUNT:
/* We always bind directories recursively, otherwise this would let us
access files that are otherwise covered on the host */
if (bind_mount (proc_fd, arg1, arg2, BIND_RECURSIVE | flags) != 0)
die_with_error ("Can't bind mount %s on %s", arg1, arg2);
break;
case PRIV_SEP_OP_PROC_MOUNT:
if (mount ("proc", arg1, "proc", MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL) != 0)
die_with_error ("Can't mount proc on %s", arg1);
break;
case PRIV_SEP_OP_TMPFS_MOUNT:
{
cleanup_free char *opt = label_mount ("mode=0755", opt_file_label);
if (mount ("tmpfs", arg1, "tmpfs", MS_NOSUID | MS_NODEV, opt) != 0)
die_with_error ("Can't mount tmpfs on %s", arg1);
break;
}
case PRIV_SEP_OP_DEVPTS_MOUNT:
if (mount ("devpts", arg1, "devpts", MS_NOSUID | MS_NOEXEC,
"newinstance,ptmxmode=0666,mode=620") != 0)
die_with_error ("Can't mount devpts on %s", arg1);
break;
case PRIV_SEP_OP_MQUEUE_MOUNT:
if (mount ("mqueue", arg1, "mqueue", 0, NULL) != 0)
die_with_error ("Can't mount mqueue on %s", arg1);
break;
case PRIV_SEP_OP_SET_HOSTNAME:
/* This is checked at the start, but lets verify it here in case
something manages to send hacked priv-sep operation requests. */
if (!opt_unshare_uts)
die ("Refusing to set hostname in original namespace");
if (sethostname (arg1, strlen(arg1)) != 0)
die_with_error ("Can't set hostname to %s", arg1);
break;
default:
die ("Unexpected privileged op %d", op);
}
}
/* This is run unprivileged in the child namespace but can request
* some privileged operations (also in the child namespace) via the
* privileged_op_socket.
*/
static void
setup_newroot (bool unshare_pid,
int privileged_op_socket)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
cleanup_free char *source = NULL;
cleanup_free char *dest = NULL;
int source_mode = 0;
int i;
if (op->source &&
op->type != SETUP_MAKE_SYMLINK)
{
source = get_oldroot_path (op->source);
source_mode = get_file_mode (source);
if (source_mode < 0)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
continue; /* Ignore and move on */
die_with_error("Can't get type of source %s", op->source);
}
}
if (op->dest &&
(op->flags & NO_CREATE_DEST) == 0)
{
dest = get_newroot_path (op->dest);
if (mkdir_with_parents (dest, 0755, FALSE) != 0)
die_with_error ("Can't mkdir parents for %s", op->dest);
}
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
if (source_mode == S_IFDIR)
{
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
}
else if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_RO_BIND_MOUNT ? BIND_READONLY : 0) |
(op->type == SETUP_DEV_BIND_MOUNT ? BIND_DEVICES : 0),
source, dest);
break;
case SETUP_REMOUNT_RO_NO_RECURSIVE:
privileged_op (privileged_op_socket,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, 0, NULL, dest);
break;
case SETUP_MOUNT_PROC:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
if (unshare_pid)
{
/* Our own procfs */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_PROC_MOUNT, 0,
dest, NULL);
}
else
{
/* Use system procfs, as we share pid namespace anyway */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, 0,
"oldroot/proc", dest);
}
/* There are a bunch of weird old subdirs of /proc that could potentially be
problematic (for instance /proc/sysrq-trigger lets you shut down the machine
if you have write access). We should not have access to these as a non-privileged
user, but lets cover them anyway just to make sure */
const char *cover_proc_dirs[] = { "sys", "sysrq-trigger", "irq", "bus" };
for (i = 0; i < N_ELEMENTS (cover_proc_dirs); i++)
{
cleanup_free char *subdir = strconcat3 (dest, "/", cover_proc_dirs[i]);
if (access (subdir, W_OK) < 0)
{
/* The file is already read-only or doesn't exist. */
if (errno == EACCES || errno == ENOENT)
continue;
die_with_error ("Can't access %s", subdir);
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_READONLY,
subdir, subdir);
}
break;
case SETUP_MOUNT_DEV:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
static const char *const devnodes[] = { "null", "zero", "full", "random", "urandom", "tty" };
for (i = 0; i < N_ELEMENTS (devnodes); i++)
{
cleanup_free char *node_dest = strconcat3 (dest, "/", devnodes[i]);
cleanup_free char *node_src = strconcat ("/oldroot/dev/", devnodes[i]);
if (create_file (node_dest, 0666, NULL) != 0)
die_with_error ("Can't create file %s/%s", op->dest, devnodes[i]);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
node_src, node_dest);
}
static const char *const stdionodes[] = { "stdin", "stdout", "stderr" };
for (i = 0; i < N_ELEMENTS (stdionodes); i++)
{
cleanup_free char *target = xasprintf ("/proc/self/fd/%d", i);
cleanup_free char *node_dest = strconcat3 (dest, "/", stdionodes[i]);
if (symlink (target, node_dest) < 0)
die_with_error ("Can't create symlink %s/%s", op->dest, stdionodes[i]);
}
/* /dev/fd and /dev/core - legacy, but both nspawn and docker do these */
{ cleanup_free char *dev_fd = strconcat (dest, "/fd");
if (symlink ("/proc/self/fd", dev_fd) < 0)
die_with_error ("Can't create symlink %s", dev_fd);
}
{ cleanup_free char *dev_core = strconcat (dest, "/core");
if (symlink ("/proc/kcore", dev_core) < 0)
die_with_error ("Can't create symlink %s", dev_core);
}
{
cleanup_free char *pts = strconcat (dest, "/pts");
cleanup_free char *ptmx = strconcat (dest, "/ptmx");
cleanup_free char *shm = strconcat (dest, "/shm");
if (mkdir (shm, 0755) == -1)
die_with_error ("Can't create %s/shm", op->dest);
if (mkdir (pts, 0755) == -1)
die_with_error ("Can't create %s/devpts", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DEVPTS_MOUNT, 0, pts, NULL);
if (symlink ("pts/ptmx", ptmx) != 0)
die_with_error ("Can't make symlink at %s/ptmx", op->dest);
}
/* If stdout is a tty, that means the sandbox can write to the
outside-sandbox tty. In that case we also create a /dev/console
that points to this tty device. This should not cause any more
access than we already have, and it makes ttyname() work in the
sandbox. */
if (host_tty_dev != NULL && *host_tty_dev != 0)
{
cleanup_free char *src_tty_dev = strconcat ("/oldroot", host_tty_dev);
cleanup_free char *dest_console = strconcat (dest, "/console");
if (create_file (dest_console, 0666, NULL) != 0)
die_with_error ("creating %s/console", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
src_tty_dev, dest_console);
}
break;
case SETUP_MOUNT_TMPFS:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
break;
case SETUP_MOUNT_MQUEUE:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_MQUEUE_MOUNT, 0,
dest, NULL);
break;
case SETUP_MAKE_DIR:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
break;
case SETUP_MAKE_FILE:
{
cleanup_fd int dest_fd = -1;
dest_fd = creat (dest, 0666);
if (dest_fd == -1)
die_with_error ("Can't create file %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
}
break;
case SETUP_MAKE_BIND_FILE:
case SETUP_MAKE_RO_BIND_FILE:
{
cleanup_fd int dest_fd = -1;
char tempfile[] = "/bindfileXXXXXX";
dest_fd = mkstemp (tempfile);
if (dest_fd == -1)
die_with_error ("Can't create tmpfile for %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
assert (dest != NULL);
if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_MAKE_RO_BIND_FILE ? BIND_READONLY : 0),
tempfile, dest);
/* Remove the file so we're sure the app can't get to it in any other way.
Its outside the container chroot, so it shouldn't be possible, but lets
make it really sure. */
unlink (tempfile);
}
break;
case SETUP_MAKE_SYMLINK:
assert (op->source != NULL); /* guaranteed by the constructor */
if (symlink (op->source, dest) != 0)
die_with_error ("Can't make symlink at %s", op->dest);
break;
case SETUP_SET_HOSTNAME:
assert (op->dest != NULL); /* guaranteed by the constructor */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_SET_HOSTNAME, 0,
op->dest, NULL);
break;
default:
die ("Unexpected type %d", op->type);
}
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DONE, 0, NULL, NULL);
}
/* Do not leak file descriptors already used by setup_newroot () */
static void
close_ops_fd (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
if (op->fd != -1)
{
(void) close (op->fd);
op->fd = -1;
}
}
}
/* We need to resolve relative symlinks in the sandbox before we
chroot so that absolute symlinks are handled correctly. We also
need to do this after we've switched to the real uid so that
e.g. paths on fuse mounts work */
static void
resolve_symlinks_in_ops (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
const char *old_source;
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
old_source = op->source;
op->source = realpath (old_source, NULL);
if (op->source == NULL)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
op->source = old_source;
else
die_with_error("Can't find source path %s", old_source);
}
break;
default:
break;
}
}
}
static const char *
resolve_string_offset (void *buffer,
size_t buffer_size,
uint32_t offset)
{
if (offset == 0)
return NULL;
if (offset > buffer_size)
die ("Invalid string offset %d (buffer size %zd)", offset, buffer_size);
return (const char *) buffer + offset;
}
static uint32_t
read_priv_sec_op (int read_socket,
void *buffer,
size_t buffer_size,
uint32_t *flags,
const char **arg1,
const char **arg2)
{
const PrivSepOp *op = (const PrivSepOp *) buffer;
ssize_t rec_len;
do
rec_len = read (read_socket, buffer, buffer_size - 1);
while (rec_len == -1 && errno == EINTR);
if (rec_len < 0)
die_with_error ("Can't read from unprivileged helper");
if (rec_len == 0)
exit (1); /* Privileged helper died and printed error, so exit silently */
if (rec_len < sizeof (PrivSepOp))
die ("Invalid size %zd from unprivileged helper", rec_len);
/* Guarantee zero termination of any strings */
((char *) buffer)[rec_len] = 0;
*flags = op->flags;
*arg1 = resolve_string_offset (buffer, rec_len, op->arg1_offset);
*arg2 = resolve_string_offset (buffer, rec_len, op->arg2_offset);
return op->op;
}
static void __attribute__ ((noreturn))
print_version_and_exit (void)
{
printf ("%s\n", PACKAGE_STRING);
exit (0);
}
static void
parse_args_recurse (int *argcp,
const char ***argvp,
bool in_file,
int *total_parsed_argc_p)
{
SetupOp *op;
int argc = *argcp;
const char **argv = *argvp;
/* I can't imagine a case where someone wants more than this.
* If you do...you should be able to pass multiple files
* via a single tmpfs and linking them there, etc.
*
* We're adding this hardening due to precedent from
* http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html
*
* I picked 9000 because the Internet told me to and it was hard to
* resist.
*/
static const uint32_t MAX_ARGS = 9000;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
while (argc > 0)
{
const char *arg = argv[0];
if (strcmp (arg, "--help") == 0)
{
usage (EXIT_SUCCESS, stdout);
}
else if (strcmp (arg, "--version") == 0)
{
print_version_and_exit ();
}
else if (strcmp (arg, "--args") == 0)
{
int the_fd;
char *endptr;
const char *p, *data_end;
size_t data_len;
cleanup_free const char **data_argv = NULL;
const char **data_argv_copy;
int data_argc;
int i;
if (in_file)
die ("--args not supported in arguments file");
if (argc < 2)
die ("--args takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
/* opt_args_data is essentially a recursive argv array, which we must
* keep allocated until exit time, since its argv entries get used
* by the other cases in parse_args_recurse() when we recurse. */
opt_args_data = load_file_data (the_fd, &data_len);
if (opt_args_data == NULL)
die_with_error ("Can't read --args data");
(void) close (the_fd);
data_end = opt_args_data + data_len;
data_argc = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
data_argc++;
(*total_parsed_argc_p)++;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv = xcalloc (sizeof (char *) * (data_argc + 1));
i = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
/* Note: load_file_data always adds a nul terminator, so this is safe
* even for the last string. */
data_argv[i++] = p;
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */
parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--unshare-all") == 0)
{
/* Keep this in order with the older (legacy) --unshare arguments,
* we use the --try variants of user and cgroup, since we want
* to support systems/kernels without support for those.
*/
opt_unshare_user_try = opt_unshare_ipc = opt_unshare_pid =
opt_unshare_uts = opt_unshare_cgroup_try =
opt_unshare_net = TRUE;
}
/* Begin here the older individual --unshare variants */
else if (strcmp (arg, "--unshare-user") == 0)
{
opt_unshare_user = TRUE;
}
else if (strcmp (arg, "--unshare-user-try") == 0)
{
opt_unshare_user_try = TRUE;
}
else if (strcmp (arg, "--unshare-ipc") == 0)
{
opt_unshare_ipc = TRUE;
}
else if (strcmp (arg, "--unshare-pid") == 0)
{
opt_unshare_pid = TRUE;
}
else if (strcmp (arg, "--unshare-net") == 0)
{
opt_unshare_net = TRUE;
}
else if (strcmp (arg, "--unshare-uts") == 0)
{
opt_unshare_uts = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup") == 0)
{
opt_unshare_cgroup = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup-try") == 0)
{
opt_unshare_cgroup_try = TRUE;
}
/* Begin here the newer --share variants */
else if (strcmp (arg, "--share-net") == 0)
{
opt_unshare_net = FALSE;
}
/* End --share variants, other arguments begin */
else if (strcmp (arg, "--chdir") == 0)
{
if (argc < 2)
die ("--chdir takes one argument");
opt_chdir_path = argv[1];
argv++;
argc--;
}
else if (strcmp (arg, "--remount-ro") == 0)
{
if (argc < 2)
die ("--remount-ro takes one argument");
SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE);
op->dest = argv[1];
argv++;
argc--;
}
else if (strcmp(arg, "--bind") == 0 ||
strcmp(arg, "--bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp(arg, "--ro-bind") == 0 ||
strcmp(arg, "--ro-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_RO_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--ro-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--dev-bind") == 0 ||
strcmp (arg, "--dev-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_DEV_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--dev-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--proc") == 0)
{
if (argc < 2)
die ("--proc takes an argument");
op = setup_op_new (SETUP_MOUNT_PROC);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--exec-label") == 0)
{
if (argc < 2)
die ("--exec-label takes an argument");
opt_exec_label = argv[1];
die_unless_label_valid (opt_exec_label);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file-label") == 0)
{
if (argc < 2)
die ("--file-label takes an argument");
opt_file_label = argv[1];
die_unless_label_valid (opt_file_label);
if (label_create_file (opt_file_label))
die_with_error ("--file-label setup failed");
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dev") == 0)
{
if (argc < 2)
die ("--dev takes an argument");
op = setup_op_new (SETUP_MOUNT_DEV);
op->dest = argv[1];
opt_needs_devpts = TRUE;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--tmpfs") == 0)
{
if (argc < 2)
die ("--tmpfs takes an argument");
op = setup_op_new (SETUP_MOUNT_TMPFS);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--mqueue") == 0)
{
if (argc < 2)
die ("--mqueue takes an argument");
op = setup_op_new (SETUP_MOUNT_MQUEUE);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dir") == 0)
{
if (argc < 2)
die ("--dir takes an argument");
op = setup_op_new (SETUP_MAKE_DIR);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--file takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--ro-bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--ro-bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_RO_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--symlink") == 0)
{
if (argc < 3)
die ("--symlink takes two arguments");
op = setup_op_new (SETUP_MAKE_SYMLINK);
op->source = argv[1];
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--lock-file") == 0)
{
if (argc < 2)
die ("--lock-file takes an argument");
(void) lock_file_new (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--sync-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--sync-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_sync_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns-block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns-block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--info-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--info-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_info_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--json-status-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--json-status-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_json_status_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--seccomp") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--seccomp takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_seccomp_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--setenv") == 0)
{
if (argc < 3)
die ("--setenv takes two arguments");
xsetenv (argv[1], argv[2], 1);
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--unsetenv") == 0)
{
if (argc < 2)
die ("--unsetenv takes an argument");
xunsetenv (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--uid") == 0)
{
int the_uid;
char *endptr;
if (argc < 2)
die ("--uid takes an argument");
the_uid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0)
die ("Invalid uid: %s", argv[1]);
opt_sandbox_uid = the_uid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--gid") == 0)
{
int the_gid;
char *endptr;
if (argc < 2)
die ("--gid takes an argument");
the_gid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0)
die ("Invalid gid: %s", argv[1]);
opt_sandbox_gid = the_gid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--hostname") == 0)
{
if (argc < 2)
die ("--hostname takes an argument");
op = setup_op_new (SETUP_SET_HOSTNAME);
op->dest = argv[1];
op->flags = NO_CREATE_DEST;
opt_sandbox_hostname = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--new-session") == 0)
{
opt_new_session = TRUE;
}
else if (strcmp (arg, "--die-with-parent") == 0)
{
opt_die_with_parent = TRUE;
}
else if (strcmp (arg, "--as-pid-1") == 0)
{
opt_as_pid_1 = TRUE;
}
else if (strcmp (arg, "--cap-add") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-add takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0xFFFFFFFF;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] |= CAP_TO_MASK_0 (cap);
else
requested_caps[1] |= CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--cap-drop") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-drop takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] &= ~CAP_TO_MASK_0 (cap);
else
requested_caps[1] &= ~CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--") == 0)
{
argv += 1;
argc -= 1;
break;
}
else if (*arg == '-')
{
die ("Unknown option %s", arg);
}
else
{
break;
}
argv++;
argc--;
}
*argcp = argc;
*argvp = argv;
}
static void
parse_args (int *argcp,
const char ***argvp)
{
int total_parsed_argc = *argcp;
parse_args_recurse (argcp, argvp, FALSE, &total_parsed_argc);
}
static void
read_overflowids (void)
{
cleanup_free char *uid_data = NULL;
cleanup_free char *gid_data = NULL;
uid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowuid");
if (uid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowuid");
overflow_uid = strtol (uid_data, NULL, 10);
if (overflow_uid == 0)
die ("Can't parse /proc/sys/kernel/overflowuid");
gid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowgid");
if (gid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowgid");
overflow_gid = strtol (gid_data, NULL, 10);
if (overflow_gid == 0)
die ("Can't parse /proc/sys/kernel/overflowgid");
}
int
main (int argc,
char **argv)
{
mode_t old_umask;
cleanup_free char *base_path = NULL;
int clone_flags;
char *old_cwd = NULL;
pid_t pid;
int event_fd = -1;
int child_wait_fd = -1;
int setup_finished_pipe[] = {-1, -1};
const char *new_cwd;
uid_t ns_uid;
gid_t ns_gid;
struct stat sbuf;
uint64_t val;
int res UNUSED;
cleanup_free char *seccomp_data = NULL;
size_t seccomp_len;
struct sock_fprog seccomp_prog;
cleanup_free char *args_data = NULL;
/* Handle --version early on before we try to acquire/drop
* any capabilities so it works in a build environment;
* right now flatpak's build runs bubblewrap --version.
* https://github.com/projectatomic/bubblewrap/issues/185
*/
if (argc == 2 && (strcmp (argv[1], "--version") == 0))
print_version_and_exit ();
real_uid = getuid ();
real_gid = getgid ();
/* Get the (optional) privileges we need */
acquire_privs ();
/* Never gain any more privs during exec */
if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed");
/* The initial code is run with high permissions
(i.e. CAP_SYS_ADMIN), so take lots of care. */
read_overflowids ();
argv0 = argv[0];
if (isatty (1))
host_tty_dev = ttyname (1);
argv++;
argc--;
if (argc == 0)
usage (EXIT_FAILURE, stderr);
parse_args (&argc, (const char ***) &argv);
/* suck the args into a cleanup_free variable to control their lifecycle */
args_data = opt_args_data;
opt_args_data = NULL;
if ((requested_caps[0] || requested_caps[1]) && is_privileged)
die ("--cap-add in setuid mode can be used only by root");
if (opt_userns_block_fd != -1 && !opt_unshare_user)
die ("--userns-block-fd requires --unshare-user");
if (opt_userns_block_fd != -1 && opt_info_fd == -1)
die ("--userns-block-fd requires --info-fd");
/* We have to do this if we weren't installed setuid (and we're not
* root), so let's just DWIM */
if (!is_privileged && getuid () != 0)
opt_unshare_user = TRUE;
#ifdef ENABLE_REQUIRE_USERNS
/* In this build option, we require userns. */
if (is_privileged && getuid () != 0)
opt_unshare_user = TRUE;
#endif
if (opt_unshare_user_try &&
stat ("/proc/self/ns/user", &sbuf) == 0)
{
bool disabled = FALSE;
/* RHEL7 has a kernel module parameter that lets you enable user namespaces */
if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0)
{
cleanup_free char *enable = NULL;
enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable");
if (enable != NULL && enable[0] == 'N')
disabled = TRUE;
}
/* Check for max_user_namespaces */
if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0)
{
cleanup_free char *max_user_ns = NULL;
max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces");
if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0)
disabled = TRUE;
}
/* Debian lets you disable *unprivileged* user namespaces. However this is not
a problem if we're privileged, and if we're not opt_unshare_user is TRUE
already, and there is not much we can do, its just a non-working setup. */
if (!disabled)
opt_unshare_user = TRUE;
}
if (argc == 0)
usage (EXIT_FAILURE, stderr);
__debug__ (("Creating root mount point\n"));
if (opt_sandbox_uid == -1)
opt_sandbox_uid = real_uid;
if (opt_sandbox_gid == -1)
opt_sandbox_gid = real_gid;
if (!opt_unshare_user && opt_sandbox_uid != real_uid)
die ("Specifying --uid requires --unshare-user");
if (!opt_unshare_user && opt_sandbox_gid != real_gid)
die ("Specifying --gid requires --unshare-user");
if (!opt_unshare_uts && opt_sandbox_hostname != NULL)
die ("Specifying --hostname requires --unshare-uts");
if (opt_as_pid_1 && !opt_unshare_pid)
die ("Specifying --as-pid-1 requires --unshare-pid");
if (opt_as_pid_1 && lock_files != NULL)
die ("Specifying --as-pid-1 and --lock-file is not permitted");
/* We need to read stuff from proc during the pivot_root dance, etc.
Lets keep a fd to it open */
proc_fd = open ("/proc", O_PATH);
if (proc_fd == -1)
die_with_error ("Can't open /proc");
/* We need *some* mountpoint where we can mount the root tmpfs.
We first try in /run, and if that fails, try in /tmp. */
base_path = xasprintf ("/run/user/%d/.bubblewrap", real_uid);
if (ensure_dir (base_path, 0755))
{
free (base_path);
base_path = xasprintf ("/tmp/.bubblewrap-%d", real_uid);
if (ensure_dir (base_path, 0755))
die_with_error ("Creating root mountpoint failed");
}
__debug__ (("creating new namespace\n"));
if (opt_unshare_pid && !opt_as_pid_1)
{
event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
if (event_fd == -1)
die_with_error ("eventfd()");
}
/* We block sigchild here so that we can use signalfd in the monitor. */
block_sigchild ();
clone_flags = SIGCHLD | CLONE_NEWNS;
if (opt_unshare_user)
clone_flags |= CLONE_NEWUSER;
if (opt_unshare_pid)
clone_flags |= CLONE_NEWPID;
if (opt_unshare_net)
clone_flags |= CLONE_NEWNET;
if (opt_unshare_ipc)
clone_flags |= CLONE_NEWIPC;
if (opt_unshare_uts)
clone_flags |= CLONE_NEWUTS;
if (opt_unshare_cgroup)
{
if (stat ("/proc/self/ns/cgroup", &sbuf))
{
if (errno == ENOENT)
die ("Cannot create new cgroup namespace because the kernel does not support it");
else
die_with_error ("stat on /proc/self/ns/cgroup failed");
}
clone_flags |= CLONE_NEWCGROUP;
}
if (opt_unshare_cgroup_try)
if (!stat ("/proc/self/ns/cgroup", &sbuf))
clone_flags |= CLONE_NEWCGROUP;
child_wait_fd = eventfd (0, EFD_CLOEXEC);
if (child_wait_fd == -1)
die_with_error ("eventfd()");
/* Track whether pre-exec setup finished if we're reporting process exit */
if (opt_json_status_fd != -1)
{
int ret;
ret = pipe2 (setup_finished_pipe, O_CLOEXEC);
if (ret == -1)
die_with_error ("pipe2()");
}
pid = raw_clone (clone_flags, NULL);
if (pid == -1)
{
if (opt_unshare_user)
{
if (errno == EINVAL)
die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems.");
else if (errno == EPERM && !is_privileged)
die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'.");
}
die_with_error ("Creating new namespace failed");
}
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (pid != 0)
{
/* Parent, outside sandbox, privileged (initially) */
if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* We're running as euid 0, but the uid we want to map is
* not 0. This means we're not allowed to write this from
* the child user namespace, so we do it from the parent.
*
* Also, we map uid/gid 0 in the namespace (to overflowuid)
* if opt_needs_devpts is true, because otherwise the mount
* of devpts fails due to root not being mapped.
*/
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
pid, TRUE, opt_needs_devpts);
}
/* Initial launched process, wait for exec:ed command to exit */
/* We don't need any privileges in the launcher, drop them immediately. */
drop_privs (FALSE);
/* Optionally bind our lifecycle to that of the parent */
handle_die_with_parent ();
if (opt_info_fd != -1)
{
cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid);
dump_info (opt_info_fd, output, TRUE);
close (opt_info_fd);
}
if (opt_json_status_fd != -1)
{
cleanup_free char *output = xasprintf ("{ \"child-pid\": %i }\n", pid);
dump_info (opt_json_status_fd, output, TRUE);
}
if (opt_userns_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1));
close (opt_userns_block_fd);
}
/* Let child run now that the uid maps are set up */
val = 1;
res = write (child_wait_fd, &val, 8);
/* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */
close (child_wait_fd);
return monitor_child (event_fd, pid, setup_finished_pipe[0]);
}
/* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user).
*
* Note that for user namespaces we run as euid 0 during clone(), so
* the child user namespace is owned by euid 0., This means that the
* regular user namespace parent (with uid != 0) doesn't have any
* capabilities in it, which is nice as we can't exploit those. In
* particular the parent user namespace doesn't have CAP_PTRACE
* which would otherwise allow the parent to hijack of the child
* after this point.
*
* Unfortunately this also means you can't ptrace the final
* sandboxed process from outside the sandbox either.
*/
if (opt_info_fd != -1)
close (opt_info_fd);
if (opt_json_status_fd != -1)
close (opt_json_status_fd);
/* Wait for the parent to init uid/gid maps and drop caps */
res = read (child_wait_fd, &val, 8);
close (child_wait_fd);
/* At this point we can completely drop root uid, but retain the
* required permitted caps. This allow us to do full setup as
* the user uid, which makes e.g. fuse access work.
*/
switch_to_user_with_privs ();
if (opt_unshare_net)
loopback_setup (); /* Will exit if unsuccessful */
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* In the unprivileged case we have to write the uid/gid maps in
* the child, because we have no caps in the parent */
if (opt_needs_devpts)
{
/* This is a bit hacky, but we need to first map the real uid/gid to
0, otherwise we can't mount the devpts filesystem because root is
not mapped. Later we will create another child user namespace and
map back to the real uid */
ns_uid = 0;
ns_gid = 0;
}
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
-1, TRUE, FALSE);
}
old_umask = umask (0);
/* Need to do this before the chroot, but after we're the real uid */
resolve_symlinks_in_ops ();
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
die_with_error ("Failed to make / slave");
/* Create a tmpfs which we will use as / in the namespace */
if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0)
die_with_error ("Failed to mount tmpfs");
old_cwd = get_current_dir_name ();
/* Chdir to the new root tmpfs mount. This will be the CWD during
the entire setup. Access old or new root via "oldroot" and "newroot". */
if (chdir (base_path) != 0)
die_with_error ("chdir base_path");
/* We create a subdir "$base_path/newroot" for the new root, that
* way we can pivot_root to base_path, and put the old root at
* "$base_path/oldroot". This avoids problems accessing the oldroot
* dir if the user requested to bind mount something over / */
if (mkdir ("newroot", 0755))
die_with_error ("Creating newroot failed");
if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0)
die_with_error ("setting up newroot bind");
if (mkdir ("oldroot", 0755))
die_with_error ("Creating oldroot failed");
if (pivot_root (base_path, "oldroot"))
die_with_error ("pivot_root");
if (chdir ("/") != 0)
die_with_error ("chdir / (base path)");
if (is_privileged)
{
pid_t child;
int privsep_sockets[2];
if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0)
die_with_error ("Can't create privsep socket");
child = fork ();
if (child == -1)
die_with_error ("Can't fork unprivileged helper");
if (child == 0)
{
/* Unprivileged setup process */
drop_privs (FALSE);
close (privsep_sockets[0]);
setup_newroot (opt_unshare_pid, privsep_sockets[1]);
exit (0);
}
else
{
int status;
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
uint32_t op, flags;
const char *arg1, *arg2;
cleanup_fd int unpriv_socket = -1;
unpriv_socket = privsep_sockets[0];
close (privsep_sockets[1]);
do
{
op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer),
&flags, &arg1, &arg2);
privileged_op (-1, op, flags, arg1, arg2);
if (write (unpriv_socket, buffer, 1) != 1)
die ("Can't write to op_socket");
}
while (op != PRIV_SEP_OP_DONE);
waitpid (child, &status, 0);
/* Continue post setup */
}
}
else
{
setup_newroot (opt_unshare_pid, -1);
}
close_ops_fd ();
/* The old root better be rprivate or we will send unmount events to the parent namespace */
if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
die_with_error ("Failed to make old root rprivate");
if (umount2 ("oldroot", MNT_DETACH))
die_with_error ("unmount old root");
/* This is our second pivot. It's like we're a Silicon Valley startup flush
* with cash but short on ideas!
*
* We're aiming to make /newroot the real root, and get rid of /oldroot. To do
* that we need a temporary place to store it before we can unmount it.
*/
{ cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY);
if (oldrootfd < 0)
die_with_error ("can't open /");
if (chdir ("/newroot") != 0)
die_with_error ("chdir /newroot");
/* While the documentation claims that put_old must be underneath
* new_root, it is perfectly fine to use the same directory as the
* kernel checks only if old_root is accessible from new_root.
*
* Both runc and LXC are using this "alternative" method for
* setting up the root of the container:
*
* https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671
* https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121
*/
if (pivot_root (".", ".") != 0)
die_with_error ("pivot_root(/newroot)");
if (fchdir (oldrootfd) < 0)
die_with_error ("fchdir to oldroot");
if (umount2 (".", MNT_DETACH) < 0)
die_with_error ("umount old root");
if (chdir ("/") != 0)
die_with_error ("chdir /");
}
if (opt_unshare_user &&
(ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) &&
opt_userns_block_fd == -1)
{
/* Now that devpts is mounted and we've no need for mount
permissions we can create a new userspace and map our uid
1:1 */
if (unshare (CLONE_NEWUSER))
die_with_error ("unshare user ns");
write_uid_gid_map (opt_sandbox_uid, ns_uid,
opt_sandbox_gid, ns_gid,
-1, FALSE, FALSE);
}
/* All privileged ops are done now, so drop caps we don't need */
drop_privs (!is_privileged);
if (opt_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1));
close (opt_block_fd);
}
if (opt_seccomp_fd != -1)
{
seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len);
if (seccomp_data == NULL)
die_with_error ("Can't read seccomp data");
if (seccomp_len % 8 != 0)
die ("Invalid seccomp data, must be multiple of 8");
seccomp_prog.len = seccomp_len / 8;
seccomp_prog.filter = (struct sock_filter *) seccomp_data;
close (opt_seccomp_fd);
}
umask (old_umask);
new_cwd = "/";
if (opt_chdir_path)
{
if (chdir (opt_chdir_path))
die_with_error ("Can't chdir to %s", opt_chdir_path);
new_cwd = opt_chdir_path;
}
else if (chdir (old_cwd) == 0)
{
/* If the old cwd is mapped in the sandbox, go there */
new_cwd = old_cwd;
}
else
{
/* If the old cwd is not mapped, go to home */
const char *home = getenv ("HOME");
if (home != NULL &&
chdir (home) == 0)
new_cwd = home;
}
xsetenv ("PWD", new_cwd, 1);
free (old_cwd);
if (opt_new_session &&
setsid () == (pid_t) -1)
die_with_error ("setsid");
if (label_exec (opt_exec_label) == -1)
die_with_error ("label_exec %s", argv[0]);
__debug__ (("forking for child\n"));
if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1))
{
/* We have to have a pid 1 in the pid namespace, because
* otherwise we'll get a bunch of zombies as nothing reaps
* them. Alternatively if we're using sync_fd or lock_files we
* need some process to own these.
*/
pid = fork ();
if (pid == -1)
die_with_error ("Can't fork for pid 1");
if (pid != 0)
{
drop_all_caps (FALSE);
/* Close fds in pid 1, except stdio and optionally event_fd
(for syncing pid 2 lifetime with monitor_child) and
opt_sync_fd (for syncing sandbox lifetime with outside
process).
Any other fds will been passed on to the child though. */
{
int dont_close[3];
int j = 0;
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_sync_fd != -1)
dont_close[j++] = opt_sync_fd;
dont_close[j++] = -1;
fdwalk (proc_fd, close_extra_fds, dont_close);
}
return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL);
}
}
__debug__ (("launch executable %s\n", argv[0]));
if (proc_fd != -1)
close (proc_fd);
/* If we are using --as-pid-1 leak the sync fd into the sandbox.
--sync-fd will still work unless the container process doesn't close this file. */
if (!opt_as_pid_1)
{
if (opt_sync_fd != -1)
close (opt_sync_fd);
}
/* We want sigchild in the child */
unblock_sigchild ();
/* Optionally bind our lifecycle */
handle_die_with_parent ();
if (!is_privileged)
set_ambient_capabilities ();
/* Should be the last thing before execve() so that filters don't
* need to handle anything above */
if (seccomp_data != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
if (setup_finished_pipe[1] != -1)
{
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
if (execvp (argv[0], argv) == -1)
{
if (setup_finished_pipe[1] != -1)
{
int saved_errno = errno;
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
errno = saved_errno;
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
die_with_error ("execvp %s", argv[0]);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_874_0 |
crossvul-cpp_data_bad_2576_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M PPPP CCCC %
% MM MM P P C %
% M M M PPPP C %
% M M P C %
% M M P CCCC %
% %
% %
% Read/Write Magick Persistant Cache Image Format %
% %
% Software Design %
% Cristy %
% March 2000 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/constitute.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/geometry.h"
#include "magick/hashmap.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/utility.h"
#include "magick/version-private.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteMPCImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M P C %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMPC() returns MagickTrue if the image format type, identified by the
% magick string, is an Magick Persistent Cache image.
%
% The format of the IsMPC method is:
%
% MagickBooleanType IsMPC(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsMPC(const unsigned char *magick,const size_t length)
{
if (length < 14)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"id=MagickCache",14) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C A C H E I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMPCImage() reads an Magick Persistent Cache image file and returns
% it. It allocates the memory necessary for the new Image structure and
% returns a pointer to the new image.
%
% The format of the ReadMPCImage method is:
%
% Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% Decompression code contributed by Kyle Shorter.
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMPCImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
cache_filename[MaxTextExtent],
id[MaxTextExtent],
keyword[MaxTextExtent],
*options;
const unsigned char
*p;
GeometryInfo
geometry_info;
Image
*image;
int
c;
LinkedListInfo
*profiles;
MagickBooleanType
status;
MagickOffsetType
offset;
MagickStatusType
flags;
register ssize_t
i;
size_t
depth,
length;
ssize_t
count;
StringInfo
*profile;
unsigned int
signature;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
(void) CopyMagickString(cache_filename,image->filename,MaxTextExtent);
AppendImageFormat("cache",cache_filename);
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
*id='\0';
(void) ResetMagickMemory(keyword,0,sizeof(keyword));
offset=0;
do
{
/*
Decode image header; header terminates one character beyond a ':'.
*/
profiles=(LinkedListInfo *) NULL;
length=MaxTextExtent;
options=AcquireString((char *) NULL);
signature=GetMagickSignature((const StringInfo *) NULL);
image->depth=8;
image->compression=NoCompression;
while ((isgraph(c) != MagickFalse) && (c != (int) ':'))
{
register char
*p;
if (c == (int) '{')
{
char
*comment;
/*
Read comment-- any text between { }.
*/
length=MaxTextExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if (c == (int) '\\')
c=ReadBlobByte(image);
else
if ((c == EOF) || (c == (int) '}'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MaxTextExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) != MagickFalse)
{
/*
Get the keyword.
*/
length=MaxTextExtent;
p=keyword;
do
{
if (c == (int) '=')
break;
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=(char) c;
c=ReadBlobByte(image);
} while (c != EOF);
*p='\0';
p=options;
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
if (c == (int) '=')
{
/*
Get the keyword value.
*/
c=ReadBlobByte(image);
while ((c != (int) '}') && (c != EOF))
{
if ((size_t) (p-options+1) >= length)
{
*p='\0';
length<<=1;
options=(char *) ResizeQuantumMemory(options,length+
MaxTextExtent,sizeof(*options));
if (options == (char *) NULL)
break;
p=options+strlen(options);
}
*p++=(char) c;
c=ReadBlobByte(image);
if (c == '\\')
{
c=ReadBlobByte(image);
if (c == (int) '}')
{
*p++=(char) c;
c=ReadBlobByte(image);
}
}
if (*options != '{')
if (isspace((int) ((unsigned char) c)) != 0)
break;
}
if (options == (char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
*p='\0';
if (*options == '{')
(void) CopyMagickString(options,options+1,strlen(options));
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'b':
case 'B':
{
if (LocaleCompare(keyword,"background-color") == 0)
{
(void) QueryColorDatabase(options,&image->background_color,
exception);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"border-color") == 0)
{
(void) QueryColorDatabase(options,&image->border_color,
exception);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'c':
case 'C':
{
if (LocaleCompare(keyword,"class") == 0)
{
ssize_t
storage_class;
storage_class=ParseCommandOption(MagickClassOptions,
MagickFalse,options);
if (storage_class < 0)
break;
image->storage_class=(ClassType) storage_class;
break;
}
if (LocaleCompare(keyword,"colors") == 0)
{
image->colors=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,options);
if (colorspace < 0)
break;
image->colorspace=(ColorspaceType) colorspace;
break;
}
if (LocaleCompare(keyword,"compression") == 0)
{
ssize_t
compression;
compression=ParseCommandOption(MagickCompressOptions,
MagickFalse,options);
if (compression < 0)
break;
image->compression=(CompressionType) compression;
break;
}
if (LocaleCompare(keyword,"columns") == 0)
{
image->columns=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'd':
case 'D':
{
if (LocaleCompare(keyword,"delay") == 0)
{
image->delay=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"depth") == 0)
{
image->depth=StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"dispose") == 0)
{
ssize_t
dispose;
dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,
options);
if (dispose < 0)
break;
image->dispose=(DisposeType) dispose;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'e':
case 'E':
{
if (LocaleCompare(keyword,"endian") == 0)
{
ssize_t
endian;
endian=ParseCommandOption(MagickEndianOptions,MagickFalse,
options);
if (endian < 0)
break;
image->endian=(EndianType) endian;
break;
}
if (LocaleCompare(keyword,"error") == 0)
{
image->error.mean_error_per_pixel=StringToDouble(options,
(char **) NULL);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'g':
case 'G':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"green-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.green_primary.x=geometry_info.rho;
image->chromaticity.green_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.green_primary.y=
image->chromaticity.green_primary.x;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'i':
case 'I':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) CopyMagickString(id,options,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"iterations") == 0)
{
image->iterations=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'm':
case 'M':
{
if (LocaleCompare(keyword,"magick-signature") == 0)
{
signature=(unsigned int) StringToUnsignedLong(options);
break;
}
if (LocaleCompare(keyword,"matte") == 0)
{
ssize_t
matte;
matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
options);
if (matte < 0)
break;
image->matte=(MagickBooleanType) matte;
break;
}
if (LocaleCompare(keyword,"matte-color") == 0)
{
(void) QueryColorDatabase(options,&image->matte_color,
exception);
break;
}
if (LocaleCompare(keyword,"maximum-error") == 0)
{
image->error.normalized_maximum_error=StringToDouble(
options,(char **) NULL);
break;
}
if (LocaleCompare(keyword,"mean-error") == 0)
{
image->error.normalized_mean_error=StringToDouble(options,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"montage") == 0)
{
(void) CloneString(&image->montage,options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'o':
case 'O':
{
if (LocaleCompare(keyword,"opaque") == 0)
{
ssize_t
matte;
matte=ParseCommandOption(MagickBooleanOptions,MagickFalse,
options);
if (matte < 0)
break;
image->matte=(MagickBooleanType) matte;
break;
}
if (LocaleCompare(keyword,"orientation") == 0)
{
ssize_t
orientation;
orientation=ParseCommandOption(MagickOrientationOptions,
MagickFalse,options);
if (orientation < 0)
break;
image->orientation=(OrientationType) orientation;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'p':
case 'P':
{
if (LocaleCompare(keyword,"page") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->page);
geometry=DestroyString(geometry);
break;
}
if (LocaleCompare(keyword,"pixel-intensity") == 0)
{
ssize_t
intensity;
intensity=ParseCommandOption(MagickPixelIntensityOptions,
MagickFalse,options);
if (intensity < 0)
break;
image->intensity=(PixelIntensityMethod) intensity;
break;
}
if ((LocaleNCompare(keyword,"profile:",8) == 0) ||
(LocaleNCompare(keyword,"profile-",8) == 0))
{
if (profiles == (LinkedListInfo *) NULL)
profiles=NewLinkedList(0);
(void) AppendValueToLinkedList(profiles,
AcquireString(keyword+8));
profile=BlobToStringInfo((const void *) NULL,(size_t)
StringToLong(options));
if (profile == (StringInfo *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
(void) SetImageProfile(image,keyword+8,profile);
profile=DestroyStringInfo(profile);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'q':
case 'Q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image->quality=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'r':
case 'R':
{
if (LocaleCompare(keyword,"red-primary") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.red_primary.x=geometry_info.rho;
if ((flags & SigmaValue) != 0)
image->chromaticity.red_primary.y=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"rendering-intent") == 0)
{
ssize_t
rendering_intent;
rendering_intent=ParseCommandOption(MagickIntentOptions,
MagickFalse,options);
if (rendering_intent < 0)
break;
image->rendering_intent=(RenderingIntent) rendering_intent;
break;
}
if (LocaleCompare(keyword,"resolution") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->x_resolution=geometry_info.rho;
image->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->y_resolution=image->x_resolution;
break;
}
if (LocaleCompare(keyword,"rows") == 0)
{
image->rows=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 's':
case 'S':
{
if (LocaleCompare(keyword,"scene") == 0)
{
image->scene=StringToUnsignedLong(options);
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 't':
case 'T':
{
if (LocaleCompare(keyword,"ticks-per-second") == 0)
{
image->ticks_per_second=(ssize_t) StringToLong(options);
break;
}
if (LocaleCompare(keyword,"tile-offset") == 0)
{
char
*geometry;
geometry=GetPageGeometry(options);
(void) ParseAbsoluteGeometry(geometry,&image->tile_offset);
geometry=DestroyString(geometry);
}
if (LocaleCompare(keyword,"type") == 0)
{
ssize_t
type;
type=ParseCommandOption(MagickTypeOptions,MagickFalse,
options);
if (type < 0)
break;
image->type=(ImageType) type;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'u':
case 'U':
{
if (LocaleCompare(keyword,"units") == 0)
{
ssize_t
units;
units=ParseCommandOption(MagickResolutionOptions,MagickFalse,
options);
if (units < 0)
break;
image->units=(ResolutionType) units;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
case 'w':
case 'W':
{
if (LocaleCompare(keyword,"white-point") == 0)
{
flags=ParseGeometry(options,&geometry_info);
image->chromaticity.white_point.x=geometry_info.rho;
image->chromaticity.white_point.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.white_point.y=
image->chromaticity.white_point.x;
break;
}
(void) SetImageProperty(image,keyword,options);
break;
}
default:
{
(void) SetImageProperty(image,keyword,options);
break;
}
}
}
else
c=ReadBlobByte(image);
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
options=DestroyString(options);
(void) ReadBlobByte(image);
/*
Verify that required image information is defined.
*/
if ((LocaleCompare(id,"MagickCache") != 0) ||
(image->storage_class == UndefinedClass) ||
(image->compression == UndefinedCompression) || (image->columns == 0) ||
(image->rows == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (signature != GetMagickSignature((const StringInfo *) NULL))
ThrowReaderException(CacheError,"IncompatibleAPI");
if (image->montage != (char *) NULL)
{
register char
*p;
/*
Image directory.
*/
length=MaxTextExtent;
image->directory=AcquireString((char *) NULL);
p=image->directory;
do
{
*p='\0';
if ((strlen(image->directory)+MaxTextExtent) >= length)
{
/*
Allocate more memory for the image directory.
*/
length<<=1;
image->directory=(char *) ResizeQuantumMemory(image->directory,
length+MaxTextExtent,sizeof(*image->directory));
if (image->directory == (char *) NULL)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=image->directory+strlen(image->directory);
}
c=ReadBlobByte(image);
*p++=(char) c;
} while (c != (int) '\0');
}
if (profiles != (LinkedListInfo *) NULL)
{
const char
*name;
const StringInfo
*profile;
register unsigned char
*p;
/*
Read image profiles.
*/
ResetLinkedListIterator(profiles);
name=(const char *) GetNextValueInLinkedList(profiles);
while (name != (const char *) NULL)
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
p=GetStringInfoDatum(profile);
(void) ReadBlob(image,GetStringInfoLength(profile),p);
}
name=(const char *) GetNextValueInLinkedList(profiles);
}
profiles=DestroyLinkedList(profiles,RelinquishMagickMemory);
}
depth=GetImageQuantumDepth(image,MagickFalse);
if (image->storage_class == PseudoClass)
{
size_t
packet_size;
unsigned char
*colormap;
/*
Create image colormap.
*/
packet_size=(size_t) (3UL*depth/8UL);
if ((packet_size*image->colors) > GetBlobSize(image))
ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile");
image->colormap=(PixelPacket *) AcquireQuantumMemory(image->colors+1,
sizeof(*image->colormap));
if (image->colormap == (PixelPacket *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->colors != 0)
{
/*
Read image colormap from file.
*/
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
packet_size*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,packet_size*image->colors,colormap);
if (count != (ssize_t) (packet_size*image->colors))
{
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
p=colormap;
switch (depth)
{
default:
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
ThrowReaderException(CorruptImageError,
"ImageDepthNotSupported");
case 8:
{
unsigned char
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushCharPixel(p,&pixel);
image->colormap[i].red=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].green=ScaleCharToQuantum(pixel);
p=PushCharPixel(p,&pixel);
image->colormap[i].blue=ScaleCharToQuantum(pixel);
}
break;
}
case 16:
{
unsigned short
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleShortToQuantum(pixel);
p=PushShortPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleShortToQuantum(pixel);
}
break;
}
case 32:
{
unsigned int
pixel;
for (i=0; i < (ssize_t) image->colors; i++)
{
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].red=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].green=ScaleLongToQuantum(pixel);
p=PushLongPixel(MSBEndian,p,&pixel);
image->colormap[i].blue=ScaleLongToQuantum(pixel);
}
break;
}
}
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
}
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) ||
(AcquireMagickResource(HeightResource,image->rows) == MagickFalse))
ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit");
/*
Attach persistent pixel cache.
*/
status=PersistPixelCache(image,cache_filename,MagickTrue,&offset,exception);
if (status == MagickFalse)
ThrowReaderException(CacheError,"UnableToPersistPixelCache");
/*
Proceed to next image.
*/
do
{
c=ReadBlobByte(image);
} while ((isgraph(c) == MagickFalse) && (c != EOF));
if (c != EOF)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (c != EOF);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M P C I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMPCImage() adds properties for the Cache image format to
% the list of supported formats. The properties include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMPCImage method is:
%
% size_t RegisterMPCImage(void)
%
*/
ModuleExport size_t RegisterMPCImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CACHE");
entry->description=ConstantString("Magick Persistent Cache image format");
entry->module=ConstantString("MPC");
entry->seekable_stream=MagickTrue;
entry->stealth=MagickTrue;
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("MPC");
entry->decoder=(DecodeImageHandler *) ReadMPCImage;
entry->encoder=(EncodeImageHandler *) WriteMPCImage;
entry->magick=(IsImageFormatHandler *) IsMPC;
entry->description=ConstantString("Magick Persistent Cache image format");
entry->seekable_stream=MagickTrue;
entry->module=ConstantString("MPC");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M P C I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMPCImage() removes format registrations made by the
% MPC module from the list of supported formats.
%
% The format of the UnregisterMPCImage method is:
%
% UnregisterMPCImage(void)
%
*/
ModuleExport void UnregisterMPCImage(void)
{
(void) UnregisterMagickInfo("CACHE");
(void) UnregisterMagickInfo("MPC");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M P C I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMPCImage() writes an Magick Persistent Cache image to a file.
%
% The format of the WriteMPCImage method is:
%
% MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o image: the image.
%
*/
static MagickBooleanType WriteMPCImage(const ImageInfo *image_info,Image *image)
{
char
buffer[MaxTextExtent],
cache_filename[MaxTextExtent];
const char
*property,
*value;
MagickBooleanType
status;
MagickOffsetType
offset,
scene;
register ssize_t
i;
size_t
depth,
one;
/*
Open persistent cache.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) CopyMagickString(cache_filename,image->filename,MaxTextExtent);
AppendImageFormat("cache",cache_filename);
scene=0;
offset=0;
one=1;
do
{
/*
Write persistent cache meta-information.
*/
depth=GetImageQuantumDepth(image,MagickTrue);
if ((image->storage_class == PseudoClass) &&
(image->colors > (one << depth)))
image->storage_class=DirectClass;
(void) WriteBlobString(image,"id=MagickCache\n");
(void) FormatLocaleString(buffer,MaxTextExtent,"magick-signature=%u\n",
GetMagickSignature((const StringInfo *) NULL));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,
"class=%s colors=%.20g matte=%s\n",CommandOptionToMnemonic(
MagickClassOptions,image->storage_class),(double) image->colors,
CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) image->matte));
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,
"columns=%.20g rows=%.20g depth=%.20g\n",(double) image->columns,
(double) image->rows,(double) image->depth);
(void) WriteBlobString(image,buffer);
if (image->type != UndefinedType)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"type=%s\n",
CommandOptionToMnemonic(MagickTypeOptions,image->type));
(void) WriteBlobString(image,buffer);
}
if (image->colorspace != UndefinedColorspace)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"colorspace=%s\n",
CommandOptionToMnemonic(MagickColorspaceOptions,image->colorspace));
(void) WriteBlobString(image,buffer);
}
if (image->intensity != UndefinedPixelIntensityMethod)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"pixel-intensity=%s\n",
CommandOptionToMnemonic(MagickPixelIntensityOptions,
image->intensity));
(void) WriteBlobString(image,buffer);
}
if (image->endian != UndefinedEndian)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"endian=%s\n",
CommandOptionToMnemonic(MagickEndianOptions,image->endian));
(void) WriteBlobString(image,buffer);
}
if (image->compression != UndefinedCompression)
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"compression=%s quality=%.20g\n",CommandOptionToMnemonic(
MagickCompressOptions,image->compression),(double) image->quality);
(void) WriteBlobString(image,buffer);
}
if (image->units != UndefinedResolution)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"units=%s\n",
CommandOptionToMnemonic(MagickResolutionOptions,image->units));
(void) WriteBlobString(image,buffer);
}
if ((image->x_resolution != 0) || (image->y_resolution != 0))
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"resolution=%gx%g\n",image->x_resolution,image->y_resolution);
(void) WriteBlobString(image,buffer);
}
if ((image->page.width != 0) || (image->page.height != 0))
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"page=%.20gx%.20g%+.20g%+.20g\n",(double) image->page.width,(double)
image->page.height,(double) image->page.x,(double) image->page.y);
(void) WriteBlobString(image,buffer);
}
else
if ((image->page.x != 0) || (image->page.y != 0))
{
(void) FormatLocaleString(buffer,MaxTextExtent,"page=%+ld%+ld\n",
(long) image->page.x,(long) image->page.y);
(void) WriteBlobString(image,buffer);
}
if ((image->tile_offset.x != 0) || (image->tile_offset.y != 0))
{
(void) FormatLocaleString(buffer,MaxTextExtent,"tile-offset=%+ld%+ld\n",
(long) image->tile_offset.x,(long) image->tile_offset.y);
(void) WriteBlobString(image,buffer);
}
if ((GetNextImageInList(image) != (Image *) NULL) ||
(GetPreviousImageInList(image) != (Image *) NULL))
{
if (image->scene == 0)
(void) FormatLocaleString(buffer,MaxTextExtent,
"iterations=%.20g delay=%.20g ticks-per-second=%.20g\n",(double)
image->iterations,(double) image->delay,(double)
image->ticks_per_second);
else
(void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g "
"iterations=%.20g delay=%.20g ticks-per-second=%.20g\n",
(double) image->scene,(double) image->iterations,(double)
image->delay,(double) image->ticks_per_second);
(void) WriteBlobString(image,buffer);
}
else
{
if (image->scene != 0)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"scene=%.20g\n",
(double) image->scene);
(void) WriteBlobString(image,buffer);
}
if (image->iterations != 0)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"iterations=%.20g\n",
(double) image->iterations);
(void) WriteBlobString(image,buffer);
}
if (image->delay != 0)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"delay=%.20g\n",
(double) image->delay);
(void) WriteBlobString(image,buffer);
}
if (image->ticks_per_second != UndefinedTicksPerSecond)
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"ticks-per-second=%.20g\n",(double) image->ticks_per_second);
(void) WriteBlobString(image,buffer);
}
}
if (image->gravity != UndefinedGravity)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"gravity=%s\n",
CommandOptionToMnemonic(MagickGravityOptions,image->gravity));
(void) WriteBlobString(image,buffer);
}
if (image->dispose != UndefinedDispose)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"dispose=%s\n",
CommandOptionToMnemonic(MagickDisposeOptions,image->dispose));
(void) WriteBlobString(image,buffer);
}
if (image->rendering_intent != UndefinedIntent)
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"rendering-intent=%s\n",CommandOptionToMnemonic(MagickIntentOptions,
image->rendering_intent));
(void) WriteBlobString(image,buffer);
}
if (image->gamma != 0.0)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"gamma=%g\n",
image->gamma);
(void) WriteBlobString(image,buffer);
}
if (image->chromaticity.white_point.x != 0.0)
{
/*
Note chomaticity points.
*/
(void) FormatLocaleString(buffer,MaxTextExtent,"red-primary="
"%g,%g green-primary=%g,%g blue-primary=%g,%g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,
image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,
image->chromaticity.blue_primary.y);
(void) WriteBlobString(image,buffer);
(void) FormatLocaleString(buffer,MaxTextExtent,
"white-point=%g,%g\n",image->chromaticity.white_point.x,
image->chromaticity.white_point.y);
(void) WriteBlobString(image,buffer);
}
if (image->orientation != UndefinedOrientation)
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"orientation=%s\n",CommandOptionToMnemonic(MagickOrientationOptions,
image->orientation));
(void) WriteBlobString(image,buffer);
}
if (image->profiles != (void *) NULL)
{
const char
*name;
const StringInfo
*profile;
/*
Generic profile.
*/
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
(void) FormatLocaleString(buffer,MaxTextExtent,
"profile:%s=%.20g\n",name,(double)
GetStringInfoLength(profile));
(void) WriteBlobString(image,buffer);
}
name=GetNextImageProfile(image);
}
}
if (image->montage != (char *) NULL)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"montage=%s\n",
image->montage);
(void) WriteBlobString(image,buffer);
}
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) FormatLocaleString(buffer,MaxTextExtent,"%s=",property);
(void) WriteBlobString(image,buffer);
value=GetImageProperty(image,property);
if (value != (const char *) NULL)
{
size_t
length;
length=strlen(value);
for (i=0; i < (ssize_t) length; i++)
if (isspace((int) ((unsigned char) value[i])) != 0)
break;
if ((i == (ssize_t) length) && (i != 0))
(void) WriteBlob(image,length,(const unsigned char *) value);
else
{
(void) WriteBlobByte(image,'{');
if (strchr(value,'}') == (char *) NULL)
(void) WriteBlob(image,length,(const unsigned char *) value);
else
for (i=0; i < (ssize_t) length; i++)
{
if (value[i] == (int) '}')
(void) WriteBlobByte(image,'\\');
(void) WriteBlobByte(image,value[i]);
}
(void) WriteBlobByte(image,'}');
}
}
(void) WriteBlobByte(image,'\n');
property=GetNextImageProperty(image);
}
(void) WriteBlobString(image,"\f\n:\032");
if (image->montage != (char *) NULL)
{
/*
Write montage tile directory.
*/
if (image->directory != (char *) NULL)
(void) WriteBlobString(image,image->directory);
(void) WriteBlobByte(image,'\0');
}
if (image->profiles != 0)
{
const char
*name;
const StringInfo
*profile;
/*
Write image profiles.
*/
ResetImageProfileIterator(image);
name=GetNextImageProfile(image);
while (name != (const char *) NULL)
{
profile=GetImageProfile(image,name);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
name=GetNextImageProfile(image);
}
}
if (image->storage_class == PseudoClass)
{
size_t
packet_size;
unsigned char
*colormap,
*q;
/*
Allocate colormap.
*/
packet_size=(size_t) (3UL*depth/8UL);
colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
packet_size*sizeof(*colormap));
if (colormap == (unsigned char *) NULL)
return(MagickFalse);
/*
Write colormap to file.
*/
q=colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
switch (depth)
{
default:
ThrowWriterException(CorruptImageError,"ImageDepthNotSupported");
case 32:
{
unsigned int
pixel;
pixel=ScaleQuantumToLong(image->colormap[i].red);
q=PopLongPixel(MSBEndian,pixel,q);
pixel=ScaleQuantumToLong(image->colormap[i].green);
q=PopLongPixel(MSBEndian,pixel,q);
pixel=ScaleQuantumToLong(image->colormap[i].blue);
q=PopLongPixel(MSBEndian,pixel,q);
break;
}
case 16:
{
unsigned short
pixel;
pixel=ScaleQuantumToShort(image->colormap[i].red);
q=PopShortPixel(MSBEndian,pixel,q);
pixel=ScaleQuantumToShort(image->colormap[i].green);
q=PopShortPixel(MSBEndian,pixel,q);
pixel=ScaleQuantumToShort(image->colormap[i].blue);
q=PopShortPixel(MSBEndian,pixel,q);
break;
}
case 8:
{
unsigned char
pixel;
pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].red);
q=PopCharPixel(pixel,q);
pixel=(unsigned char) ScaleQuantumToChar(
image->colormap[i].green);
q=PopCharPixel(pixel,q);
pixel=(unsigned char) ScaleQuantumToChar(image->colormap[i].blue);
q=PopCharPixel(pixel,q);
break;
}
}
}
(void) WriteBlob(image,packet_size*image->colors,colormap);
colormap=(unsigned char *) RelinquishMagickMemory(colormap);
}
/*
Initialize persistent pixel cache.
*/
status=PersistPixelCache(image,cache_filename,MagickFalse,&offset,
&image->exception);
if (status == MagickFalse)
ThrowWriterException(CacheError,"UnableToPersistPixelCache");
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
status=image->progress_monitor(SaveImagesTag,scene,
GetImageListLength(image),image->client_data);
if (status == MagickFalse)
break;
}
scene++;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2576_0 |
crossvul-cpp_data_good_5113_0 | /* netscreen.c
*
* Juniper NetScreen snoop output parser
* Created by re-using a lot of code from cosine.c
* Copyright (c) 2007 by Sake Blok <sake@euronet.nl>
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "netscreen.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/* XXX TODO:
*
* o Construct a list of interfaces, with interface names, give
* them link-layer types based on the interface name and packet
* data, and supply interface IDs with each packet (i.e., make
* this supply a pcap-ng-style set of interfaces and associate
* packets with interfaces). This is probably the right way
* to "Pass the interface names and the traffic direction to either
* the frame-structure, a pseudo-header or use PPI." See the
* message at
*
* http://www.wireshark.org/lists/wireshark-dev/200708/msg00029.html
*
* to see whether any further discussion is still needed. I suspect
* it doesn't; pcap-NG existed at the time, as per the final
* message in that thread:
*
* http://www.wireshark.org/lists/wireshark-dev/200708/msg00039.html
*
* but I don't think we fully *supported* it at that point. Now
* that we do, we have the infrastructure to support this, except
* that we currently have no way to translate interface IDs to
* interface names in the "frame" dissector or to supply interface
* information as part of the packet metadata from Wiretap modules.
* That should be fixed so that we can show interface information,
* such as the interface name, in packet dissections from, for example,
* pcap-NG captures.
*/
static gboolean info_line(const gchar *line);
static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr);
static gboolean netscreen_check_file_type(wtap *wth, int *err,
gchar **err_info);
static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean netscreen_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info);
static gboolean parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr,
Buffer* buf, char *line, int *err, gchar **err_info);
static int parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
/* Returns TRUE if the line appears to be a line with protocol info.
Otherwise it returns FALSE. */
static gboolean info_line(const gchar *line)
{
int i=NETSCREEN_SPACES_ON_INFO_LINE;
while (i-- > 0) {
if (g_ascii_isspace(*line)) {
line++;
continue;
} else {
return FALSE;
}
}
return TRUE;
}
/* Seeks to the beginning of the next packet, and returns the
byte offset. Copy the header line to hdr. Returns -1 on failure,
and sets "*err" to the error and sets "*err_info" to null or an
additional error string. */
static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr)
{
gint64 cur_off;
char buf[NETSCREEN_LINE_LENGTH];
while (1) {
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error */
*err = file_error(wth->fh, err_info);
return -1;
}
if (file_gets(buf, sizeof(buf), wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
break;
}
if (strstr(buf, NETSCREEN_REC_MAGIC_STR1) ||
strstr(buf, NETSCREEN_REC_MAGIC_STR2)) {
g_strlcpy(hdr, buf, NETSCREEN_LINE_LENGTH);
return cur_off;
}
}
return -1;
}
/* Look through the first part of a file to see if this is
* NetScreen snoop output.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" is set to null or an additional error string.
*/
static gboolean netscreen_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[NETSCREEN_LINE_LENGTH];
guint reclen, line;
buf[NETSCREEN_LINE_LENGTH-1] = '\0';
for (line = 0; line < NETSCREEN_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, NETSCREEN_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = (guint) strlen(buf);
if (reclen < strlen(NETSCREEN_HDR_MAGIC_STR1) ||
reclen < strlen(NETSCREEN_HDR_MAGIC_STR2)) {
continue;
}
if (strstr(buf, NETSCREEN_HDR_MAGIC_STR1) ||
strstr(buf, NETSCREEN_HDR_MAGIC_STR2)) {
return TRUE;
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val netscreen_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for a NetScreen snoop header line */
if (!netscreen_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */
return WTAP_OPEN_ERROR;
wth->file_encap = WTAP_ENCAP_UNKNOWN;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_NETSCREEN;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = netscreen_read;
wth->subtype_seek_read = netscreen_seek_read;
wth->file_tsprec = WTAP_TSPREC_DSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
char line[NETSCREEN_LINE_LENGTH];
/* Find the next packet */
offset = netscreen_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
/* Parse the header and convert the ASCII hex dump to binary data */
if (!parse_netscreen_packet(wth->fh, &wth->phdr,
wth->frame_buffer, line, err, err_info))
return FALSE;
/*
* If the per-file encapsulation isn't known, set it to this
* packet's encapsulation.
*
* If it *is* known, and it isn't this packet's encapsulation,
* set it to WTAP_ENCAP_PER_PACKET, as this file doesn't
* have a single encapsulation for all packets in the file.
*/
if (wth->file_encap == WTAP_ENCAP_UNKNOWN)
wth->file_encap = wth->phdr.pkt_encap;
else {
if (wth->file_encap != wth->phdr.pkt_encap)
wth->file_encap = WTAP_ENCAP_PER_PACKET;
}
*data_offset = offset;
return TRUE;
}
/* Used to read packets in random-access fashion */
static gboolean
netscreen_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
char line[NETSCREEN_LINE_LENGTH];
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) {
return FALSE;
}
if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) {
*err = file_error(wth->random_fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
return parse_netscreen_packet(wth->random_fh, phdr, buf, line,
err, err_info);
}
/* Parses a packet record header. There are a few possible formats:
*
* XXX list extra formats here!
6843828.0: trust(o) len=98:00121ebbd132->00600868d659/0800
192.168.1.1 -> 192.168.1.10/6
vhl=45, tos=00, id=37739, frag=0000, ttl=64 tlen=84
tcp:ports 2222->2333, seq=3452113890, ack=1540618280, flag=5018/ACK
00 60 08 68 d6 59 00 12 1e bb d1 32 08 00 45 00 .`.h.Y.....2..E.
00 54 93 6b 00 00 40 06 63 dd c0 a8 01 01 c0 a8 .T.k..@.c.......
01 0a 08 ae 09 1d cd c3 13 e2 5b d3 f8 28 50 18 ..........[..(P.
1f d4 79 21 00 00 e7 76 89 64 16 e2 19 0a 80 09 ..y!...v.d......
31 e7 04 28 04 58 f3 d9 b1 9f 3d 65 1a db d8 61 1..(.X....=e...a
2c 21 b6 d3 20 60 0c 8c 35 98 88 cf 20 91 0e a9 ,!...`..5.......
1d 0b ..
*/
static gboolean
parse_netscreen_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer* buf,
char *line, int *err, gchar **err_info)
{
int pkt_len;
int sec;
int dsec;
char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH];
char direction[2];
char cap_src[13];
char cap_dst[13];
guint8 *pd;
gchar *p;
int n, i = 0;
int offset = 0;
gchar dststr[13];
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/",
&sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: Can't parse packet-header");
return -1;
}
if (pkt_len < 0) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: packet header has a negative packet length");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("netscreen: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
/*
* If direction[0] is 'o', the direction is NETSCREEN_EGRESS,
* otherwise it's NETSCREEN_INGRESS.
*/
phdr->ts.secs = sec;
phdr->ts.nsecs = dsec * 100000000;
phdr->len = pkt_len;
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if (n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if (offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
/* Take a string representing one line from a hex dump, with leading white
* space removed, and converts the text to binary data. We place the bytes
* in the buffer at the specified offset.
*
* Returns number of bytes successfully read, -1 if bad. */
static int
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset)
{
int num_items_scanned;
guint8 character;
guint8 byte;
for (num_items_scanned = 0; num_items_scanned < 16; num_items_scanned++) {
character = *rec++;
if (character >= '0' && character <= '9')
byte = character - '0' + 0;
else if (character >= 'A' && character <= 'F')
byte = character - 'A' + 0xA;
else if (character >= 'a' && character <= 'f')
byte = character - 'a' + 0xa;
else if (character == ' ' || character == '\r' || character == '\n' || character == '\0') {
/* Nothing more to parse */
break;
} else
return -1; /* not a hex digit, space before ASCII dump, or EOL */
byte <<= 4;
character = *rec++ & 0xFF;
if (character >= '0' && character <= '9')
byte += character - '0' + 0;
else if (character >= 'A' && character <= 'F')
byte += character - 'A' + 0xA;
else if (character >= 'a' && character <= 'f')
byte += character - 'a' + 0xa;
else
return -1; /* not a hex digit */
buf[byte_offset + num_items_scanned] = byte;
character = *rec++ & 0xFF;
if (character == '\0' || character == '\r' || character == '\n') {
/* Nothing more to parse */
break;
} else if (character != ' ') {
/* not space before ASCII dump */
return -1;
}
}
if (num_items_scanned == 0)
return -1;
return num_items_scanned;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5113_0 |
crossvul-cpp_data_good_5420_1 | /* $Id: parsetagx.c,v 1.18 2006/06/07 03:52:03 inu Exp $ */
#include "fm.h"
#include "myctype.h"
#include "indep.h"
#include "Str.h"
#include "parsetagx.h"
#include "hash.h"
#include "html.c"
/* parse HTML tag */
static int noConv(char *, char **);
static int toNumber(char *, int *);
static int toLength(char *, int *);
static int toAlign(char *, int *);
static int toVAlign(char *, int *);
/* *INDENT-OFF* */
static int (*toValFunc[]) () = {
noConv, /* VTYPE_NONE */
noConv, /* VTYPE_STR */
toNumber, /* VTYPE_NUMBER */
toLength, /* VTYPE_LENGTH */
toAlign, /* VTYPE_ALIGN */
toVAlign, /* VTYPE_VALIGN */
noConv, /* VTYPE_ACTION */
noConv, /* VTYPE_ENCTYPE */
noConv, /* VTYPE_METHOD */
noConv, /* VTYPE_MLENGTH */
noConv, /* VTYPE_TYPE */
};
/* *INDENT-ON* */
static int
noConv(char *oval, char **str)
{
*str = oval;
return 1;
}
static int
toNumber(char *oval, int *num)
{
char *ep;
int x;
x = strtol(oval, &ep, 10);
if (ep > oval) {
*num = x;
return 1;
}
else
return 0;
}
static int
toLength(char *oval, int *len)
{
int w;
if (!IS_DIGIT(oval[0]))
return 0;
w = atoi(oval);
if (w < 0)
return 0;
if (w == 0)
w = 1;
if (oval[strlen(oval) - 1] == '%')
*len = -w;
else
*len = w;
return 1;
}
static int
toAlign(char *oval, int *align)
{
if (strcasecmp(oval, "left") == 0)
*align = ALIGN_LEFT;
else if (strcasecmp(oval, "right") == 0)
*align = ALIGN_RIGHT;
else if (strcasecmp(oval, "center") == 0)
*align = ALIGN_CENTER;
else if (strcasecmp(oval, "top") == 0)
*align = ALIGN_TOP;
else if (strcasecmp(oval, "bottom") == 0)
*align = ALIGN_BOTTOM;
else if (strcasecmp(oval, "middle") == 0)
*align = ALIGN_MIDDLE;
else
return 0;
return 1;
}
static int
toVAlign(char *oval, int *valign)
{
if (strcasecmp(oval, "top") == 0 || strcasecmp(oval, "baseline") == 0)
*valign = VALIGN_TOP;
else if (strcasecmp(oval, "bottom") == 0)
*valign = VALIGN_BOTTOM;
else if (strcasecmp(oval, "middle") == 0)
*valign = VALIGN_MIDDLE;
else
return 0;
return 1;
}
extern Hash_si tagtable;
#define MAX_TAG_LEN 64
struct parsed_tag *
parse_tag(char **s, int internal)
{
struct parsed_tag *tag = NULL;
int tag_id;
char tagname[MAX_TAG_LEN], attrname[MAX_TAG_LEN];
char *p, *q;
int i, attr_id = 0, nattr;
/* Parse tag name */
tagname[0] = '\0';
q = (*s) + 1;
p = tagname;
if (*q == '/') {
*(p++) = *(q++);
SKIP_BLANKS(q);
}
while (*q && !IS_SPACE(*q) && !(tagname[0] != '/' && *q == '/') &&
*q != '>' && p - tagname < MAX_TAG_LEN - 1) {
*(p++) = TOLOWER(*q);
q++;
}
*p = '\0';
while (*q && !IS_SPACE(*q) && !(tagname[0] != '/' && *q == '/') &&
*q != '>')
q++;
tag_id = getHash_si(&tagtable, tagname, HTML_UNKNOWN);
if (tag_id == HTML_UNKNOWN ||
(!internal && TagMAP[tag_id].flag & TFLG_INT))
goto skip_parse_tagarg;
tag = New(struct parsed_tag);
bzero(tag, sizeof(struct parsed_tag));
tag->tagid = tag_id;
if ((nattr = TagMAP[tag_id].max_attribute) > 0) {
tag->attrid = NewAtom_N(unsigned char, nattr);
tag->value = New_N(char *, nattr);
tag->map = NewAtom_N(unsigned char, MAX_TAGATTR);
memset(tag->map, MAX_TAGATTR, MAX_TAGATTR);
memset(tag->attrid, ATTR_UNKNOWN, nattr);
for (i = 0; i < nattr; i++)
tag->map[TagMAP[tag_id].accept_attribute[i]] = i;
}
/* Parse tag arguments */
SKIP_BLANKS(q);
while (1) {
Str value = NULL, value_tmp = NULL;
if (*q == '>' || *q == '\0')
goto done_parse_tag;
p = attrname;
while (*q && *q != '=' && !IS_SPACE(*q) &&
*q != '>' && p - attrname < MAX_TAG_LEN - 1) {
*(p++) = TOLOWER(*q);
q++;
}
*p = '\0';
while (*q && *q != '=' && !IS_SPACE(*q) && *q != '>')
q++;
SKIP_BLANKS(q);
if (*q == '=') {
/* get value */
value_tmp = Strnew();
q++;
SKIP_BLANKS(q);
if (*q == '"') {
q++;
while (*q && *q != '"') {
Strcat_char(value_tmp, *q);
if (!tag->need_reconstruct && is_html_quote(*q))
tag->need_reconstruct = TRUE;
q++;
}
if (*q == '"')
q++;
}
else if (*q == '\'') {
q++;
while (*q && *q != '\'') {
Strcat_char(value_tmp, *q);
if (!tag->need_reconstruct && is_html_quote(*q))
tag->need_reconstruct = TRUE;
q++;
}
if (*q == '\'')
q++;
}
else if (*q) {
while (*q && !IS_SPACE(*q) && *q != '>') {
Strcat_char(value_tmp, *q);
if (!tag->need_reconstruct && is_html_quote(*q))
tag->need_reconstruct = TRUE;
q++;
}
}
}
for (i = 0; i < nattr; i++) {
if ((tag)->attrid[i] == ATTR_UNKNOWN &&
strcmp(AttrMAP[TagMAP[tag_id].accept_attribute[i]].name,
attrname) == 0) {
attr_id = TagMAP[tag_id].accept_attribute[i];
break;
}
}
if (value_tmp) {
int j, hidden=FALSE;
for (j=0; j<i; j++) {
if (tag->attrid[j] == ATTR_TYPE &&
tag->value[j] &&
strcmp("hidden",tag->value[j]) == 0) {
hidden=TRUE;
break;
}
}
if ((tag_id == HTML_INPUT || tag_id == HTML_INPUT_ALT) &&
attr_id == ATTR_VALUE && hidden) {
value = value_tmp;
} else {
char *x;
value = Strnew();
for (x = value_tmp->ptr; *x; x++) {
if (*x != '\n')
Strcat_char(value, *x);
}
}
}
if (i != nattr) {
if (!internal &&
((AttrMAP[attr_id].flag & AFLG_INT) ||
(value && AttrMAP[attr_id].vtype == VTYPE_METHOD &&
!strcasecmp(value->ptr, "internal")))) {
tag->need_reconstruct = TRUE;
continue;
}
tag->attrid[i] = attr_id;
if (value)
tag->value[i] = html_unquote(value->ptr);
else
tag->value[i] = NULL;
}
else {
tag->need_reconstruct = TRUE;
}
}
skip_parse_tagarg:
while (*q != '>' && *q)
q++;
done_parse_tag:
if (*q == '>')
q++;
*s = q;
return tag;
}
int
parsedtag_set_value(struct parsed_tag *tag, int id, char *value)
{
int i;
if (!parsedtag_accepts(tag, id))
return 0;
i = tag->map[id];
tag->attrid[i] = id;
if (value)
tag->value[i] = allocStr(value, -1);
else
tag->value[i] = NULL;
tag->need_reconstruct = TRUE;
return 1;
}
int
parsedtag_get_value(struct parsed_tag *tag, int id, void *value)
{
int i;
if (!parsedtag_exists(tag, id) || !tag->value[i = tag->map[id]])
return 0;
return toValFunc[AttrMAP[id].vtype] (tag->value[i], value);
}
Str
parsedtag2str(struct parsed_tag *tag)
{
int i;
int tag_id = tag->tagid;
int nattr = TagMAP[tag_id].max_attribute;
Str tagstr = Strnew();
Strcat_char(tagstr, '<');
Strcat_charp(tagstr, TagMAP[tag_id].name);
for (i = 0; i < nattr; i++) {
if (tag->attrid[i] != ATTR_UNKNOWN) {
Strcat_char(tagstr, ' ');
Strcat_charp(tagstr, AttrMAP[tag->attrid[i]].name);
if (tag->value[i])
Strcat(tagstr, Sprintf("=\"%s\"", html_quote(tag->value[i])));
}
}
Strcat_char(tagstr, '>');
return tagstr;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5420_1 |
crossvul-cpp_data_good_5876_0 | /*
* linux/mm/filemap.c
*
* Copyright (C) 1994-1999 Linus Torvalds
*/
/*
* This file handles the generic file mmap semantics used by
* most "normal" filesystems (but you don't /have/ to use this:
* the NFS filesystem used to do this differently, for example)
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/compiler.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/aio.h>
#include <linux/capability.h>
#include <linux/kernel_stat.h>
#include <linux/mm.h>
#include <linux/swap.h>
#include <linux/mman.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/uio.h>
#include <linux/hash.h>
#include <linux/writeback.h>
#include <linux/backing-dev.h>
#include <linux/pagevec.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/cpuset.h>
#include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
#include "internal.h"
/*
* FIXME: remove all knowledge of the buffer layer from the core VM
*/
#include <linux/buffer_head.h> /* for generic_osync_inode */
#include <asm/mman.h>
static ssize_t
generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
loff_t offset, unsigned long nr_segs);
/*
* Shared mappings implemented 30.11.1994. It's not fully working yet,
* though.
*
* Shared mappings now work. 15.8.1995 Bruno.
*
* finished 'unifying' the page and buffer cache and SMP-threaded the
* page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
*
* SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
*/
/*
* Lock ordering:
*
* ->i_mmap_lock (vmtruncate)
* ->private_lock (__free_pte->__set_page_dirty_buffers)
* ->swap_lock (exclusive_swap_page, others)
* ->mapping->tree_lock
* ->zone.lock
*
* ->i_mutex
* ->i_mmap_lock (truncate->unmap_mapping_range)
*
* ->mmap_sem
* ->i_mmap_lock
* ->page_table_lock or pte_lock (various, mainly in memory.c)
* ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
*
* ->mmap_sem
* ->lock_page (access_process_vm)
*
* ->i_mutex (generic_file_buffered_write)
* ->mmap_sem (fault_in_pages_readable->do_page_fault)
*
* ->i_mutex
* ->i_alloc_sem (various)
*
* ->inode_lock
* ->sb_lock (fs/fs-writeback.c)
* ->mapping->tree_lock (__sync_single_inode)
*
* ->i_mmap_lock
* ->anon_vma.lock (vma_adjust)
*
* ->anon_vma.lock
* ->page_table_lock or pte_lock (anon_vma_prepare and various)
*
* ->page_table_lock or pte_lock
* ->swap_lock (try_to_unmap_one)
* ->private_lock (try_to_unmap_one)
* ->tree_lock (try_to_unmap_one)
* ->zone.lru_lock (follow_page->mark_page_accessed)
* ->zone.lru_lock (check_pte_range->isolate_lru_page)
* ->private_lock (page_remove_rmap->set_page_dirty)
* ->tree_lock (page_remove_rmap->set_page_dirty)
* ->inode_lock (page_remove_rmap->set_page_dirty)
* ->inode_lock (zap_pte_range->set_page_dirty)
* ->private_lock (zap_pte_range->__set_page_dirty_buffers)
*
* ->task->proc_lock
* ->dcache_lock (proc_pid_lookup)
*/
/*
* Remove a page from the page cache and free it. Caller has to make
* sure the page is locked and that nobody else uses it - or that usage
* is safe. The caller must hold a write_lock on the mapping's tree_lock.
*/
void __remove_from_page_cache(struct page *page)
{
struct address_space *mapping = page->mapping;
radix_tree_delete(&mapping->page_tree, page->index);
page->mapping = NULL;
mapping->nrpages--;
__dec_zone_page_state(page, NR_FILE_PAGES);
BUG_ON(page_mapped(page));
/*
* Some filesystems seem to re-dirty the page even after
* the VM has canceled the dirty bit (eg ext3 journaling).
*
* Fix it up by doing a final dirty accounting check after
* having removed the page entirely.
*/
if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
dec_zone_page_state(page, NR_FILE_DIRTY);
dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
}
}
void remove_from_page_cache(struct page *page)
{
struct address_space *mapping = page->mapping;
BUG_ON(!PageLocked(page));
write_lock_irq(&mapping->tree_lock);
__remove_from_page_cache(page);
write_unlock_irq(&mapping->tree_lock);
}
static int sync_page(void *word)
{
struct address_space *mapping;
struct page *page;
page = container_of((unsigned long *)word, struct page, flags);
/*
* page_mapping() is being called without PG_locked held.
* Some knowledge of the state and use of the page is used to
* reduce the requirements down to a memory barrier.
* The danger here is of a stale page_mapping() return value
* indicating a struct address_space different from the one it's
* associated with when it is associated with one.
* After smp_mb(), it's either the correct page_mapping() for
* the page, or an old page_mapping() and the page's own
* page_mapping() has gone NULL.
* The ->sync_page() address_space operation must tolerate
* page_mapping() going NULL. By an amazing coincidence,
* this comes about because none of the users of the page
* in the ->sync_page() methods make essential use of the
* page_mapping(), merely passing the page down to the backing
* device's unplug functions when it's non-NULL, which in turn
* ignore it for all cases but swap, where only page_private(page) is
* of interest. When page_mapping() does go NULL, the entire
* call stack gracefully ignores the page and returns.
* -- wli
*/
smp_mb();
mapping = page_mapping(page);
if (mapping && mapping->a_ops && mapping->a_ops->sync_page)
mapping->a_ops->sync_page(page);
io_schedule();
return 0;
}
static int sync_page_killable(void *word)
{
sync_page(word);
return fatal_signal_pending(current) ? -EINTR : 0;
}
/**
* __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
* @mapping: address space structure to write
* @start: offset in bytes where the range starts
* @end: offset in bytes where the range ends (inclusive)
* @sync_mode: enable synchronous operation
*
* Start writeback against all of a mapping's dirty pages that lie
* within the byte offsets <start, end> inclusive.
*
* If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
* opposed to a regular memory cleansing writeback. The difference between
* these two operations is that if a dirty page/buffer is encountered, it must
* be waited upon, and not just skipped over.
*/
int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
loff_t end, int sync_mode)
{
int ret;
struct writeback_control wbc = {
.sync_mode = sync_mode,
.nr_to_write = mapping->nrpages * 2,
.range_start = start,
.range_end = end,
};
if (!mapping_cap_writeback_dirty(mapping))
return 0;
ret = do_writepages(mapping, &wbc);
return ret;
}
static inline int __filemap_fdatawrite(struct address_space *mapping,
int sync_mode)
{
return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
}
int filemap_fdatawrite(struct address_space *mapping)
{
return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
}
EXPORT_SYMBOL(filemap_fdatawrite);
static int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
loff_t end)
{
return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
}
/**
* filemap_flush - mostly a non-blocking flush
* @mapping: target address_space
*
* This is a mostly non-blocking flush. Not suitable for data-integrity
* purposes - I/O may not be started against all dirty pages.
*/
int filemap_flush(struct address_space *mapping)
{
return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
}
EXPORT_SYMBOL(filemap_flush);
/**
* wait_on_page_writeback_range - wait for writeback to complete
* @mapping: target address_space
* @start: beginning page index
* @end: ending page index
*
* Wait for writeback to complete against pages indexed by start->end
* inclusive
*/
int wait_on_page_writeback_range(struct address_space *mapping,
pgoff_t start, pgoff_t end)
{
struct pagevec pvec;
int nr_pages;
int ret = 0;
pgoff_t index;
if (end < start)
return 0;
pagevec_init(&pvec, 0);
index = start;
while ((index <= end) &&
(nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
PAGECACHE_TAG_WRITEBACK,
min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
unsigned i;
for (i = 0; i < nr_pages; i++) {
struct page *page = pvec.pages[i];
/* until radix tree lookup accepts end_index */
if (page->index > end)
continue;
wait_on_page_writeback(page);
if (PageError(page))
ret = -EIO;
}
pagevec_release(&pvec);
cond_resched();
}
/* Check for outstanding write errors */
if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
ret = -ENOSPC;
if (test_and_clear_bit(AS_EIO, &mapping->flags))
ret = -EIO;
return ret;
}
/**
* sync_page_range - write and wait on all pages in the passed range
* @inode: target inode
* @mapping: target address_space
* @pos: beginning offset in pages to write
* @count: number of bytes to write
*
* Write and wait upon all the pages in the passed range. This is a "data
* integrity" operation. It waits upon in-flight writeout before starting and
* waiting upon new writeout. If there was an IO error, return it.
*
* We need to re-take i_mutex during the generic_osync_inode list walk because
* it is otherwise livelockable.
*/
int sync_page_range(struct inode *inode, struct address_space *mapping,
loff_t pos, loff_t count)
{
pgoff_t start = pos >> PAGE_CACHE_SHIFT;
pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
int ret;
if (!mapping_cap_writeback_dirty(mapping) || !count)
return 0;
ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
if (ret == 0) {
mutex_lock(&inode->i_mutex);
ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
mutex_unlock(&inode->i_mutex);
}
if (ret == 0)
ret = wait_on_page_writeback_range(mapping, start, end);
return ret;
}
EXPORT_SYMBOL(sync_page_range);
/**
* sync_page_range_nolock
* @inode: target inode
* @mapping: target address_space
* @pos: beginning offset in pages to write
* @count: number of bytes to write
*
* Note: Holding i_mutex across sync_page_range_nolock() is not a good idea
* as it forces O_SYNC writers to different parts of the same file
* to be serialised right until io completion.
*/
int sync_page_range_nolock(struct inode *inode, struct address_space *mapping,
loff_t pos, loff_t count)
{
pgoff_t start = pos >> PAGE_CACHE_SHIFT;
pgoff_t end = (pos + count - 1) >> PAGE_CACHE_SHIFT;
int ret;
if (!mapping_cap_writeback_dirty(mapping) || !count)
return 0;
ret = filemap_fdatawrite_range(mapping, pos, pos + count - 1);
if (ret == 0)
ret = generic_osync_inode(inode, mapping, OSYNC_METADATA);
if (ret == 0)
ret = wait_on_page_writeback_range(mapping, start, end);
return ret;
}
EXPORT_SYMBOL(sync_page_range_nolock);
/**
* filemap_fdatawait - wait for all under-writeback pages to complete
* @mapping: address space structure to wait for
*
* Walk the list of under-writeback pages of the given address space
* and wait for all of them.
*/
int filemap_fdatawait(struct address_space *mapping)
{
loff_t i_size = i_size_read(mapping->host);
if (i_size == 0)
return 0;
return wait_on_page_writeback_range(mapping, 0,
(i_size - 1) >> PAGE_CACHE_SHIFT);
}
EXPORT_SYMBOL(filemap_fdatawait);
int filemap_write_and_wait(struct address_space *mapping)
{
int err = 0;
if (mapping->nrpages) {
err = filemap_fdatawrite(mapping);
/*
* Even if the above returned error, the pages may be
* written partially (e.g. -ENOSPC), so we wait for it.
* But the -EIO is special case, it may indicate the worst
* thing (e.g. bug) happened, so we avoid waiting for it.
*/
if (err != -EIO) {
int err2 = filemap_fdatawait(mapping);
if (!err)
err = err2;
}
}
return err;
}
EXPORT_SYMBOL(filemap_write_and_wait);
/**
* filemap_write_and_wait_range - write out & wait on a file range
* @mapping: the address_space for the pages
* @lstart: offset in bytes where the range starts
* @lend: offset in bytes where the range ends (inclusive)
*
* Write out and wait upon file offsets lstart->lend, inclusive.
*
* Note that `lend' is inclusive (describes the last byte to be written) so
* that this function can be used to write to the very end-of-file (end = -1).
*/
int filemap_write_and_wait_range(struct address_space *mapping,
loff_t lstart, loff_t lend)
{
int err = 0;
if (mapping->nrpages) {
err = __filemap_fdatawrite_range(mapping, lstart, lend,
WB_SYNC_ALL);
/* See comment of filemap_write_and_wait() */
if (err != -EIO) {
int err2 = wait_on_page_writeback_range(mapping,
lstart >> PAGE_CACHE_SHIFT,
lend >> PAGE_CACHE_SHIFT);
if (!err)
err = err2;
}
}
return err;
}
/**
* add_to_page_cache - add newly allocated pagecache pages
* @page: page to add
* @mapping: the page's address_space
* @offset: page index
* @gfp_mask: page allocation mode
*
* This function is used to add newly allocated pagecache pages;
* the page is new, so we can just run SetPageLocked() against it.
* The other page state flags were set by rmqueue().
*
* This function does not add the page to the LRU. The caller must do that.
*/
int add_to_page_cache(struct page *page, struct address_space *mapping,
pgoff_t offset, gfp_t gfp_mask)
{
int error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
if (error == 0) {
write_lock_irq(&mapping->tree_lock);
error = radix_tree_insert(&mapping->page_tree, offset, page);
if (!error) {
page_cache_get(page);
SetPageLocked(page);
page->mapping = mapping;
page->index = offset;
mapping->nrpages++;
__inc_zone_page_state(page, NR_FILE_PAGES);
}
write_unlock_irq(&mapping->tree_lock);
radix_tree_preload_end();
}
return error;
}
EXPORT_SYMBOL(add_to_page_cache);
int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
pgoff_t offset, gfp_t gfp_mask)
{
int ret = add_to_page_cache(page, mapping, offset, gfp_mask);
if (ret == 0)
lru_cache_add(page);
return ret;
}
#ifdef CONFIG_NUMA
struct page *__page_cache_alloc(gfp_t gfp)
{
if (cpuset_do_page_mem_spread()) {
int n = cpuset_mem_spread_node();
return alloc_pages_node(n, gfp, 0);
}
return alloc_pages(gfp, 0);
}
EXPORT_SYMBOL(__page_cache_alloc);
#endif
static int __sleep_on_page_lock(void *word)
{
io_schedule();
return 0;
}
/*
* In order to wait for pages to become available there must be
* waitqueues associated with pages. By using a hash table of
* waitqueues where the bucket discipline is to maintain all
* waiters on the same queue and wake all when any of the pages
* become available, and for the woken contexts to check to be
* sure the appropriate page became available, this saves space
* at a cost of "thundering herd" phenomena during rare hash
* collisions.
*/
static wait_queue_head_t *page_waitqueue(struct page *page)
{
const struct zone *zone = page_zone(page);
return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
}
static inline void wake_up_page(struct page *page, int bit)
{
__wake_up_bit(page_waitqueue(page), &page->flags, bit);
}
void fastcall wait_on_page_bit(struct page *page, int bit_nr)
{
DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
if (test_bit(bit_nr, &page->flags))
__wait_on_bit(page_waitqueue(page), &wait, sync_page,
TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(wait_on_page_bit);
/**
* unlock_page - unlock a locked page
* @page: the page
*
* Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
* Also wakes sleepers in wait_on_page_writeback() because the wakeup
* mechananism between PageLocked pages and PageWriteback pages is shared.
* But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
*
* The first mb is necessary to safely close the critical section opened by the
* TestSetPageLocked(), the second mb is necessary to enforce ordering between
* the clear_bit and the read of the waitqueue (to avoid SMP races with a
* parallel wait_on_page_locked()).
*/
void fastcall unlock_page(struct page *page)
{
smp_mb__before_clear_bit();
if (!TestClearPageLocked(page))
BUG();
smp_mb__after_clear_bit();
wake_up_page(page, PG_locked);
}
EXPORT_SYMBOL(unlock_page);
/**
* end_page_writeback - end writeback against a page
* @page: the page
*/
void end_page_writeback(struct page *page)
{
if (!TestClearPageReclaim(page) || rotate_reclaimable_page(page)) {
if (!test_clear_page_writeback(page))
BUG();
}
smp_mb__after_clear_bit();
wake_up_page(page, PG_writeback);
}
EXPORT_SYMBOL(end_page_writeback);
/**
* __lock_page - get a lock on the page, assuming we need to sleep to get it
* @page: the page to lock
*
* Ugly. Running sync_page() in state TASK_UNINTERRUPTIBLE is scary. If some
* random driver's requestfn sets TASK_RUNNING, we could busywait. However
* chances are that on the second loop, the block layer's plug list is empty,
* so sync_page() will then return in state TASK_UNINTERRUPTIBLE.
*/
void fastcall __lock_page(struct page *page)
{
DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
__wait_on_bit_lock(page_waitqueue(page), &wait, sync_page,
TASK_UNINTERRUPTIBLE);
}
EXPORT_SYMBOL(__lock_page);
int fastcall __lock_page_killable(struct page *page)
{
DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
return __wait_on_bit_lock(page_waitqueue(page), &wait,
sync_page_killable, TASK_KILLABLE);
}
/*
* Variant of lock_page that does not require the caller to hold a reference
* on the page's mapping.
*/
void fastcall __lock_page_nosync(struct page *page)
{
DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
__wait_on_bit_lock(page_waitqueue(page), &wait, __sleep_on_page_lock,
TASK_UNINTERRUPTIBLE);
}
/**
* find_get_page - find and get a page reference
* @mapping: the address_space to search
* @offset: the page index
*
* Is there a pagecache struct page at the given (mapping, offset) tuple?
* If yes, increment its refcount and return it; if no, return NULL.
*/
struct page * find_get_page(struct address_space *mapping, pgoff_t offset)
{
struct page *page;
read_lock_irq(&mapping->tree_lock);
page = radix_tree_lookup(&mapping->page_tree, offset);
if (page)
page_cache_get(page);
read_unlock_irq(&mapping->tree_lock);
return page;
}
EXPORT_SYMBOL(find_get_page);
/**
* find_lock_page - locate, pin and lock a pagecache page
* @mapping: the address_space to search
* @offset: the page index
*
* Locates the desired pagecache page, locks it, increments its reference
* count and returns its address.
*
* Returns zero if the page was not present. find_lock_page() may sleep.
*/
struct page *find_lock_page(struct address_space *mapping,
pgoff_t offset)
{
struct page *page;
repeat:
read_lock_irq(&mapping->tree_lock);
page = radix_tree_lookup(&mapping->page_tree, offset);
if (page) {
page_cache_get(page);
if (TestSetPageLocked(page)) {
read_unlock_irq(&mapping->tree_lock);
__lock_page(page);
/* Has the page been truncated while we slept? */
if (unlikely(page->mapping != mapping)) {
unlock_page(page);
page_cache_release(page);
goto repeat;
}
VM_BUG_ON(page->index != offset);
goto out;
}
}
read_unlock_irq(&mapping->tree_lock);
out:
return page;
}
EXPORT_SYMBOL(find_lock_page);
/**
* find_or_create_page - locate or add a pagecache page
* @mapping: the page's address_space
* @index: the page's index into the mapping
* @gfp_mask: page allocation mode
*
* Locates a page in the pagecache. If the page is not present, a new page
* is allocated using @gfp_mask and is added to the pagecache and to the VM's
* LRU list. The returned page is locked and has its reference count
* incremented.
*
* find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
* allocation!
*
* find_or_create_page() returns the desired page's address, or zero on
* memory exhaustion.
*/
struct page *find_or_create_page(struct address_space *mapping,
pgoff_t index, gfp_t gfp_mask)
{
struct page *page;
int err;
repeat:
page = find_lock_page(mapping, index);
if (!page) {
page = __page_cache_alloc(gfp_mask);
if (!page)
return NULL;
err = add_to_page_cache_lru(page, mapping, index, gfp_mask);
if (unlikely(err)) {
page_cache_release(page);
page = NULL;
if (err == -EEXIST)
goto repeat;
}
}
return page;
}
EXPORT_SYMBOL(find_or_create_page);
/**
* find_get_pages - gang pagecache lookup
* @mapping: The address_space to search
* @start: The starting page index
* @nr_pages: The maximum number of pages
* @pages: Where the resulting pages are placed
*
* find_get_pages() will search for and return a group of up to
* @nr_pages pages in the mapping. The pages are placed at @pages.
* find_get_pages() takes a reference against the returned pages.
*
* The search returns a group of mapping-contiguous pages with ascending
* indexes. There may be holes in the indices due to not-present pages.
*
* find_get_pages() returns the number of pages which were found.
*/
unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
unsigned int nr_pages, struct page **pages)
{
unsigned int i;
unsigned int ret;
read_lock_irq(&mapping->tree_lock);
ret = radix_tree_gang_lookup(&mapping->page_tree,
(void **)pages, start, nr_pages);
for (i = 0; i < ret; i++)
page_cache_get(pages[i]);
read_unlock_irq(&mapping->tree_lock);
return ret;
}
/**
* find_get_pages_contig - gang contiguous pagecache lookup
* @mapping: The address_space to search
* @index: The starting page index
* @nr_pages: The maximum number of pages
* @pages: Where the resulting pages are placed
*
* find_get_pages_contig() works exactly like find_get_pages(), except
* that the returned number of pages are guaranteed to be contiguous.
*
* find_get_pages_contig() returns the number of pages which were found.
*/
unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
unsigned int nr_pages, struct page **pages)
{
unsigned int i;
unsigned int ret;
read_lock_irq(&mapping->tree_lock);
ret = radix_tree_gang_lookup(&mapping->page_tree,
(void **)pages, index, nr_pages);
for (i = 0; i < ret; i++) {
if (pages[i]->mapping == NULL || pages[i]->index != index)
break;
page_cache_get(pages[i]);
index++;
}
read_unlock_irq(&mapping->tree_lock);
return i;
}
EXPORT_SYMBOL(find_get_pages_contig);
/**
* find_get_pages_tag - find and return pages that match @tag
* @mapping: the address_space to search
* @index: the starting page index
* @tag: the tag index
* @nr_pages: the maximum number of pages
* @pages: where the resulting pages are placed
*
* Like find_get_pages, except we only return pages which are tagged with
* @tag. We update @index to index the next page for the traversal.
*/
unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
int tag, unsigned int nr_pages, struct page **pages)
{
unsigned int i;
unsigned int ret;
read_lock_irq(&mapping->tree_lock);
ret = radix_tree_gang_lookup_tag(&mapping->page_tree,
(void **)pages, *index, nr_pages, tag);
for (i = 0; i < ret; i++)
page_cache_get(pages[i]);
if (ret)
*index = pages[ret - 1]->index + 1;
read_unlock_irq(&mapping->tree_lock);
return ret;
}
EXPORT_SYMBOL(find_get_pages_tag);
/**
* grab_cache_page_nowait - returns locked page at given index in given cache
* @mapping: target address_space
* @index: the page index
*
* Same as grab_cache_page(), but do not wait if the page is unavailable.
* This is intended for speculative data generators, where the data can
* be regenerated if the page couldn't be grabbed. This routine should
* be safe to call while holding the lock for another page.
*
* Clear __GFP_FS when allocating the page to avoid recursion into the fs
* and deadlock against the caller's locked page.
*/
struct page *
grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
{
struct page *page = find_get_page(mapping, index);
if (page) {
if (!TestSetPageLocked(page))
return page;
page_cache_release(page);
return NULL;
}
page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
if (page && add_to_page_cache_lru(page, mapping, index, GFP_KERNEL)) {
page_cache_release(page);
page = NULL;
}
return page;
}
EXPORT_SYMBOL(grab_cache_page_nowait);
/*
* CD/DVDs are error prone. When a medium error occurs, the driver may fail
* a _large_ part of the i/o request. Imagine the worst scenario:
*
* ---R__________________________________________B__________
* ^ reading here ^ bad block(assume 4k)
*
* read(R) => miss => readahead(R...B) => media error => frustrating retries
* => failing the whole request => read(R) => read(R+1) =>
* readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
* readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
* readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
*
* It is going insane. Fix it by quickly scaling down the readahead size.
*/
static void shrink_readahead_size_eio(struct file *filp,
struct file_ra_state *ra)
{
if (!ra->ra_pages)
return;
ra->ra_pages /= 4;
}
/**
* do_generic_mapping_read - generic file read routine
* @mapping: address_space to be read
* @ra: file's readahead state
* @filp: the file to read
* @ppos: current file position
* @desc: read_descriptor
* @actor: read method
*
* This is a generic file read routine, and uses the
* mapping->a_ops->readpage() function for the actual low-level stuff.
*
* This is really ugly. But the goto's actually try to clarify some
* of the logic when it comes to error handling etc.
*
* Note the struct file* is only passed for the use of readpage.
* It may be NULL.
*/
void do_generic_mapping_read(struct address_space *mapping,
struct file_ra_state *ra,
struct file *filp,
loff_t *ppos,
read_descriptor_t *desc,
read_actor_t actor)
{
struct inode *inode = mapping->host;
pgoff_t index;
pgoff_t last_index;
pgoff_t prev_index;
unsigned long offset; /* offset into pagecache page */
unsigned int prev_offset;
int error;
index = *ppos >> PAGE_CACHE_SHIFT;
prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
offset = *ppos & ~PAGE_CACHE_MASK;
for (;;) {
struct page *page;
pgoff_t end_index;
loff_t isize;
unsigned long nr, ret;
cond_resched();
find_page:
page = find_get_page(mapping, index);
if (!page) {
page_cache_sync_readahead(mapping,
ra, filp,
index, last_index - index);
page = find_get_page(mapping, index);
if (unlikely(page == NULL))
goto no_cached_page;
}
if (PageReadahead(page)) {
page_cache_async_readahead(mapping,
ra, filp, page,
index, last_index - index);
}
if (!PageUptodate(page))
goto page_not_up_to_date;
page_ok:
/*
* i_size must be checked after we know the page is Uptodate.
*
* Checking i_size after the check allows us to calculate
* the correct value for "nr", which means the zero-filled
* part of the page is not copied back to userspace (unless
* another truncate extends the file - this is desired though).
*/
isize = i_size_read(inode);
end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
if (unlikely(!isize || index > end_index)) {
page_cache_release(page);
goto out;
}
/* nr is the maximum number of bytes to copy from this page */
nr = PAGE_CACHE_SIZE;
if (index == end_index) {
nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
if (nr <= offset) {
page_cache_release(page);
goto out;
}
}
nr = nr - offset;
/* If users can be writing to this page using arbitrary
* virtual addresses, take care about potential aliasing
* before reading the page on the kernel side.
*/
if (mapping_writably_mapped(mapping))
flush_dcache_page(page);
/*
* When a sequential read accesses a page several times,
* only mark it as accessed the first time.
*/
if (prev_index != index || offset != prev_offset)
mark_page_accessed(page);
prev_index = index;
/*
* Ok, we have the page, and it's up-to-date, so
* now we can copy it to user space...
*
* The actor routine returns how many bytes were actually used..
* NOTE! This may not be the same as how much of a user buffer
* we filled up (we may be padding etc), so we can only update
* "pos" here (the actor routine has to update the user buffer
* pointers and the remaining count).
*/
ret = actor(desc, page, offset, nr);
offset += ret;
index += offset >> PAGE_CACHE_SHIFT;
offset &= ~PAGE_CACHE_MASK;
prev_offset = offset;
page_cache_release(page);
if (ret == nr && desc->count)
continue;
goto out;
page_not_up_to_date:
/* Get exclusive access to the page ... */
if (lock_page_killable(page))
goto readpage_eio;
/* Did it get truncated before we got the lock? */
if (!page->mapping) {
unlock_page(page);
page_cache_release(page);
continue;
}
/* Did somebody else fill it already? */
if (PageUptodate(page)) {
unlock_page(page);
goto page_ok;
}
readpage:
/* Start the actual read. The read will unlock the page. */
error = mapping->a_ops->readpage(filp, page);
if (unlikely(error)) {
if (error == AOP_TRUNCATED_PAGE) {
page_cache_release(page);
goto find_page;
}
goto readpage_error;
}
if (!PageUptodate(page)) {
if (lock_page_killable(page))
goto readpage_eio;
if (!PageUptodate(page)) {
if (page->mapping == NULL) {
/*
* invalidate_inode_pages got it
*/
unlock_page(page);
page_cache_release(page);
goto find_page;
}
unlock_page(page);
shrink_readahead_size_eio(filp, ra);
goto readpage_eio;
}
unlock_page(page);
}
goto page_ok;
readpage_eio:
error = -EIO;
readpage_error:
/* UHHUH! A synchronous read error occurred. Report it */
desc->error = error;
page_cache_release(page);
goto out;
no_cached_page:
/*
* Ok, it wasn't cached, so we need to create a new
* page..
*/
page = page_cache_alloc_cold(mapping);
if (!page) {
desc->error = -ENOMEM;
goto out;
}
error = add_to_page_cache_lru(page, mapping,
index, GFP_KERNEL);
if (error) {
page_cache_release(page);
if (error == -EEXIST)
goto find_page;
desc->error = error;
goto out;
}
goto readpage;
}
out:
ra->prev_pos = prev_index;
ra->prev_pos <<= PAGE_CACHE_SHIFT;
ra->prev_pos |= prev_offset;
*ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
if (filp)
file_accessed(filp);
}
EXPORT_SYMBOL(do_generic_mapping_read);
int file_read_actor(read_descriptor_t *desc, struct page *page,
unsigned long offset, unsigned long size)
{
char *kaddr;
unsigned long left, count = desc->count;
if (size > count)
size = count;
/*
* Faults on the destination of a read are common, so do it before
* taking the kmap.
*/
if (!fault_in_pages_writeable(desc->arg.buf, size)) {
kaddr = kmap_atomic(page, KM_USER0);
left = __copy_to_user_inatomic(desc->arg.buf,
kaddr + offset, size);
kunmap_atomic(kaddr, KM_USER0);
if (left == 0)
goto success;
}
/* Do it the slow way */
kaddr = kmap(page);
left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
kunmap(page);
if (left) {
size -= left;
desc->error = -EFAULT;
}
success:
desc->count = count - size;
desc->written += size;
desc->arg.buf += size;
return size;
}
/*
* Performs necessary checks before doing a write
* @iov: io vector request
* @nr_segs: number of segments in the iovec
* @count: number of bytes to write
* @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
*
* Adjust number of segments and amount of bytes to write (nr_segs should be
* properly initialized first). Returns appropriate error code that caller
* should return or zero in case that write should be allowed.
*/
int generic_segment_checks(const struct iovec *iov,
unsigned long *nr_segs, size_t *count, int access_flags)
{
unsigned long seg;
size_t cnt = 0;
for (seg = 0; seg < *nr_segs; seg++) {
const struct iovec *iv = &iov[seg];
/*
* If any segment has a negative length, or the cumulative
* length ever wraps negative then return -EINVAL.
*/
cnt += iv->iov_len;
if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
return -EINVAL;
if (access_ok(access_flags, iv->iov_base, iv->iov_len))
continue;
if (seg == 0)
return -EFAULT;
*nr_segs = seg;
cnt -= iv->iov_len; /* This segment is no good */
break;
}
*count = cnt;
return 0;
}
EXPORT_SYMBOL(generic_segment_checks);
/**
* generic_file_aio_read - generic filesystem read routine
* @iocb: kernel I/O control block
* @iov: io vector request
* @nr_segs: number of segments in the iovec
* @pos: current file position
*
* This is the "read()" routine for all filesystems
* that can use the page cache directly.
*/
ssize_t
generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct file *filp = iocb->ki_filp;
ssize_t retval;
unsigned long seg;
size_t count;
loff_t *ppos = &iocb->ki_pos;
count = 0;
retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
if (retval)
return retval;
/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
if (filp->f_flags & O_DIRECT) {
loff_t size;
struct address_space *mapping;
struct inode *inode;
mapping = filp->f_mapping;
inode = mapping->host;
retval = 0;
if (!count)
goto out; /* skip atime */
size = i_size_read(inode);
if (pos < size) {
retval = generic_file_direct_IO(READ, iocb,
iov, pos, nr_segs);
if (retval > 0)
*ppos = pos + retval;
}
if (likely(retval != 0)) {
file_accessed(filp);
goto out;
}
}
retval = 0;
if (count) {
for (seg = 0; seg < nr_segs; seg++) {
read_descriptor_t desc;
desc.written = 0;
desc.arg.buf = iov[seg].iov_base;
desc.count = iov[seg].iov_len;
if (desc.count == 0)
continue;
desc.error = 0;
do_generic_file_read(filp,ppos,&desc,file_read_actor);
retval += desc.written;
if (desc.error) {
retval = retval ?: desc.error;
break;
}
if (desc.count > 0)
break;
}
}
out:
return retval;
}
EXPORT_SYMBOL(generic_file_aio_read);
static ssize_t
do_readahead(struct address_space *mapping, struct file *filp,
pgoff_t index, unsigned long nr)
{
if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
return -EINVAL;
force_page_cache_readahead(mapping, filp, index,
max_sane_readahead(nr));
return 0;
}
asmlinkage ssize_t sys_readahead(int fd, loff_t offset, size_t count)
{
ssize_t ret;
struct file *file;
ret = -EBADF;
file = fget(fd);
if (file) {
if (file->f_mode & FMODE_READ) {
struct address_space *mapping = file->f_mapping;
pgoff_t start = offset >> PAGE_CACHE_SHIFT;
pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
unsigned long len = end - start + 1;
ret = do_readahead(mapping, file, start, len);
}
fput(file);
}
return ret;
}
#ifdef CONFIG_MMU
/**
* page_cache_read - adds requested page to the page cache if not already there
* @file: file to read
* @offset: page index
*
* This adds the requested page to the page cache if it isn't already there,
* and schedules an I/O to read in its contents from disk.
*/
static int fastcall page_cache_read(struct file * file, pgoff_t offset)
{
struct address_space *mapping = file->f_mapping;
struct page *page;
int ret;
do {
page = page_cache_alloc_cold(mapping);
if (!page)
return -ENOMEM;
ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
if (ret == 0)
ret = mapping->a_ops->readpage(file, page);
else if (ret == -EEXIST)
ret = 0; /* losing race to add is OK */
page_cache_release(page);
} while (ret == AOP_TRUNCATED_PAGE);
return ret;
}
#define MMAP_LOTSAMISS (100)
/**
* filemap_fault - read in file data for page fault handling
* @vma: vma in which the fault was taken
* @vmf: struct vm_fault containing details of the fault
*
* filemap_fault() is invoked via the vma operations vector for a
* mapped memory region to read in file data during a page fault.
*
* The goto's are kind of ugly, but this streamlines the normal case of having
* it in the page cache, and handles the special cases reasonably without
* having a lot of duplicated code.
*/
int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
int error;
struct file *file = vma->vm_file;
struct address_space *mapping = file->f_mapping;
struct file_ra_state *ra = &file->f_ra;
struct inode *inode = mapping->host;
struct page *page;
unsigned long size;
int did_readaround = 0;
int ret = 0;
size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
if (vmf->pgoff >= size)
return VM_FAULT_SIGBUS;
/* If we don't want any read-ahead, don't bother */
if (VM_RandomReadHint(vma))
goto no_cached_page;
/*
* Do we have something in the page cache already?
*/
retry_find:
page = find_lock_page(mapping, vmf->pgoff);
/*
* For sequential accesses, we use the generic readahead logic.
*/
if (VM_SequentialReadHint(vma)) {
if (!page) {
page_cache_sync_readahead(mapping, ra, file,
vmf->pgoff, 1);
page = find_lock_page(mapping, vmf->pgoff);
if (!page)
goto no_cached_page;
}
if (PageReadahead(page)) {
page_cache_async_readahead(mapping, ra, file, page,
vmf->pgoff, 1);
}
}
if (!page) {
unsigned long ra_pages;
ra->mmap_miss++;
/*
* Do we miss much more than hit in this file? If so,
* stop bothering with read-ahead. It will only hurt.
*/
if (ra->mmap_miss > MMAP_LOTSAMISS)
goto no_cached_page;
/*
* To keep the pgmajfault counter straight, we need to
* check did_readaround, as this is an inner loop.
*/
if (!did_readaround) {
ret = VM_FAULT_MAJOR;
count_vm_event(PGMAJFAULT);
}
did_readaround = 1;
ra_pages = max_sane_readahead(file->f_ra.ra_pages);
if (ra_pages) {
pgoff_t start = 0;
if (vmf->pgoff > ra_pages / 2)
start = vmf->pgoff - ra_pages / 2;
do_page_cache_readahead(mapping, file, start, ra_pages);
}
page = find_lock_page(mapping, vmf->pgoff);
if (!page)
goto no_cached_page;
}
if (!did_readaround)
ra->mmap_miss--;
/*
* We have a locked page in the page cache, now we need to check
* that it's up-to-date. If not, it is going to be due to an error.
*/
if (unlikely(!PageUptodate(page)))
goto page_not_uptodate;
/* Must recheck i_size under page lock */
size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
if (unlikely(vmf->pgoff >= size)) {
unlock_page(page);
page_cache_release(page);
return VM_FAULT_SIGBUS;
}
/*
* Found the page and have a reference on it.
*/
mark_page_accessed(page);
ra->prev_pos = (loff_t)page->index << PAGE_CACHE_SHIFT;
vmf->page = page;
return ret | VM_FAULT_LOCKED;
no_cached_page:
/*
* We're only likely to ever get here if MADV_RANDOM is in
* effect.
*/
error = page_cache_read(file, vmf->pgoff);
/*
* The page we want has now been added to the page cache.
* In the unlikely event that someone removed it in the
* meantime, we'll just come back here and read it again.
*/
if (error >= 0)
goto retry_find;
/*
* An error return from page_cache_read can result if the
* system is low on memory, or a problem occurs while trying
* to schedule I/O.
*/
if (error == -ENOMEM)
return VM_FAULT_OOM;
return VM_FAULT_SIGBUS;
page_not_uptodate:
/* IO error path */
if (!did_readaround) {
ret = VM_FAULT_MAJOR;
count_vm_event(PGMAJFAULT);
}
/*
* Umm, take care of errors if the page isn't up-to-date.
* Try to re-read it _once_. We do this synchronously,
* because there really aren't any performance issues here
* and we need to check for errors.
*/
ClearPageError(page);
error = mapping->a_ops->readpage(file, page);
page_cache_release(page);
if (!error || error == AOP_TRUNCATED_PAGE)
goto retry_find;
/* Things didn't work out. Return zero to tell the mm layer so. */
shrink_readahead_size_eio(file, ra);
return VM_FAULT_SIGBUS;
}
EXPORT_SYMBOL(filemap_fault);
struct vm_operations_struct generic_file_vm_ops = {
.fault = filemap_fault,
};
/* This is used for a general mmap of a disk file */
int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
{
struct address_space *mapping = file->f_mapping;
if (!mapping->a_ops->readpage)
return -ENOEXEC;
file_accessed(file);
vma->vm_ops = &generic_file_vm_ops;
vma->vm_flags |= VM_CAN_NONLINEAR;
return 0;
}
/*
* This is for filesystems which do not implement ->writepage.
*/
int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
{
if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
return -EINVAL;
return generic_file_mmap(file, vma);
}
#else
int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
{
return -ENOSYS;
}
int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
{
return -ENOSYS;
}
#endif /* CONFIG_MMU */
EXPORT_SYMBOL(generic_file_mmap);
EXPORT_SYMBOL(generic_file_readonly_mmap);
static struct page *__read_cache_page(struct address_space *mapping,
pgoff_t index,
int (*filler)(void *,struct page*),
void *data)
{
struct page *page;
int err;
repeat:
page = find_get_page(mapping, index);
if (!page) {
page = page_cache_alloc_cold(mapping);
if (!page)
return ERR_PTR(-ENOMEM);
err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
if (unlikely(err)) {
page_cache_release(page);
if (err == -EEXIST)
goto repeat;
/* Presumably ENOMEM for radix tree node */
return ERR_PTR(err);
}
err = filler(data, page);
if (err < 0) {
page_cache_release(page);
page = ERR_PTR(err);
}
}
return page;
}
/*
* Same as read_cache_page, but don't wait for page to become unlocked
* after submitting it to the filler.
*/
struct page *read_cache_page_async(struct address_space *mapping,
pgoff_t index,
int (*filler)(void *,struct page*),
void *data)
{
struct page *page;
int err;
retry:
page = __read_cache_page(mapping, index, filler, data);
if (IS_ERR(page))
return page;
if (PageUptodate(page))
goto out;
lock_page(page);
if (!page->mapping) {
unlock_page(page);
page_cache_release(page);
goto retry;
}
if (PageUptodate(page)) {
unlock_page(page);
goto out;
}
err = filler(data, page);
if (err < 0) {
page_cache_release(page);
return ERR_PTR(err);
}
out:
mark_page_accessed(page);
return page;
}
EXPORT_SYMBOL(read_cache_page_async);
/**
* read_cache_page - read into page cache, fill it if needed
* @mapping: the page's address_space
* @index: the page index
* @filler: function to perform the read
* @data: destination for read data
*
* Read into the page cache. If a page already exists, and PageUptodate() is
* not set, try to fill the page then wait for it to become unlocked.
*
* If the page does not get brought uptodate, return -EIO.
*/
struct page *read_cache_page(struct address_space *mapping,
pgoff_t index,
int (*filler)(void *,struct page*),
void *data)
{
struct page *page;
page = read_cache_page_async(mapping, index, filler, data);
if (IS_ERR(page))
goto out;
wait_on_page_locked(page);
if (!PageUptodate(page)) {
page_cache_release(page);
page = ERR_PTR(-EIO);
}
out:
return page;
}
EXPORT_SYMBOL(read_cache_page);
/*
* The logic we want is
*
* if suid or (sgid and xgrp)
* remove privs
*/
int should_remove_suid(struct dentry *dentry)
{
mode_t mode = dentry->d_inode->i_mode;
int kill = 0;
/* suid always must be killed */
if (unlikely(mode & S_ISUID))
kill = ATTR_KILL_SUID;
/*
* sgid without any exec bits is just a mandatory locking mark; leave
* it alone. If some exec bits are set, it's a real sgid; kill it.
*/
if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
kill |= ATTR_KILL_SGID;
if (unlikely(kill && !capable(CAP_FSETID)))
return kill;
return 0;
}
EXPORT_SYMBOL(should_remove_suid);
int __remove_suid(struct dentry *dentry, int kill)
{
struct iattr newattrs;
newattrs.ia_valid = ATTR_FORCE | kill;
return notify_change(dentry, &newattrs);
}
int remove_suid(struct dentry *dentry)
{
int killsuid = should_remove_suid(dentry);
int killpriv = security_inode_need_killpriv(dentry);
int error = 0;
if (killpriv < 0)
return killpriv;
if (killpriv)
error = security_inode_killpriv(dentry);
if (!error && killsuid)
error = __remove_suid(dentry, killsuid);
return error;
}
EXPORT_SYMBOL(remove_suid);
static size_t __iovec_copy_from_user_inatomic(char *vaddr,
const struct iovec *iov, size_t base, size_t bytes)
{
size_t copied = 0, left = 0;
while (bytes) {
char __user *buf = iov->iov_base + base;
int copy = min(bytes, iov->iov_len - base);
base = 0;
left = __copy_from_user_inatomic_nocache(vaddr, buf, copy);
copied += copy;
bytes -= copy;
vaddr += copy;
iov++;
if (unlikely(left))
break;
}
return copied - left;
}
/*
* Copy as much as we can into the page and return the number of bytes which
* were sucessfully copied. If a fault is encountered then return the number of
* bytes which were copied.
*/
size_t iov_iter_copy_from_user_atomic(struct page *page,
struct iov_iter *i, unsigned long offset, size_t bytes)
{
char *kaddr;
size_t copied;
BUG_ON(!in_atomic());
kaddr = kmap_atomic(page, KM_USER0);
if (likely(i->nr_segs == 1)) {
int left;
char __user *buf = i->iov->iov_base + i->iov_offset;
left = __copy_from_user_inatomic_nocache(kaddr + offset,
buf, bytes);
copied = bytes - left;
} else {
copied = __iovec_copy_from_user_inatomic(kaddr + offset,
i->iov, i->iov_offset, bytes);
}
kunmap_atomic(kaddr, KM_USER0);
return copied;
}
EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
/*
* This has the same sideeffects and return value as
* iov_iter_copy_from_user_atomic().
* The difference is that it attempts to resolve faults.
* Page must not be locked.
*/
size_t iov_iter_copy_from_user(struct page *page,
struct iov_iter *i, unsigned long offset, size_t bytes)
{
char *kaddr;
size_t copied;
kaddr = kmap(page);
if (likely(i->nr_segs == 1)) {
int left;
char __user *buf = i->iov->iov_base + i->iov_offset;
left = __copy_from_user_nocache(kaddr + offset, buf, bytes);
copied = bytes - left;
} else {
copied = __iovec_copy_from_user_inatomic(kaddr + offset,
i->iov, i->iov_offset, bytes);
}
kunmap(page);
return copied;
}
EXPORT_SYMBOL(iov_iter_copy_from_user);
static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes)
{
if (likely(i->nr_segs == 1)) {
i->iov_offset += bytes;
} else {
const struct iovec *iov = i->iov;
size_t base = i->iov_offset;
/*
* The !iov->iov_len check ensures we skip over unlikely
* zero-length segments.
*/
while (bytes || !iov->iov_len) {
int copy = min(bytes, iov->iov_len - base);
bytes -= copy;
base += copy;
if (iov->iov_len == base) {
iov++;
base = 0;
}
}
i->iov = iov;
i->iov_offset = base;
}
}
void iov_iter_advance(struct iov_iter *i, size_t bytes)
{
BUG_ON(i->count < bytes);
__iov_iter_advance_iov(i, bytes);
i->count -= bytes;
}
EXPORT_SYMBOL(iov_iter_advance);
/*
* Fault in the first iovec of the given iov_iter, to a maximum length
* of bytes. Returns 0 on success, or non-zero if the memory could not be
* accessed (ie. because it is an invalid address).
*
* writev-intensive code may want this to prefault several iovecs -- that
* would be possible (callers must not rely on the fact that _only_ the
* first iovec will be faulted with the current implementation).
*/
int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
{
char __user *buf = i->iov->iov_base + i->iov_offset;
bytes = min(bytes, i->iov->iov_len - i->iov_offset);
return fault_in_pages_readable(buf, bytes);
}
EXPORT_SYMBOL(iov_iter_fault_in_readable);
/*
* Return the count of just the current iov_iter segment.
*/
size_t iov_iter_single_seg_count(struct iov_iter *i)
{
const struct iovec *iov = i->iov;
if (i->nr_segs == 1)
return i->count;
else
return min(i->count, iov->iov_len - i->iov_offset);
}
EXPORT_SYMBOL(iov_iter_single_seg_count);
/*
* Performs necessary checks before doing a write
*
* Can adjust writing position or amount of bytes to write.
* Returns appropriate error code that caller should return or
* zero in case that write should be allowed.
*/
inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
{
struct inode *inode = file->f_mapping->host;
unsigned long limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
if (unlikely(*pos < 0))
return -EINVAL;
if (!isblk) {
/* FIXME: this is for backwards compatibility with 2.4 */
if (file->f_flags & O_APPEND)
*pos = i_size_read(inode);
if (limit != RLIM_INFINITY) {
if (*pos >= limit) {
send_sig(SIGXFSZ, current, 0);
return -EFBIG;
}
if (*count > limit - (typeof(limit))*pos) {
*count = limit - (typeof(limit))*pos;
}
}
}
/*
* LFS rule
*/
if (unlikely(*pos + *count > MAX_NON_LFS &&
!(file->f_flags & O_LARGEFILE))) {
if (*pos >= MAX_NON_LFS) {
return -EFBIG;
}
if (*count > MAX_NON_LFS - (unsigned long)*pos) {
*count = MAX_NON_LFS - (unsigned long)*pos;
}
}
/*
* Are we about to exceed the fs block limit ?
*
* If we have written data it becomes a short write. If we have
* exceeded without writing data we send a signal and return EFBIG.
* Linus frestrict idea will clean these up nicely..
*/
if (likely(!isblk)) {
if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
if (*count || *pos > inode->i_sb->s_maxbytes) {
return -EFBIG;
}
/* zero-length writes at ->s_maxbytes are OK */
}
if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
*count = inode->i_sb->s_maxbytes - *pos;
} else {
#ifdef CONFIG_BLOCK
loff_t isize;
if (bdev_read_only(I_BDEV(inode)))
return -EPERM;
isize = i_size_read(inode);
if (*pos >= isize) {
if (*count || *pos > isize)
return -ENOSPC;
}
if (*pos + *count > isize)
*count = isize - *pos;
#else
return -EPERM;
#endif
}
return 0;
}
EXPORT_SYMBOL(generic_write_checks);
int pagecache_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata)
{
const struct address_space_operations *aops = mapping->a_ops;
if (aops->write_begin) {
return aops->write_begin(file, mapping, pos, len, flags,
pagep, fsdata);
} else {
int ret;
pgoff_t index = pos >> PAGE_CACHE_SHIFT;
unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
struct inode *inode = mapping->host;
struct page *page;
again:
page = __grab_cache_page(mapping, index);
*pagep = page;
if (!page)
return -ENOMEM;
if (flags & AOP_FLAG_UNINTERRUPTIBLE && !PageUptodate(page)) {
/*
* There is no way to resolve a short write situation
* for a !Uptodate page (except by double copying in
* the caller done by generic_perform_write_2copy).
*
* Instead, we have to bring it uptodate here.
*/
ret = aops->readpage(file, page);
page_cache_release(page);
if (ret) {
if (ret == AOP_TRUNCATED_PAGE)
goto again;
return ret;
}
goto again;
}
ret = aops->prepare_write(file, page, offset, offset+len);
if (ret) {
unlock_page(page);
page_cache_release(page);
if (pos + len > inode->i_size)
vmtruncate(inode, inode->i_size);
}
return ret;
}
}
EXPORT_SYMBOL(pagecache_write_begin);
int pagecache_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata)
{
const struct address_space_operations *aops = mapping->a_ops;
int ret;
if (aops->write_end) {
mark_page_accessed(page);
ret = aops->write_end(file, mapping, pos, len, copied,
page, fsdata);
} else {
unsigned offset = pos & (PAGE_CACHE_SIZE - 1);
struct inode *inode = mapping->host;
flush_dcache_page(page);
ret = aops->commit_write(file, page, offset, offset+len);
unlock_page(page);
mark_page_accessed(page);
page_cache_release(page);
if (ret < 0) {
if (pos + len > inode->i_size)
vmtruncate(inode, inode->i_size);
} else if (ret > 0)
ret = min_t(size_t, copied, ret);
else
ret = copied;
}
return ret;
}
EXPORT_SYMBOL(pagecache_write_end);
ssize_t
generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long *nr_segs, loff_t pos, loff_t *ppos,
size_t count, size_t ocount)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
ssize_t written;
if (count != ocount)
*nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
written = generic_file_direct_IO(WRITE, iocb, iov, pos, *nr_segs);
if (written > 0) {
loff_t end = pos + written;
if (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
i_size_write(inode, end);
mark_inode_dirty(inode);
}
*ppos = end;
}
/*
* Sync the fs metadata but not the minor inode changes and
* of course not the data as we did direct DMA for the IO.
* i_mutex is held, which protects generic_osync_inode() from
* livelocking. AIO O_DIRECT ops attempt to sync metadata here.
*/
if ((written >= 0 || written == -EIOCBQUEUED) &&
((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
int err = generic_osync_inode(inode, mapping, OSYNC_METADATA);
if (err < 0)
written = err;
}
return written;
}
EXPORT_SYMBOL(generic_file_direct_write);
/*
* Find or create a page at the given pagecache position. Return the locked
* page. This function is specifically for buffered writes.
*/
struct page *__grab_cache_page(struct address_space *mapping, pgoff_t index)
{
int status;
struct page *page;
repeat:
page = find_lock_page(mapping, index);
if (likely(page))
return page;
page = page_cache_alloc(mapping);
if (!page)
return NULL;
status = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
if (unlikely(status)) {
page_cache_release(page);
if (status == -EEXIST)
goto repeat;
return NULL;
}
return page;
}
EXPORT_SYMBOL(__grab_cache_page);
static ssize_t generic_perform_write_2copy(struct file *file,
struct iov_iter *i, loff_t pos)
{
struct address_space *mapping = file->f_mapping;
const struct address_space_operations *a_ops = mapping->a_ops;
struct inode *inode = mapping->host;
long status = 0;
ssize_t written = 0;
do {
struct page *src_page;
struct page *page;
pgoff_t index; /* Pagecache index for current page */
unsigned long offset; /* Offset into pagecache page */
unsigned long bytes; /* Bytes to write to page */
size_t copied; /* Bytes copied from user */
offset = (pos & (PAGE_CACHE_SIZE - 1));
index = pos >> PAGE_CACHE_SHIFT;
bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
iov_iter_count(i));
/*
* a non-NULL src_page indicates that we're doing the
* copy via get_user_pages and kmap.
*/
src_page = NULL;
/*
* Bring in the user page that we will copy from _first_.
* Otherwise there's a nasty deadlock on copying from the
* same page as we're writing to, without it being marked
* up-to-date.
*
* Not only is this an optimisation, but it is also required
* to check that the address is actually valid, when atomic
* usercopies are used, below.
*/
if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
status = -EFAULT;
break;
}
page = __grab_cache_page(mapping, index);
if (!page) {
status = -ENOMEM;
break;
}
/*
* non-uptodate pages cannot cope with short copies, and we
* cannot take a pagefault with the destination page locked.
* So pin the source page to copy it.
*/
if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) {
unlock_page(page);
src_page = alloc_page(GFP_KERNEL);
if (!src_page) {
page_cache_release(page);
status = -ENOMEM;
break;
}
/*
* Cannot get_user_pages with a page locked for the
* same reason as we can't take a page fault with a
* page locked (as explained below).
*/
copied = iov_iter_copy_from_user(src_page, i,
offset, bytes);
if (unlikely(copied == 0)) {
status = -EFAULT;
page_cache_release(page);
page_cache_release(src_page);
break;
}
bytes = copied;
lock_page(page);
/*
* Can't handle the page going uptodate here, because
* that means we would use non-atomic usercopies, which
* zero out the tail of the page, which can cause
* zeroes to become transiently visible. We could just
* use a non-zeroing copy, but the APIs aren't too
* consistent.
*/
if (unlikely(!page->mapping || PageUptodate(page))) {
unlock_page(page);
page_cache_release(page);
page_cache_release(src_page);
continue;
}
}
status = a_ops->prepare_write(file, page, offset, offset+bytes);
if (unlikely(status))
goto fs_write_aop_error;
if (!src_page) {
/*
* Must not enter the pagefault handler here, because
* we hold the page lock, so we might recursively
* deadlock on the same lock, or get an ABBA deadlock
* against a different lock, or against the mmap_sem
* (which nests outside the page lock). So increment
* preempt count, and use _atomic usercopies.
*
* The page is uptodate so we are OK to encounter a
* short copy: if unmodified parts of the page are
* marked dirty and written out to disk, it doesn't
* really matter.
*/
pagefault_disable();
copied = iov_iter_copy_from_user_atomic(page, i,
offset, bytes);
pagefault_enable();
} else {
void *src, *dst;
src = kmap_atomic(src_page, KM_USER0);
dst = kmap_atomic(page, KM_USER1);
memcpy(dst + offset, src + offset, bytes);
kunmap_atomic(dst, KM_USER1);
kunmap_atomic(src, KM_USER0);
copied = bytes;
}
flush_dcache_page(page);
status = a_ops->commit_write(file, page, offset, offset+bytes);
if (unlikely(status < 0))
goto fs_write_aop_error;
if (unlikely(status > 0)) /* filesystem did partial write */
copied = min_t(size_t, copied, status);
unlock_page(page);
mark_page_accessed(page);
page_cache_release(page);
if (src_page)
page_cache_release(src_page);
iov_iter_advance(i, copied);
pos += copied;
written += copied;
balance_dirty_pages_ratelimited(mapping);
cond_resched();
continue;
fs_write_aop_error:
unlock_page(page);
page_cache_release(page);
if (src_page)
page_cache_release(src_page);
/*
* prepare_write() may have instantiated a few blocks
* outside i_size. Trim these off again. Don't need
* i_size_read because we hold i_mutex.
*/
if (pos + bytes > inode->i_size)
vmtruncate(inode, inode->i_size);
break;
} while (iov_iter_count(i));
return written ? written : status;
}
static ssize_t generic_perform_write(struct file *file,
struct iov_iter *i, loff_t pos)
{
struct address_space *mapping = file->f_mapping;
const struct address_space_operations *a_ops = mapping->a_ops;
long status = 0;
ssize_t written = 0;
unsigned int flags = 0;
/*
* Copies from kernel address space cannot fail (NFSD is a big user).
*/
if (segment_eq(get_fs(), KERNEL_DS))
flags |= AOP_FLAG_UNINTERRUPTIBLE;
do {
struct page *page;
pgoff_t index; /* Pagecache index for current page */
unsigned long offset; /* Offset into pagecache page */
unsigned long bytes; /* Bytes to write to page */
size_t copied; /* Bytes copied from user */
void *fsdata;
offset = (pos & (PAGE_CACHE_SIZE - 1));
index = pos >> PAGE_CACHE_SHIFT;
bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
iov_iter_count(i));
again:
/*
* Bring in the user page that we will copy from _first_.
* Otherwise there's a nasty deadlock on copying from the
* same page as we're writing to, without it being marked
* up-to-date.
*
* Not only is this an optimisation, but it is also required
* to check that the address is actually valid, when atomic
* usercopies are used, below.
*/
if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
status = -EFAULT;
break;
}
status = a_ops->write_begin(file, mapping, pos, bytes, flags,
&page, &fsdata);
if (unlikely(status))
break;
pagefault_disable();
copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
pagefault_enable();
flush_dcache_page(page);
status = a_ops->write_end(file, mapping, pos, bytes, copied,
page, fsdata);
if (unlikely(status < 0))
break;
copied = status;
cond_resched();
iov_iter_advance(i, copied);
if (unlikely(copied == 0)) {
/*
* If we were unable to copy any data at all, we must
* fall back to a single segment length write.
*
* If we didn't fallback here, we could livelock
* because not all segments in the iov can be copied at
* once without a pagefault.
*/
bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
iov_iter_single_seg_count(i));
goto again;
}
pos += copied;
written += copied;
balance_dirty_pages_ratelimited(mapping);
} while (iov_iter_count(i));
return written ? written : status;
}
ssize_t
generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos, loff_t *ppos,
size_t count, ssize_t written)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
const struct address_space_operations *a_ops = mapping->a_ops;
struct inode *inode = mapping->host;
ssize_t status;
struct iov_iter i;
iov_iter_init(&i, iov, nr_segs, count, written);
if (a_ops->write_begin)
status = generic_perform_write(file, &i, pos);
else
status = generic_perform_write_2copy(file, &i, pos);
if (likely(status >= 0)) {
written += status;
*ppos = pos + status;
/*
* For now, when the user asks for O_SYNC, we'll actually give
* O_DSYNC
*/
if (unlikely((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
if (!a_ops->writepage || !is_sync_kiocb(iocb))
status = generic_osync_inode(inode, mapping,
OSYNC_METADATA|OSYNC_DATA);
}
}
/*
* If we get here for O_DIRECT writes then we must have fallen through
* to buffered writes (block instantiation inside i_size). So we sync
* the file data here, to try to honour O_DIRECT expectations.
*/
if (unlikely(file->f_flags & O_DIRECT) && written)
status = filemap_write_and_wait(mapping);
return written ? written : status;
}
EXPORT_SYMBOL(generic_file_buffered_write);
static ssize_t
__generic_file_aio_write_nolock(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t *ppos)
{
struct file *file = iocb->ki_filp;
struct address_space * mapping = file->f_mapping;
size_t ocount; /* original count */
size_t count; /* after file limit checks */
struct inode *inode = mapping->host;
loff_t pos;
ssize_t written;
ssize_t err;
ocount = 0;
err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
if (err)
return err;
count = ocount;
pos = *ppos;
vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
/* We can write back this queue in page reclaim */
current->backing_dev_info = mapping->backing_dev_info;
written = 0;
err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
if (err)
goto out;
if (count == 0)
goto out;
err = remove_suid(file->f_path.dentry);
if (err)
goto out;
file_update_time(file);
/* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
if (unlikely(file->f_flags & O_DIRECT)) {
loff_t endbyte;
ssize_t written_buffered;
written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
ppos, count, ocount);
if (written < 0 || written == count)
goto out;
/*
* direct-io write to a hole: fall through to buffered I/O
* for completing the rest of the request.
*/
pos += written;
count -= written;
written_buffered = generic_file_buffered_write(iocb, iov,
nr_segs, pos, ppos, count,
written);
/*
* If generic_file_buffered_write() retuned a synchronous error
* then we want to return the number of bytes which were
* direct-written, or the error code if that was zero. Note
* that this differs from normal direct-io semantics, which
* will return -EFOO even if some bytes were written.
*/
if (written_buffered < 0) {
err = written_buffered;
goto out;
}
/*
* We need to ensure that the page cache pages are written to
* disk and invalidated to preserve the expected O_DIRECT
* semantics.
*/
endbyte = pos + written_buffered - written - 1;
err = do_sync_mapping_range(file->f_mapping, pos, endbyte,
SYNC_FILE_RANGE_WAIT_BEFORE|
SYNC_FILE_RANGE_WRITE|
SYNC_FILE_RANGE_WAIT_AFTER);
if (err == 0) {
written = written_buffered;
invalidate_mapping_pages(mapping,
pos >> PAGE_CACHE_SHIFT,
endbyte >> PAGE_CACHE_SHIFT);
} else {
/*
* We don't know how much we wrote, so just return
* the number of bytes which were direct-written
*/
}
} else {
written = generic_file_buffered_write(iocb, iov, nr_segs,
pos, ppos, count, written);
}
out:
current->backing_dev_info = NULL;
return written ? written : err;
}
ssize_t generic_file_aio_write_nolock(struct kiocb *iocb,
const struct iovec *iov, unsigned long nr_segs, loff_t pos)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
ssize_t ret;
BUG_ON(iocb->ki_pos != pos);
ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
&iocb->ki_pos);
if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
ssize_t err;
err = sync_page_range_nolock(inode, mapping, pos, ret);
if (err < 0)
ret = err;
}
return ret;
}
EXPORT_SYMBOL(generic_file_aio_write_nolock);
ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
ssize_t ret;
BUG_ON(iocb->ki_pos != pos);
mutex_lock(&inode->i_mutex);
ret = __generic_file_aio_write_nolock(iocb, iov, nr_segs,
&iocb->ki_pos);
mutex_unlock(&inode->i_mutex);
if (ret > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
ssize_t err;
err = sync_page_range(inode, mapping, pos, ret);
if (err < 0)
ret = err;
}
return ret;
}
EXPORT_SYMBOL(generic_file_aio_write);
/*
* Called under i_mutex for writes to S_ISREG files. Returns -EIO if something
* went wrong during pagecache shootdown.
*/
static ssize_t
generic_file_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov,
loff_t offset, unsigned long nr_segs)
{
struct file *file = iocb->ki_filp;
struct address_space *mapping = file->f_mapping;
ssize_t retval;
size_t write_len;
pgoff_t end = 0; /* silence gcc */
/*
* If it's a write, unmap all mmappings of the file up-front. This
* will cause any pte dirty bits to be propagated into the pageframes
* for the subsequent filemap_write_and_wait().
*/
if (rw == WRITE) {
write_len = iov_length(iov, nr_segs);
end = (offset + write_len - 1) >> PAGE_CACHE_SHIFT;
if (mapping_mapped(mapping))
unmap_mapping_range(mapping, offset, write_len, 0);
}
retval = filemap_write_and_wait(mapping);
if (retval)
goto out;
/*
* After a write we want buffered reads to be sure to go to disk to get
* the new data. We invalidate clean cached page from the region we're
* about to write. We do this *before* the write so that we can return
* -EIO without clobbering -EIOCBQUEUED from ->direct_IO().
*/
if (rw == WRITE && mapping->nrpages) {
retval = invalidate_inode_pages2_range(mapping,
offset >> PAGE_CACHE_SHIFT, end);
if (retval)
goto out;
}
retval = mapping->a_ops->direct_IO(rw, iocb, iov, offset, nr_segs);
/*
* Finally, try again to invalidate clean pages which might have been
* cached by non-direct readahead, or faulted in by get_user_pages()
* if the source of the write was an mmap'ed region of the file
* we're writing. Either one is a pretty crazy thing to do,
* so we don't support it 100%. If this invalidation
* fails, tough, the write still worked...
*/
if (rw == WRITE && mapping->nrpages) {
invalidate_inode_pages2_range(mapping, offset >> PAGE_CACHE_SHIFT, end);
}
out:
return retval;
}
/**
* try_to_release_page() - release old fs-specific metadata on a page
*
* @page: the page which the kernel is trying to free
* @gfp_mask: memory allocation flags (and I/O mode)
*
* The address_space is to try to release any data against the page
* (presumably at page->private). If the release was successful, return `1'.
* Otherwise return zero.
*
* The @gfp_mask argument specifies whether I/O may be performed to release
* this page (__GFP_IO), and whether the call may block (__GFP_WAIT).
*
* NOTE: @gfp_mask may go away, and this function may become non-blocking.
*/
int try_to_release_page(struct page *page, gfp_t gfp_mask)
{
struct address_space * const mapping = page->mapping;
BUG_ON(!PageLocked(page));
if (PageWriteback(page))
return 0;
if (mapping && mapping->a_ops->releasepage)
return mapping->a_ops->releasepage(page, gfp_mask);
return try_to_free_buffers(page);
}
EXPORT_SYMBOL(try_to_release_page);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5876_0 |
crossvul-cpp_data_bad_3516_0 | #include <linux/mm.h>
#include <linux/hugetlb.h>
#include <linux/huge_mm.h>
#include <linux/mount.h>
#include <linux/seq_file.h>
#include <linux/highmem.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/mempolicy.h>
#include <linux/rmap.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <asm/elf.h>
#include <asm/uaccess.h>
#include <asm/tlbflush.h>
#include "internal.h"
void task_mem(struct seq_file *m, struct mm_struct *mm)
{
unsigned long data, text, lib, swap;
unsigned long hiwater_vm, total_vm, hiwater_rss, total_rss;
/*
* Note: to minimize their overhead, mm maintains hiwater_vm and
* hiwater_rss only when about to *lower* total_vm or rss. Any
* collector of these hiwater stats must therefore get total_vm
* and rss too, which will usually be the higher. Barriers? not
* worth the effort, such snapshots can always be inconsistent.
*/
hiwater_vm = total_vm = mm->total_vm;
if (hiwater_vm < mm->hiwater_vm)
hiwater_vm = mm->hiwater_vm;
hiwater_rss = total_rss = get_mm_rss(mm);
if (hiwater_rss < mm->hiwater_rss)
hiwater_rss = mm->hiwater_rss;
data = mm->total_vm - mm->shared_vm - mm->stack_vm;
text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> 10;
lib = (mm->exec_vm << (PAGE_SHIFT-10)) - text;
swap = get_mm_counter(mm, MM_SWAPENTS);
seq_printf(m,
"VmPeak:\t%8lu kB\n"
"VmSize:\t%8lu kB\n"
"VmLck:\t%8lu kB\n"
"VmHWM:\t%8lu kB\n"
"VmRSS:\t%8lu kB\n"
"VmData:\t%8lu kB\n"
"VmStk:\t%8lu kB\n"
"VmExe:\t%8lu kB\n"
"VmLib:\t%8lu kB\n"
"VmPTE:\t%8lu kB\n"
"VmSwap:\t%8lu kB\n",
hiwater_vm << (PAGE_SHIFT-10),
(total_vm - mm->reserved_vm) << (PAGE_SHIFT-10),
mm->locked_vm << (PAGE_SHIFT-10),
hiwater_rss << (PAGE_SHIFT-10),
total_rss << (PAGE_SHIFT-10),
data << (PAGE_SHIFT-10),
mm->stack_vm << (PAGE_SHIFT-10), text, lib,
(PTRS_PER_PTE*sizeof(pte_t)*mm->nr_ptes) >> 10,
swap << (PAGE_SHIFT-10));
}
unsigned long task_vsize(struct mm_struct *mm)
{
return PAGE_SIZE * mm->total_vm;
}
unsigned long task_statm(struct mm_struct *mm,
unsigned long *shared, unsigned long *text,
unsigned long *data, unsigned long *resident)
{
*shared = get_mm_counter(mm, MM_FILEPAGES);
*text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK))
>> PAGE_SHIFT;
*data = mm->total_vm - mm->shared_vm;
*resident = *shared + get_mm_counter(mm, MM_ANONPAGES);
return mm->total_vm;
}
static void pad_len_spaces(struct seq_file *m, int len)
{
len = 25 + sizeof(void*) * 6 - len;
if (len < 1)
len = 1;
seq_printf(m, "%*c", len, ' ');
}
static void vma_stop(struct proc_maps_private *priv, struct vm_area_struct *vma)
{
if (vma && vma != priv->tail_vma) {
struct mm_struct *mm = vma->vm_mm;
up_read(&mm->mmap_sem);
mmput(mm);
}
}
static void *m_start(struct seq_file *m, loff_t *pos)
{
struct proc_maps_private *priv = m->private;
unsigned long last_addr = m->version;
struct mm_struct *mm;
struct vm_area_struct *vma, *tail_vma = NULL;
loff_t l = *pos;
/* Clear the per syscall fields in priv */
priv->task = NULL;
priv->tail_vma = NULL;
/*
* We remember last_addr rather than next_addr to hit with
* mmap_cache most of the time. We have zero last_addr at
* the beginning and also after lseek. We will have -1 last_addr
* after the end of the vmas.
*/
if (last_addr == -1UL)
return NULL;
priv->task = get_pid_task(priv->pid, PIDTYPE_PID);
if (!priv->task)
return ERR_PTR(-ESRCH);
mm = mm_for_maps(priv->task);
if (!mm || IS_ERR(mm))
return mm;
down_read(&mm->mmap_sem);
tail_vma = get_gate_vma(priv->task->mm);
priv->tail_vma = tail_vma;
/* Start with last addr hint */
vma = find_vma(mm, last_addr);
if (last_addr && vma) {
vma = vma->vm_next;
goto out;
}
/*
* Check the vma index is within the range and do
* sequential scan until m_index.
*/
vma = NULL;
if ((unsigned long)l < mm->map_count) {
vma = mm->mmap;
while (l-- && vma)
vma = vma->vm_next;
goto out;
}
if (l != mm->map_count)
tail_vma = NULL; /* After gate vma */
out:
if (vma)
return vma;
/* End of vmas has been reached */
m->version = (tail_vma != NULL)? 0: -1UL;
up_read(&mm->mmap_sem);
mmput(mm);
return tail_vma;
}
static void *m_next(struct seq_file *m, void *v, loff_t *pos)
{
struct proc_maps_private *priv = m->private;
struct vm_area_struct *vma = v;
struct vm_area_struct *tail_vma = priv->tail_vma;
(*pos)++;
if (vma && (vma != tail_vma) && vma->vm_next)
return vma->vm_next;
vma_stop(priv, vma);
return (vma != tail_vma)? tail_vma: NULL;
}
static void m_stop(struct seq_file *m, void *v)
{
struct proc_maps_private *priv = m->private;
struct vm_area_struct *vma = v;
vma_stop(priv, vma);
if (priv->task)
put_task_struct(priv->task);
}
static int do_maps_open(struct inode *inode, struct file *file,
const struct seq_operations *ops)
{
struct proc_maps_private *priv;
int ret = -ENOMEM;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv) {
priv->pid = proc_pid(inode);
ret = seq_open(file, ops);
if (!ret) {
struct seq_file *m = file->private_data;
m->private = priv;
} else {
kfree(priv);
}
}
return ret;
}
static void show_map_vma(struct seq_file *m, struct vm_area_struct *vma)
{
struct mm_struct *mm = vma->vm_mm;
struct file *file = vma->vm_file;
int flags = vma->vm_flags;
unsigned long ino = 0;
unsigned long long pgoff = 0;
unsigned long start;
dev_t dev = 0;
int len;
if (file) {
struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
dev = inode->i_sb->s_dev;
ino = inode->i_ino;
pgoff = ((loff_t)vma->vm_pgoff) << PAGE_SHIFT;
}
/* We don't show the stack guard page in /proc/maps */
start = vma->vm_start;
if (vma->vm_flags & VM_GROWSDOWN)
if (!vma_stack_continue(vma->vm_prev, vma->vm_start))
start += PAGE_SIZE;
seq_printf(m, "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu %n",
start,
vma->vm_end,
flags & VM_READ ? 'r' : '-',
flags & VM_WRITE ? 'w' : '-',
flags & VM_EXEC ? 'x' : '-',
flags & VM_MAYSHARE ? 's' : 'p',
pgoff,
MAJOR(dev), MINOR(dev), ino, &len);
/*
* Print the dentry name for named mappings, and a
* special [heap] marker for the heap:
*/
if (file) {
pad_len_spaces(m, len);
seq_path(m, &file->f_path, "\n");
} else {
const char *name = arch_vma_name(vma);
if (!name) {
if (mm) {
if (vma->vm_start <= mm->brk &&
vma->vm_end >= mm->start_brk) {
name = "[heap]";
} else if (vma->vm_start <= mm->start_stack &&
vma->vm_end >= mm->start_stack) {
name = "[stack]";
}
} else {
name = "[vdso]";
}
}
if (name) {
pad_len_spaces(m, len);
seq_puts(m, name);
}
}
seq_putc(m, '\n');
}
static int show_map(struct seq_file *m, void *v)
{
struct vm_area_struct *vma = v;
struct proc_maps_private *priv = m->private;
struct task_struct *task = priv->task;
show_map_vma(m, vma);
if (m->count < m->size) /* vma is copied successfully */
m->version = (vma != get_gate_vma(task->mm))
? vma->vm_start : 0;
return 0;
}
static const struct seq_operations proc_pid_maps_op = {
.start = m_start,
.next = m_next,
.stop = m_stop,
.show = show_map
};
static int maps_open(struct inode *inode, struct file *file)
{
return do_maps_open(inode, file, &proc_pid_maps_op);
}
const struct file_operations proc_maps_operations = {
.open = maps_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
/*
* Proportional Set Size(PSS): my share of RSS.
*
* PSS of a process is the count of pages it has in memory, where each
* page is divided by the number of processes sharing it. So if a
* process has 1000 pages all to itself, and 1000 shared with one other
* process, its PSS will be 1500.
*
* To keep (accumulated) division errors low, we adopt a 64bit
* fixed-point pss counter to minimize division errors. So (pss >>
* PSS_SHIFT) would be the real byte count.
*
* A shift of 12 before division means (assuming 4K page size):
* - 1M 3-user-pages add up to 8KB errors;
* - supports mapcount up to 2^24, or 16M;
* - supports PSS up to 2^52 bytes, or 4PB.
*/
#define PSS_SHIFT 12
#ifdef CONFIG_PROC_PAGE_MONITOR
struct mem_size_stats {
struct vm_area_struct *vma;
unsigned long resident;
unsigned long shared_clean;
unsigned long shared_dirty;
unsigned long private_clean;
unsigned long private_dirty;
unsigned long referenced;
unsigned long anonymous;
unsigned long anonymous_thp;
unsigned long swap;
u64 pss;
};
static void smaps_pte_entry(pte_t ptent, unsigned long addr,
unsigned long ptent_size, struct mm_walk *walk)
{
struct mem_size_stats *mss = walk->private;
struct vm_area_struct *vma = mss->vma;
struct page *page;
int mapcount;
if (is_swap_pte(ptent)) {
mss->swap += ptent_size;
return;
}
if (!pte_present(ptent))
return;
page = vm_normal_page(vma, addr, ptent);
if (!page)
return;
if (PageAnon(page))
mss->anonymous += ptent_size;
mss->resident += ptent_size;
/* Accumulate the size in pages that have been accessed. */
if (pte_young(ptent) || PageReferenced(page))
mss->referenced += ptent_size;
mapcount = page_mapcount(page);
if (mapcount >= 2) {
if (pte_dirty(ptent) || PageDirty(page))
mss->shared_dirty += ptent_size;
else
mss->shared_clean += ptent_size;
mss->pss += (ptent_size << PSS_SHIFT) / mapcount;
} else {
if (pte_dirty(ptent) || PageDirty(page))
mss->private_dirty += ptent_size;
else
mss->private_clean += ptent_size;
mss->pss += (ptent_size << PSS_SHIFT);
}
}
static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct mem_size_stats *mss = walk->private;
struct vm_area_struct *vma = mss->vma;
pte_t *pte;
spinlock_t *ptl;
spin_lock(&walk->mm->page_table_lock);
if (pmd_trans_huge(*pmd)) {
if (pmd_trans_splitting(*pmd)) {
spin_unlock(&walk->mm->page_table_lock);
wait_split_huge_page(vma->anon_vma, pmd);
} else {
smaps_pte_entry(*(pte_t *)pmd, addr,
HPAGE_PMD_SIZE, walk);
spin_unlock(&walk->mm->page_table_lock);
mss->anonymous_thp += HPAGE_PMD_SIZE;
return 0;
}
} else {
spin_unlock(&walk->mm->page_table_lock);
}
/*
* The mmap_sem held all the way back in m_start() is what
* keeps khugepaged out of here and from collapsing things
* in here.
*/
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE)
smaps_pte_entry(*pte, addr, PAGE_SIZE, walk);
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
static int show_smap(struct seq_file *m, void *v)
{
struct proc_maps_private *priv = m->private;
struct task_struct *task = priv->task;
struct vm_area_struct *vma = v;
struct mem_size_stats mss;
struct mm_walk smaps_walk = {
.pmd_entry = smaps_pte_range,
.mm = vma->vm_mm,
.private = &mss,
};
memset(&mss, 0, sizeof mss);
mss.vma = vma;
/* mmap_sem is held in m_start */
if (vma->vm_mm && !is_vm_hugetlb_page(vma))
walk_page_range(vma->vm_start, vma->vm_end, &smaps_walk);
show_map_vma(m, vma);
seq_printf(m,
"Size: %8lu kB\n"
"Rss: %8lu kB\n"
"Pss: %8lu kB\n"
"Shared_Clean: %8lu kB\n"
"Shared_Dirty: %8lu kB\n"
"Private_Clean: %8lu kB\n"
"Private_Dirty: %8lu kB\n"
"Referenced: %8lu kB\n"
"Anonymous: %8lu kB\n"
"AnonHugePages: %8lu kB\n"
"Swap: %8lu kB\n"
"KernelPageSize: %8lu kB\n"
"MMUPageSize: %8lu kB\n"
"Locked: %8lu kB\n",
(vma->vm_end - vma->vm_start) >> 10,
mss.resident >> 10,
(unsigned long)(mss.pss >> (10 + PSS_SHIFT)),
mss.shared_clean >> 10,
mss.shared_dirty >> 10,
mss.private_clean >> 10,
mss.private_dirty >> 10,
mss.referenced >> 10,
mss.anonymous >> 10,
mss.anonymous_thp >> 10,
mss.swap >> 10,
vma_kernel_pagesize(vma) >> 10,
vma_mmu_pagesize(vma) >> 10,
(vma->vm_flags & VM_LOCKED) ?
(unsigned long)(mss.pss >> (10 + PSS_SHIFT)) : 0);
if (m->count < m->size) /* vma is copied successfully */
m->version = (vma != get_gate_vma(task->mm))
? vma->vm_start : 0;
return 0;
}
static const struct seq_operations proc_pid_smaps_op = {
.start = m_start,
.next = m_next,
.stop = m_stop,
.show = show_smap
};
static int smaps_open(struct inode *inode, struct file *file)
{
return do_maps_open(inode, file, &proc_pid_smaps_op);
}
const struct file_operations proc_smaps_operations = {
.open = smaps_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr,
unsigned long end, struct mm_walk *walk)
{
struct vm_area_struct *vma = walk->private;
pte_t *pte, ptent;
spinlock_t *ptl;
struct page *page;
split_huge_page_pmd(walk->mm, pmd);
pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl);
for (; addr != end; pte++, addr += PAGE_SIZE) {
ptent = *pte;
if (!pte_present(ptent))
continue;
page = vm_normal_page(vma, addr, ptent);
if (!page)
continue;
/* Clear accessed and referenced bits. */
ptep_test_and_clear_young(vma, addr, pte);
ClearPageReferenced(page);
}
pte_unmap_unlock(pte - 1, ptl);
cond_resched();
return 0;
}
#define CLEAR_REFS_ALL 1
#define CLEAR_REFS_ANON 2
#define CLEAR_REFS_MAPPED 3
static ssize_t clear_refs_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task;
char buffer[PROC_NUMBUF];
struct mm_struct *mm;
struct vm_area_struct *vma;
long type;
memset(buffer, 0, sizeof(buffer));
if (count > sizeof(buffer) - 1)
count = sizeof(buffer) - 1;
if (copy_from_user(buffer, buf, count))
return -EFAULT;
if (strict_strtol(strstrip(buffer), 10, &type))
return -EINVAL;
if (type < CLEAR_REFS_ALL || type > CLEAR_REFS_MAPPED)
return -EINVAL;
task = get_proc_task(file->f_path.dentry->d_inode);
if (!task)
return -ESRCH;
mm = get_task_mm(task);
if (mm) {
struct mm_walk clear_refs_walk = {
.pmd_entry = clear_refs_pte_range,
.mm = mm,
};
down_read(&mm->mmap_sem);
for (vma = mm->mmap; vma; vma = vma->vm_next) {
clear_refs_walk.private = vma;
if (is_vm_hugetlb_page(vma))
continue;
/*
* Writing 1 to /proc/pid/clear_refs affects all pages.
*
* Writing 2 to /proc/pid/clear_refs only affects
* Anonymous pages.
*
* Writing 3 to /proc/pid/clear_refs only affects file
* mapped pages.
*/
if (type == CLEAR_REFS_ANON && vma->vm_file)
continue;
if (type == CLEAR_REFS_MAPPED && !vma->vm_file)
continue;
walk_page_range(vma->vm_start, vma->vm_end,
&clear_refs_walk);
}
flush_tlb_mm(mm);
up_read(&mm->mmap_sem);
mmput(mm);
}
put_task_struct(task);
return count;
}
const struct file_operations proc_clear_refs_operations = {
.write = clear_refs_write,
.llseek = noop_llseek,
};
struct pagemapread {
int pos, len;
u64 *buffer;
};
#define PM_ENTRY_BYTES sizeof(u64)
#define PM_STATUS_BITS 3
#define PM_STATUS_OFFSET (64 - PM_STATUS_BITS)
#define PM_STATUS_MASK (((1LL << PM_STATUS_BITS) - 1) << PM_STATUS_OFFSET)
#define PM_STATUS(nr) (((nr) << PM_STATUS_OFFSET) & PM_STATUS_MASK)
#define PM_PSHIFT_BITS 6
#define PM_PSHIFT_OFFSET (PM_STATUS_OFFSET - PM_PSHIFT_BITS)
#define PM_PSHIFT_MASK (((1LL << PM_PSHIFT_BITS) - 1) << PM_PSHIFT_OFFSET)
#define PM_PSHIFT(x) (((u64) (x) << PM_PSHIFT_OFFSET) & PM_PSHIFT_MASK)
#define PM_PFRAME_MASK ((1LL << PM_PSHIFT_OFFSET) - 1)
#define PM_PFRAME(x) ((x) & PM_PFRAME_MASK)
#define PM_PRESENT PM_STATUS(4LL)
#define PM_SWAP PM_STATUS(2LL)
#define PM_NOT_PRESENT PM_PSHIFT(PAGE_SHIFT)
#define PM_END_OF_BUFFER 1
static int add_to_pagemap(unsigned long addr, u64 pfn,
struct pagemapread *pm)
{
pm->buffer[pm->pos++] = pfn;
if (pm->pos >= pm->len)
return PM_END_OF_BUFFER;
return 0;
}
static int pagemap_pte_hole(unsigned long start, unsigned long end,
struct mm_walk *walk)
{
struct pagemapread *pm = walk->private;
unsigned long addr;
int err = 0;
for (addr = start; addr < end; addr += PAGE_SIZE) {
err = add_to_pagemap(addr, PM_NOT_PRESENT, pm);
if (err)
break;
}
return err;
}
static u64 swap_pte_to_pagemap_entry(pte_t pte)
{
swp_entry_t e = pte_to_swp_entry(pte);
return swp_type(e) | (swp_offset(e) << MAX_SWAPFILES_SHIFT);
}
static u64 pte_to_pagemap_entry(pte_t pte)
{
u64 pme = 0;
if (is_swap_pte(pte))
pme = PM_PFRAME(swap_pte_to_pagemap_entry(pte))
| PM_PSHIFT(PAGE_SHIFT) | PM_SWAP;
else if (pte_present(pte))
pme = PM_PFRAME(pte_pfn(pte))
| PM_PSHIFT(PAGE_SHIFT) | PM_PRESENT;
return pme;
}
static int pagemap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct vm_area_struct *vma;
struct pagemapread *pm = walk->private;
pte_t *pte;
int err = 0;
split_huge_page_pmd(walk->mm, pmd);
/* find the first VMA at or above 'addr' */
vma = find_vma(walk->mm, addr);
for (; addr != end; addr += PAGE_SIZE) {
u64 pfn = PM_NOT_PRESENT;
/* check to see if we've left 'vma' behind
* and need a new, higher one */
if (vma && (addr >= vma->vm_end))
vma = find_vma(walk->mm, addr);
/* check that 'vma' actually covers this address,
* and that it isn't a huge page vma */
if (vma && (vma->vm_start <= addr) &&
!is_vm_hugetlb_page(vma)) {
pte = pte_offset_map(pmd, addr);
pfn = pte_to_pagemap_entry(*pte);
/* unmap before userspace copy */
pte_unmap(pte);
}
err = add_to_pagemap(addr, pfn, pm);
if (err)
return err;
}
cond_resched();
return err;
}
#ifdef CONFIG_HUGETLB_PAGE
static u64 huge_pte_to_pagemap_entry(pte_t pte, int offset)
{
u64 pme = 0;
if (pte_present(pte))
pme = PM_PFRAME(pte_pfn(pte) + offset)
| PM_PSHIFT(PAGE_SHIFT) | PM_PRESENT;
return pme;
}
/* This function walks within one hugetlb entry in the single call */
static int pagemap_hugetlb_range(pte_t *pte, unsigned long hmask,
unsigned long addr, unsigned long end,
struct mm_walk *walk)
{
struct pagemapread *pm = walk->private;
int err = 0;
u64 pfn;
for (; addr != end; addr += PAGE_SIZE) {
int offset = (addr & ~hmask) >> PAGE_SHIFT;
pfn = huge_pte_to_pagemap_entry(*pte, offset);
err = add_to_pagemap(addr, pfn, pm);
if (err)
return err;
}
cond_resched();
return err;
}
#endif /* HUGETLB_PAGE */
/*
* /proc/pid/pagemap - an array mapping virtual pages to pfns
*
* For each page in the address space, this file contains one 64-bit entry
* consisting of the following:
*
* Bits 0-55 page frame number (PFN) if present
* Bits 0-4 swap type if swapped
* Bits 5-55 swap offset if swapped
* Bits 55-60 page shift (page size = 1<<page shift)
* Bit 61 reserved for future use
* Bit 62 page swapped
* Bit 63 page present
*
* If the page is not present but in swap, then the PFN contains an
* encoding of the swap file number and the page's offset into the
* swap. Unmapped pages return a null PFN. This allows determining
* precisely which pages are mapped (or in swap) and comparing mapped
* pages between processes.
*
* Efficient users of this interface will use /proc/pid/maps to
* determine which areas of memory are actually mapped and llseek to
* skip over unmapped regions.
*/
#define PAGEMAP_WALK_SIZE (PMD_SIZE)
#define PAGEMAP_WALK_MASK (PMD_MASK)
static ssize_t pagemap_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct task_struct *task = get_proc_task(file->f_path.dentry->d_inode);
struct mm_struct *mm;
struct pagemapread pm;
int ret = -ESRCH;
struct mm_walk pagemap_walk = {};
unsigned long src;
unsigned long svpfn;
unsigned long start_vaddr;
unsigned long end_vaddr;
int copied = 0;
if (!task)
goto out;
mm = mm_for_maps(task);
ret = PTR_ERR(mm);
if (!mm || IS_ERR(mm))
goto out_task;
ret = -EINVAL;
/* file position must be aligned */
if ((*ppos % PM_ENTRY_BYTES) || (count % PM_ENTRY_BYTES))
goto out_task;
ret = 0;
if (!count)
goto out_task;
pm.len = PM_ENTRY_BYTES * (PAGEMAP_WALK_SIZE >> PAGE_SHIFT);
pm.buffer = kmalloc(pm.len, GFP_TEMPORARY);
ret = -ENOMEM;
if (!pm.buffer)
goto out_mm;
pagemap_walk.pmd_entry = pagemap_pte_range;
pagemap_walk.pte_hole = pagemap_pte_hole;
#ifdef CONFIG_HUGETLB_PAGE
pagemap_walk.hugetlb_entry = pagemap_hugetlb_range;
#endif
pagemap_walk.mm = mm;
pagemap_walk.private = ±
src = *ppos;
svpfn = src / PM_ENTRY_BYTES;
start_vaddr = svpfn << PAGE_SHIFT;
end_vaddr = TASK_SIZE_OF(task);
/* watch out for wraparound */
if (svpfn > TASK_SIZE_OF(task) >> PAGE_SHIFT)
start_vaddr = end_vaddr;
/*
* The odds are that this will stop walking way
* before end_vaddr, because the length of the
* user buffer is tracked in "pm", and the walk
* will stop when we hit the end of the buffer.
*/
ret = 0;
while (count && (start_vaddr < end_vaddr)) {
int len;
unsigned long end;
pm.pos = 0;
end = (start_vaddr + PAGEMAP_WALK_SIZE) & PAGEMAP_WALK_MASK;
/* overflow ? */
if (end < start_vaddr || end > end_vaddr)
end = end_vaddr;
down_read(&mm->mmap_sem);
ret = walk_page_range(start_vaddr, end, &pagemap_walk);
up_read(&mm->mmap_sem);
start_vaddr = end;
len = min(count, PM_ENTRY_BYTES * pm.pos);
if (copy_to_user(buf, pm.buffer, len)) {
ret = -EFAULT;
goto out_free;
}
copied += len;
buf += len;
count -= len;
}
*ppos += copied;
if (!ret || ret == PM_END_OF_BUFFER)
ret = copied;
out_free:
kfree(pm.buffer);
out_mm:
mmput(mm);
out_task:
put_task_struct(task);
out:
return ret;
}
const struct file_operations proc_pagemap_operations = {
.llseek = mem_lseek, /* borrow this */
.read = pagemap_read,
};
#endif /* CONFIG_PROC_PAGE_MONITOR */
#ifdef CONFIG_NUMA
extern int show_numa_map(struct seq_file *m, void *v);
static const struct seq_operations proc_pid_numa_maps_op = {
.start = m_start,
.next = m_next,
.stop = m_stop,
.show = show_numa_map,
};
static int numa_maps_open(struct inode *inode, struct file *file)
{
return do_maps_open(inode, file, &proc_pid_numa_maps_op);
}
const struct file_operations proc_numa_maps_operations = {
.open = numa_maps_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3516_0 |
crossvul-cpp_data_good_4782_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M AAA GGGG IIIII CCCC K K %
% MM MM A A G I C K K %
% M M M AAAAA G GGG I C KKK %
% M M A A G G I C K K %
% M M A A GGGG IIIII CCCC K K %
% %
% CCCC L IIIII %
% C L I %
% C L I %
% C L I %
% CCCC LLLLL IIIII %
% %
% Perform "Magick" on Images via the Command Line Interface %
% %
% Dragon Computing %
% Anthony Thyssen %
% January 2012 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Read CLI arguments, script files, and pipelines, to provide options that
% manipulate images from many different formats.
%
*/
/*
Include declarations.
*/
#include "MagickWand/studio.h"
#include "MagickWand/MagickWand.h"
#include "MagickWand/magick-wand-private.h"
#include "MagickWand/wandcli.h"
#include "MagickWand/wandcli-private.h"
#include "MagickWand/operation.h"
#include "MagickWand/magick-cli.h"
#include "MagickWand/script-token.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/version.h"
/* verbose debugging,
0 - no debug lines
3 - show option details (better to use -debug Command now)
5 - image counts (after option runs)
*/
#define MagickCommandDebug 0
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r o c e s s S c r i p t O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ProcessScriptOptions() reads options and processes options as they are
% found in the given file, or pipeline. The filename to open and read
% options is given as the 'index' argument of the argument array given.
%
% Other arguments following index may be read by special script options
% as settings (strings), images, or as operations to be processed in various
% ways. How they are treated is up to the script being processed.
%
% Note that a script not 'return' to the command line processing, nor can
% they call (and return from) other scripts. At least not at this time.
%
% There are no 'ProcessOptionFlags' control flags at this time.
%
% The format of the ProcessScriptOptions method is:
%
% void ProcessScriptOptions(MagickCLI *cli_wand,const char *filename,
% int argc,char **argv,int index)
%
% A description of each parameter follows:
%
% o cli_wand: the main CLI Wand to use.
%
% o filename: the filename of script to process
%
% o argc: the number of elements in the argument vector. (optional)
%
% o argv: A text array containing the command line arguments. (optional)
%
% o index: offset of next argment in argv (script arguments) (optional)
%
*/
WandExport void ProcessScriptOptions(MagickCLI *cli_wand,const char *filename,
int argc,char **argv,int index)
{
ScriptTokenInfo
*token_info;
CommandOptionFlags
option_type;
int
count;
char
*option,
*arg1,
*arg2;
assert(filename != (char *) NULL ); /* at least one argument - script name */
assert(cli_wand != (MagickCLI *) NULL);
assert(cli_wand->signature == MagickWandSignature);
if (cli_wand->wand.debug != MagickFalse)
(void) LogMagickEvent(CommandEvent,GetMagickModule(),
"Processing script \"%s\"", filename);
/* open file script or stream, and set up tokenizer */
token_info = AcquireScriptTokenInfo(filename);
if (token_info == (ScriptTokenInfo *) NULL) {
CLIWandExceptionFile(OptionFatalError,"UnableToOpenScript",filename);
return;
}
/* define the error location string for use in exceptions
order of localtion format escapes: filename, line, column */
cli_wand->location="in \"%s\" at line %u,column %u";
if ( LocaleCompare("-", filename) == 0 )
cli_wand->filename="stdin";
else
cli_wand->filename=filename;
/* Process Options from Script */
option = arg1 = arg2 = (char*) NULL;
DisableMSCWarning(4127)
while (1) {
RestoreMSCWarning
{ MagickBooleanType status = GetScriptToken(token_info);
cli_wand->line=token_info->token_line;
cli_wand->column=token_info->token_column;
if (status == MagickFalse)
break; /* error or end of options */
}
do { /* use break to loop to exception handler and loop */
/* save option details */
CloneString(&option,token_info->token);
/* get option, its argument count, and option type */
cli_wand->command = GetCommandOptionInfo(option);
count=cli_wand->command->type;
option_type=(CommandOptionFlags) cli_wand->command->flags;
#if 0
(void) FormatLocaleFile(stderr, "Script: %u,%u: \"%s\" matched \"%s\"\n",
cli_wand->line, cli_wand->line, option, cli_wand->command->mnemonic );
#endif
/* handle a undefined option - image read - always for "magick-script" */
if ( option_type == UndefinedOptionFlag ||
(option_type & NonMagickOptionFlag) != 0 ) {
#if MagickCommandDebug >= 3
(void) FormatLocaleFile(stderr, "Script %u,%u Non-Option: \"%s\"\n",
cli_wand->line, cli_wand->line, option);
#endif
if (IsCommandOption(option) == MagickFalse) {
/* non-option -- treat as a image read */
cli_wand->command=(const OptionInfo *) NULL;
CLIOption(cli_wand,"-read",option);
break; /* next option */
}
CLIWandException(OptionFatalError,"UnrecognizedOption",option);
break; /* next option */
}
if ( count >= 1 ) {
if (GetScriptToken(token_info) == MagickFalse)
CLIWandException(OptionFatalError,"MissingArgument",option);
CloneString(&arg1,token_info->token);
}
else
CloneString(&arg1,(char *) NULL);
if ( count >= 2 ) {
if (GetScriptToken(token_info) == MagickFalse)
CLIWandExceptionBreak(OptionFatalError,"MissingArgument",option);
CloneString(&arg2,token_info->token);
}
else
CloneString(&arg2,(char *) NULL);
/*
Process Options
*/
#if MagickCommandDebug >= 3
(void) FormatLocaleFile(stderr,
"Script %u,%u Option: \"%s\" Count: %d Flags: %04x Args: \"%s\" \"%s\"\n",
cli_wand->line,cli_wand->line,option,count,option_type,arg1,arg2);
#endif
/* Hard Deprecated Options, no code to execute - error */
if ( (option_type & DeprecateOptionFlag) != 0 ) {
CLIWandException(OptionError,"DeprecatedOptionNoCode",option);
break; /* next option */
}
/* MagickCommandGenesis() options have no place in a magick script */
if ( (option_type & GenesisOptionFlag) != 0 ) {
CLIWandException(OptionError,"InvalidUseOfOption",option);
break; /* next option */
}
/* handle any special 'script' options */
if ( (option_type & SpecialOptionFlag) != 0 ) {
if ( LocaleCompare(option,"-exit") == 0 ) {
goto loop_exit; /* break out of loop - return from script */
}
if ( LocaleCompare(option,"-script") == 0 ) {
/* FUTURE: call new script from this script - error for now */
CLIWandException(OptionError,"InvalidUseOfOption",option);
break; /* next option */
}
/* FUTURE: handle special script-argument options here */
/* handle any other special operators now */
CLIWandException(OptionError,"InvalidUseOfOption",option);
break; /* next option */
}
/* Process non-specific Option */
CLIOption(cli_wand, option, arg1, arg2);
(void) fflush(stdout);
(void) fflush(stderr);
DisableMSCWarning(4127)
} while (0); /* break block to next option */
RestoreMSCWarning
#if MagickCommandDebug >= 5
fprintf(stderr, "Script Image Count = %ld\n",
GetImageListLength(cli_wand->wand.images) );
#endif
if (CLICatchException(cli_wand, MagickFalse) != MagickFalse)
break; /* exit loop */
}
/*
Loop exit - check for some tokenization error
*/
loop_exit:
#if MagickCommandDebug >= 3
(void) FormatLocaleFile(stderr, "Script End: %d\n", token_info->status);
#endif
switch( token_info->status ) {
case TokenStatusOK:
case TokenStatusEOF:
if (cli_wand->image_list_stack != (Stack *) NULL)
CLIWandException(OptionError,"UnbalancedParenthesis", "(eof)");
else if (cli_wand->image_info_stack != (Stack *) NULL)
CLIWandException(OptionError,"UnbalancedBraces", "(eof)");
break;
case TokenStatusBadQuotes:
/* Ensure last token has a sane length for error report */
if( strlen(token_info->token) > INITAL_TOKEN_LENGTH-1 ) {
token_info->token[INITAL_TOKEN_LENGTH-4] = '.';
token_info->token[INITAL_TOKEN_LENGTH-3] = '.';
token_info->token[INITAL_TOKEN_LENGTH-2] = '.';
token_info->token[INITAL_TOKEN_LENGTH-1] = '\0';
}
CLIWandException(OptionFatalError,"ScriptUnbalancedQuotes",
token_info->token);
break;
case TokenStatusMemoryFailed:
CLIWandException(OptionFatalError,"ScriptTokenMemoryFailed","");
break;
case TokenStatusBinary:
CLIWandException(OptionFatalError,"ScriptIsBinary","");
break;
}
(void) fflush(stdout);
(void) fflush(stderr);
if (cli_wand->wand.debug != MagickFalse)
(void) LogMagickEvent(CommandEvent,GetMagickModule(),
"Script End \"%s\"", filename);
/* Clean up */
token_info = DestroyScriptTokenInfo(token_info);
CloneString(&option,(char *) NULL);
CloneString(&arg1,(char *) NULL);
CloneString(&arg2,(char *) NULL);
return;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P r o c e s s C o m m a n d O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ProcessCommandOptions() reads and processes arguments in the given
% command line argument array. The 'index' defines where in the array we
% should begin processing
%
% The 'process_flags' can be used to control and limit option processing.
% For example, to only process one option, or how unknown and special options
% are to be handled, and if the last argument in array is to be regarded as a
% final image write argument (filename or special coder).
%
% The format of the ProcessCommandOptions method is:
%
% int ProcessCommandOptions(MagickCLI *cli_wand,int argc,char **argv,
% int index)
%
% A description of each parameter follows:
%
% o cli_wand: the main CLI Wand to use.
%
% o argc: the number of elements in the argument vector.
%
% o argv: A text array containing the command line arguments.
%
% o process_flags: What type of arguments will be processed, ignored
% or return errors.
%
% o index: index in the argv array to start processing from
%
% The function returns the index ot the next option to be processed. This
% is really only releven if process_flags contains a ProcessOneOptionOnly
% flag.
%
*/
WandExport int ProcessCommandOptions(MagickCLI *cli_wand,int argc,char **argv,
int index)
{
const char
*option,
*arg1,
*arg2;
int
i,
end,
count;
CommandOptionFlags
option_type;
assert(argc>=index); /* you may have no arguments left! */
assert(argv != (char **) NULL);
assert(argv[index] != (char *) NULL);
assert(argv[argc-1] != (char *) NULL);
assert(cli_wand != (MagickCLI *) NULL);
assert(cli_wand->signature == MagickWandSignature);
/* define the error location string for use in exceptions
order of localtion format escapes: filename, line, column */
cli_wand->location="at %s arg %u";
cli_wand->filename="CLI";
cli_wand->line=index; /* note first argument we will process */
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- Starting (\"%s\")", argv[index]);
end = argc;
if ( (cli_wand->process_flags & ProcessImplictWrite) != 0 )
end--; /* the last arument is an implied write, do not process directly */
for (i=index; i < end; i += count +1) {
/* Finished processing one option? */
if ( (cli_wand->process_flags & ProcessOneOptionOnly) != 0 && i != index )
return(i);
do { /* use break to loop to exception handler and loop */
option=argv[i];
cli_wand->line=i; /* note the argument for this option */
/* get option, its argument count, and option type */
cli_wand->command = GetCommandOptionInfo(argv[i]);
count=cli_wand->command->type;
option_type=(CommandOptionFlags) cli_wand->command->flags;
#if 0
(void) FormatLocaleFile(stderr, "CLI %d: \"%s\" matched \"%s\"\n",
i, argv[i], cli_wand->command->mnemonic );
#endif
if ( option_type == UndefinedOptionFlag ||
(option_type & NonMagickOptionFlag) != 0 ) {
#if MagickCommandDebug >= 3
(void) FormatLocaleFile(stderr, "CLI arg %d Non-Option: \"%s\"\n",
i, option);
#endif
if (IsCommandOption(option) == MagickFalse) {
if ( (cli_wand->process_flags & ProcessImplictRead) != 0 ) {
/* non-option -- treat as a image read */
cli_wand->command=(const OptionInfo *) NULL;
CLIOption(cli_wand,"-read",option);
break; /* next option */
}
}
CLIWandException(OptionFatalError,"UnrecognizedOption",option);
break; /* next option */
}
if ( ((option_type & SpecialOptionFlag) != 0 ) &&
((cli_wand->process_flags & ProcessScriptOption) != 0) &&
(LocaleCompare(option,"-script") == 0) ) {
/* Call Script from CLI, with a filename as a zeroth argument.
NOTE: -script may need to use the 'implict write filename' argument
so it must be handled specially to prevent a 'missing argument' error.
*/
if ( (i+count) >= argc )
CLIWandException(OptionFatalError,"MissingArgument",option);
ProcessScriptOptions(cli_wand,argv[i+1],argc,argv,i+count);
return(argc); /* Script does not return to CLI -- Yet */
/* FUTURE: when it does, their may be no write arg! */
}
if ((i+count) >= end ) {
CLIWandException(OptionFatalError,"MissingArgument",option);
if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse )
return(end);
break; /* next option - not that their is any! */
}
arg1 = ( count >= 1 ) ? argv[i+1] : (char *) NULL;
arg2 = ( count >= 2 ) ? argv[i+2] : (char *) NULL;
/*
Process Known Options
*/
#if MagickCommandDebug >= 3
(void) FormatLocaleFile(stderr,
"CLI arg %u Option: \"%s\" Count: %d Flags: %04x Args: \"%s\" \"%s\"\n",
i,option,count,option_type,arg1,arg2);
#endif
/* ignore 'genesis options' in command line args */
if ( (option_type & GenesisOptionFlag) != 0 )
break; /* next option */
/* Handle any special options for CLI (-script handled above) */
if ( (option_type & SpecialOptionFlag) != 0 ) {
if ( (cli_wand->process_flags & ProcessExitOption) != 0
&& LocaleCompare(option,"-exit") == 0 )
return(i+count);
break; /* next option */
}
/* Process standard image option */
CLIOption(cli_wand, option, arg1, arg2);
DisableMSCWarning(4127)
} while (0); /* break block to next option */
RestoreMSCWarning
#if MagickCommandDebug >= 5
(void) FormatLocaleFile(stderr, "CLI-post Image Count = %ld\n",
(long) GetImageListLength(cli_wand->wand.images) );
#endif
if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse )
return(i+count);
}
assert(i==end);
if ( (cli_wand->process_flags & ProcessImplictWrite) == 0 )
return(end); /* no implied write -- just return to caller */
assert(end==argc-1); /* end should not include last argument */
/*
Implicit Write of images to final CLI argument
*/
option=argv[i];
cli_wand->line=i;
/* check that stacks are empty - or cause exception */
if (cli_wand->image_list_stack != (Stack *) NULL)
CLIWandException(OptionError,"UnbalancedParenthesis", "(end of cli)");
else if (cli_wand->image_info_stack != (Stack *) NULL)
CLIWandException(OptionError,"UnbalancedBraces", "(end of cli)");
if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse )
return(argc);
#if MagickCommandDebug >= 3
(void) FormatLocaleFile(stderr,"CLI arg %d Write File: \"%s\"\n",i,option);
#endif
/* Valid 'do no write' replacement option (instead of "null:") */
if (LocaleCompare(option,"-exit") == 0 )
return(argc); /* just exit, no image write */
/* If filename looks like an option,
Or the common 'end of line' error of a single space.
-- produce an error */
if (IsCommandOption(option) != MagickFalse ||
(option[0] == ' ' && option[1] == '\0') ) {
CLIWandException(OptionError,"MissingOutputFilename",option);
return(argc);
}
cli_wand->command=(const OptionInfo *) NULL;
CLIOption(cli_wand,"-write",option);
return(argc);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ M a g i c k I m a g e C o m m a n d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagickImageCommand() Handle special use CLI arguments and prepare a
% CLI MagickCLI to process the command line or directly specified script.
%
% This is essentualy interface function between the MagickCore library
% initialization function MagickCommandGenesis(), and the option MagickCLI
% processing functions ProcessCommandOptions() or ProcessScriptOptions()
%
% The format of the MagickImageCommand method is:
%
% MagickBooleanType MagickImageCommand(ImageInfo *image_info,int argc,
% char **argv,char **metadata,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the starting image_info structure
% (for compatibilty with MagickCommandGenisis())
%
% o argc: the number of elements in the argument vector.
%
% o argv: A text array containing the command line arguments.
%
% o metadata: any metadata (for VBS) is returned here.
% (for compatibilty with MagickCommandGenisis())
%
% o exception: return any errors or warnings in this structure.
%
*/
static void MagickUsage(MagickBooleanType verbose)
{
const char
*name;
size_t
len;
name=GetClientName();
len=strlen(name);
if (len>=7 && LocaleCompare("convert",name+len-7) == 0) {
/* convert usage */
(void) FormatLocaleFile(stdout,
"Usage: %s [ {option} | {image} ... ] {output_image}\n",name);
(void) FormatLocaleFile(stdout,
" %s -help | -version | -usage | -list {option}\n\n",name);
return;
}
else if (len>=6 && LocaleCompare("script",name+len-6) == 0) {
/* magick-script usage */
(void) FormatLocaleFile(stdout,
"Usage: %s {filename} [ {script_args} ... ]\n",name);
}
else {
/* magick usage */
(void) FormatLocaleFile(stdout,
"Usage: %s [ {option} | {image} ... ] {output_image}\n",name);
(void) FormatLocaleFile(stdout,
" %s [ {option} | {image} ... ] -script {filename} [ {script_args} ...]\n",
name);
}
(void) FormatLocaleFile(stdout,
" %s -help | -version | -usage | -list {option}\n\n",name);
if (verbose == MagickFalse)
return;
(void) FormatLocaleFile(stdout,"%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
"All options are performed in a strict 'as you see them' order\n",
"You must read-in images before you can operate on them.\n",
"\n",
"Magick Script files can use any of the following forms...\n",
" #!/path/to/magick -script\n",
"or\n",
" #!/bin/sh\n",
" :; exec magick -script \"$0\" \"$@\"; exit 10\n",
" # Magick script from here...\n",
"or\n",
" #!/usr/bin/env magick-script\n",
"The latter two forms do not require the path to the command hard coded.\n",
"Note: \"magick-script\" needs to be linked to the \"magick\" command.\n",
"\n",
"For more information on usage, options, examples, and techniques\n",
"see the ImageMagick website at ", MagickAuthoritativeURL);
return;
}
/*
Concatanate given file arguments to the given output argument.
Used for a special -concatenate option used for specific 'delegates'.
The option is not formally documented.
magick -concatenate files... output
This is much like the UNIX "cat" command, but for both UNIX and Windows,
however the last argument provides the output filename.
*/
static MagickBooleanType ConcatenateImages(int argc,char **argv,
ExceptionInfo *exception )
{
FILE
*input,
*output;
MagickBooleanType
status;
int
c;
register ssize_t
i;
if (ExpandFilenames(&argc,&argv) == MagickFalse)
ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed",
GetExceptionMessage(errno));
output=fopen_utf8(argv[argc-1],"wb");
if (output == (FILE *) NULL)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
argv[argc-1]);
return(MagickFalse);
}
status=MagickTrue;
for (i=2; i < (ssize_t) (argc-1); i++)
{
input=fopen_utf8(argv[i],"rb");
if (input == (FILE *) NULL)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]);
continue;
}
for (c=fgetc(input); c != EOF; c=fgetc(input))
if (fputc((char) c,output) != c)
status=MagickFalse;
(void) fclose(input);
(void) remove_utf8(argv[i]);
}
(void) fclose(output);
return(status);
}
WandExport MagickBooleanType MagickImageCommand(ImageInfo *image_info,int argc,
char **argv,char **metadata,ExceptionInfo *exception)
{
MagickCLI
*cli_wand;
size_t
len;
assert(image_info != (ImageInfo *) NULL);
/* For specific OS command line requirements */
ReadCommandlLine(argc,&argv);
/* Initialize special "CLI Wand" to hold images and settings (empty) */
cli_wand=AcquireMagickCLI(image_info,exception);
cli_wand->location="Initializing";
cli_wand->filename=argv[0];
cli_wand->line=1;
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"\"%s\"",argv[0]);
GetPathComponent(argv[0],TailPath,cli_wand->wand.name);
SetClientName(cli_wand->wand.name);
ConcatenateMagickString(cli_wand->wand.name,"-CLI",MagickPathExtent);
len=strlen(argv[0]); /* precaution */
/* "convert" command - give a "deprecated" warning" */
if (len>=7 && LocaleCompare("convert",argv[0]+len-7) == 0) {
cli_wand->process_flags = ConvertCommandOptionFlags;
(void) FormatLocaleFile(stderr,"WARNING: %s\n",
"The convert command is deprecated in IMv7, use \"magick\"\n");
}
/* Special Case: If command name ends with "script" implied "-script" */
if (len>=6 && LocaleCompare("script",argv[0]+len-6) == 0) {
if (argc >= 2 && ( (*(argv[1]) != '-') || (strlen(argv[1]) == 1) )) {
GetPathComponent(argv[1],TailPath,cli_wand->wand.name);
ProcessScriptOptions(cli_wand,argv[1],argc,argv,2);
goto Magick_Command_Cleanup;
}
}
/* Special Case: Version Information and Abort */
if (argc == 2) {
if ((LocaleCompare("-version",argv[1]) == 0) || /* GNU standard option */
(LocaleCompare("--version",argv[1]) == 0) ) { /* just version */
CLIOption(cli_wand, "-version");
goto Magick_Command_Exit;
}
if ((LocaleCompare("-help",argv[1]) == 0) || /* GNU standard option */
(LocaleCompare("--help",argv[1]) == 0) ) { /* just a brief summary */
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- Special Option \"%s\"", argv[1]);
MagickUsage(MagickFalse);
goto Magick_Command_Exit;
}
if (LocaleCompare("-usage",argv[1]) == 0) { /* both version & usage */
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- Special Option \"%s\"", argv[1]);
CLIOption(cli_wand, "-version" );
MagickUsage(MagickTrue);
goto Magick_Command_Exit;
}
}
/* not enough arguments -- including -help */
if (argc < 3) {
(void) FormatLocaleFile(stderr,
"Error: Invalid argument or not enough arguments\n\n");
MagickUsage(MagickFalse);
goto Magick_Command_Exit;
}
/* Special "concatenate option (hidden) for delegate usage */
if (LocaleCompare("-concatenate",argv[1]) == 0) {
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- Special Option \"%s\"", argv[1]);
ConcatenateImages(argc,argv,exception);
goto Magick_Command_Exit;
}
/* List Information and Abort */
if (argc == 3 && LocaleCompare("-list",argv[1]) == 0) {
CLIOption(cli_wand, argv[1], argv[2]);
goto Magick_Command_Exit;
}
/* ------------- */
/* The Main Call */
if (LocaleCompare("-script",argv[1]) == 0) {
/* Start processing directly from script, no pre-script options
Replace wand command name with script name
First argument in the argv array is the script name to read.
*/
GetPathComponent(argv[2],TailPath,cli_wand->wand.name);
ProcessScriptOptions(cli_wand,argv[2],argc,argv,3);
}
else {
/* Normal Command Line, assumes output file as last option */
ProcessCommandOptions(cli_wand,argc,argv,1);
}
/* ------------- */
Magick_Command_Cleanup:
cli_wand->location="Cleanup";
cli_wand->filename=argv[0];
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"\"%s\"",argv[0]);
/* recover original image_info and clean up stacks
FUTURE: "-reset stacks" option */
while ((cli_wand->image_list_stack != (Stack *) NULL) &&
(cli_wand->image_list_stack->next != (Stack *) NULL))
CLIOption(cli_wand,")");
while ((cli_wand->image_info_stack != (Stack *) NULL) &&
(cli_wand->image_info_stack->next != (Stack *) NULL))
CLIOption(cli_wand,"}");
/* assert we have recovered the original structures */
assert(cli_wand->wand.image_info == image_info);
assert(cli_wand->wand.exception == exception);
/* Handle metadata for ImageMagickObject COM object for Windows VBS */
if (metadata != (char **) NULL) {
const char
*format;
char
*text;
format="%w,%h,%m"; // Get this from image_info Option splaytree
text=InterpretImageProperties(image_info,cli_wand->wand.images,format,
exception);
if (text == (char *) NULL)
ThrowMagickException(exception,GetMagickModule(),ResourceLimitError,
"MemoryAllocationFailed","`%s'", GetExceptionMessage(errno));
else {
(void) ConcatenateString(&(*metadata),text);
text=DestroyString(text);
}
}
Magick_Command_Exit:
cli_wand->location="Exiting";
cli_wand->filename=argv[0];
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"\"%s\"",argv[0]);
/* Destroy the special CLI Wand */
cli_wand->wand.image_info = (ImageInfo *) NULL; /* not these */
cli_wand->wand.exception = (ExceptionInfo *) NULL;
cli_wand=DestroyMagickCLI(cli_wand);
return(exception->severity < ErrorException ? MagickTrue : MagickFalse);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4782_0 |
crossvul-cpp_data_bad_5533_1 | #include "redis.h"
#include <sys/uio.h>
void *dupClientReplyValue(void *o) {
incrRefCount((robj*)o);
return o;
}
int listMatchObjects(void *a, void *b) {
return equalStringObjects(a,b);
}
redisClient *createClient(int fd) {
redisClient *c = zmalloc(sizeof(redisClient));
c->bufpos = 0;
anetNonBlock(NULL,fd);
anetTcpNoDelay(NULL,fd);
if (!c) return NULL;
if (aeCreateFileEvent(server.el,fd,AE_READABLE,
readQueryFromClient, c) == AE_ERR)
{
close(fd);
zfree(c);
return NULL;
}
selectDb(c,0);
c->fd = fd;
c->querybuf = sdsempty();
c->reqtype = 0;
c->argc = 0;
c->argv = NULL;
c->multibulklen = 0;
c->bulklen = -1;
c->sentlen = 0;
c->flags = 0;
c->lastinteraction = time(NULL);
c->authenticated = 0;
c->replstate = REDIS_REPL_NONE;
c->reply = listCreate();
listSetFreeMethod(c->reply,decrRefCount);
listSetDupMethod(c->reply,dupClientReplyValue);
c->bpop.keys = NULL;
c->bpop.count = 0;
c->bpop.timeout = 0;
c->bpop.target = NULL;
c->io_keys = listCreate();
c->watched_keys = listCreate();
listSetFreeMethod(c->io_keys,decrRefCount);
c->pubsub_channels = dictCreate(&setDictType,NULL);
c->pubsub_patterns = listCreate();
listSetFreeMethod(c->pubsub_patterns,decrRefCount);
listSetMatchMethod(c->pubsub_patterns,listMatchObjects);
listAddNodeTail(server.clients,c);
initClientMultiState(c);
return c;
}
/* Set the event loop to listen for write events on the client's socket.
* Typically gets called every time a reply is built. */
int _installWriteEvent(redisClient *c) {
/* When CLOSE_AFTER_REPLY is set, no more replies may be added! */
redisAssert(!(c->flags & REDIS_CLOSE_AFTER_REPLY));
if (c->fd <= 0) return REDIS_ERR;
if (c->bufpos == 0 && listLength(c->reply) == 0 &&
(c->replstate == REDIS_REPL_NONE ||
c->replstate == REDIS_REPL_ONLINE) &&
aeCreateFileEvent(server.el, c->fd, AE_WRITABLE,
sendReplyToClient, c) == AE_ERR) return REDIS_ERR;
return REDIS_OK;
}
/* Create a duplicate of the last object in the reply list when
* it is not exclusively owned by the reply list. */
robj *dupLastObjectIfNeeded(list *reply) {
robj *new, *cur;
listNode *ln;
redisAssert(listLength(reply) > 0);
ln = listLast(reply);
cur = listNodeValue(ln);
if (cur->refcount > 1) {
new = dupStringObject(cur);
decrRefCount(cur);
listNodeValue(ln) = new;
}
return listNodeValue(ln);
}
int _addReplyToBuffer(redisClient *c, char *s, size_t len) {
size_t available = sizeof(c->buf)-c->bufpos;
/* If there already are entries in the reply list, we cannot
* add anything more to the static buffer. */
if (listLength(c->reply) > 0) return REDIS_ERR;
/* Check that the buffer has enough space available for this string. */
if (len > available) return REDIS_ERR;
memcpy(c->buf+c->bufpos,s,len);
c->bufpos+=len;
return REDIS_OK;
}
void _addReplyObjectToList(redisClient *c, robj *o) {
robj *tail;
if (listLength(c->reply) == 0) {
incrRefCount(o);
listAddNodeTail(c->reply,o);
} else {
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
if (tail->ptr != NULL &&
sdslen(tail->ptr)+sdslen(o->ptr) <= REDIS_REPLY_CHUNK_BYTES)
{
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr));
} else {
incrRefCount(o);
listAddNodeTail(c->reply,o);
}
}
}
/* This method takes responsibility over the sds. When it is no longer
* needed it will be free'd, otherwise it ends up in a robj. */
void _addReplySdsToList(redisClient *c, sds s) {
robj *tail;
if (listLength(c->reply) == 0) {
listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
} else {
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
if (tail->ptr != NULL &&
sdslen(tail->ptr)+sdslen(s) <= REDIS_REPLY_CHUNK_BYTES)
{
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,s,sdslen(s));
sdsfree(s);
} else {
listAddNodeTail(c->reply,createObject(REDIS_STRING,s));
}
}
}
void _addReplyStringToList(redisClient *c, char *s, size_t len) {
robj *tail;
if (listLength(c->reply) == 0) {
listAddNodeTail(c->reply,createStringObject(s,len));
} else {
tail = listNodeValue(listLast(c->reply));
/* Append to this object when possible. */
if (tail->ptr != NULL &&
sdslen(tail->ptr)+len <= REDIS_REPLY_CHUNK_BYTES)
{
tail = dupLastObjectIfNeeded(c->reply);
tail->ptr = sdscatlen(tail->ptr,s,len);
} else {
listAddNodeTail(c->reply,createStringObject(s,len));
}
}
}
void addReply(redisClient *c, robj *obj) {
if (_installWriteEvent(c) != REDIS_OK) return;
redisAssert(!server.vm_enabled || obj->storage == REDIS_VM_MEMORY);
/* This is an important place where we can avoid copy-on-write
* when there is a saving child running, avoiding touching the
* refcount field of the object if it's not needed.
*
* If the encoding is RAW and there is room in the static buffer
* we'll be able to send the object to the client without
* messing with its page. */
if (obj->encoding == REDIS_ENCODING_RAW) {
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
_addReplyObjectToList(c,obj);
} else {
/* FIXME: convert the long into string and use _addReplyToBuffer()
* instead of calling getDecodedObject. As this place in the
* code is too performance critical. */
obj = getDecodedObject(obj);
if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != REDIS_OK)
_addReplyObjectToList(c,obj);
decrRefCount(obj);
}
}
void addReplySds(redisClient *c, sds s) {
if (_installWriteEvent(c) != REDIS_OK) {
/* The caller expects the sds to be free'd. */
sdsfree(s);
return;
}
if (_addReplyToBuffer(c,s,sdslen(s)) == REDIS_OK) {
sdsfree(s);
} else {
/* This method free's the sds when it is no longer needed. */
_addReplySdsToList(c,s);
}
}
void addReplyString(redisClient *c, char *s, size_t len) {
if (_installWriteEvent(c) != REDIS_OK) return;
if (_addReplyToBuffer(c,s,len) != REDIS_OK)
_addReplyStringToList(c,s,len);
}
void _addReplyError(redisClient *c, char *s, size_t len) {
addReplyString(c,"-ERR ",5);
addReplyString(c,s,len);
addReplyString(c,"\r\n",2);
}
void addReplyError(redisClient *c, char *err) {
_addReplyError(c,err,strlen(err));
}
void addReplyErrorFormat(redisClient *c, const char *fmt, ...) {
va_list ap;
va_start(ap,fmt);
sds s = sdscatvprintf(sdsempty(),fmt,ap);
va_end(ap);
_addReplyError(c,s,sdslen(s));
sdsfree(s);
}
void _addReplyStatus(redisClient *c, char *s, size_t len) {
addReplyString(c,"+",1);
addReplyString(c,s,len);
addReplyString(c,"\r\n",2);
}
void addReplyStatus(redisClient *c, char *status) {
_addReplyStatus(c,status,strlen(status));
}
void addReplyStatusFormat(redisClient *c, const char *fmt, ...) {
va_list ap;
va_start(ap,fmt);
sds s = sdscatvprintf(sdsempty(),fmt,ap);
va_end(ap);
_addReplyStatus(c,s,sdslen(s));
sdsfree(s);
}
/* Adds an empty object to the reply list that will contain the multi bulk
* length, which is not known when this function is called. */
void *addDeferredMultiBulkLength(redisClient *c) {
/* Note that we install the write event here even if the object is not
* ready to be sent, since we are sure that before returning to the
* event loop setDeferredMultiBulkLength() will be called. */
if (_installWriteEvent(c) != REDIS_OK) return NULL;
listAddNodeTail(c->reply,createObject(REDIS_STRING,NULL));
return listLast(c->reply);
}
/* Populate the length object and try glueing it to the next chunk. */
void setDeferredMultiBulkLength(redisClient *c, void *node, long length) {
listNode *ln = (listNode*)node;
robj *len, *next;
/* Abort when *node is NULL (see addDeferredMultiBulkLength). */
if (node == NULL) return;
len = listNodeValue(ln);
len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length);
if (ln->next != NULL) {
next = listNodeValue(ln->next);
/* Only glue when the next node is non-NULL (an sds in this case) */
if (next->ptr != NULL) {
len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr));
listDelNode(c->reply,ln->next);
}
}
}
/* Add a duble as a bulk reply */
void addReplyDouble(redisClient *c, double d) {
char dbuf[128], sbuf[128];
int dlen, slen;
dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d);
slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf);
addReplyString(c,sbuf,slen);
}
/* Add a long long as integer reply or bulk len / multi bulk count.
* Basically this is used to output <prefix><long long><crlf>. */
void _addReplyLongLong(redisClient *c, long long ll, char prefix) {
char buf[128];
int len;
buf[0] = prefix;
len = ll2string(buf+1,sizeof(buf)-1,ll);
buf[len+1] = '\r';
buf[len+2] = '\n';
addReplyString(c,buf,len+3);
}
void addReplyLongLong(redisClient *c, long long ll) {
_addReplyLongLong(c,ll,':');
}
void addReplyMultiBulkLen(redisClient *c, long length) {
_addReplyLongLong(c,length,'*');
}
/* Create the length prefix of a bulk reply, example: $2234 */
void addReplyBulkLen(redisClient *c, robj *obj) {
size_t len;
if (obj->encoding == REDIS_ENCODING_RAW) {
len = sdslen(obj->ptr);
} else {
long n = (long)obj->ptr;
/* Compute how many bytes will take this integer as a radix 10 string */
len = 1;
if (n < 0) {
len++;
n = -n;
}
while((n = n/10) != 0) {
len++;
}
}
_addReplyLongLong(c,len,'$');
}
/* Add a Redis Object as a bulk reply */
void addReplyBulk(redisClient *c, robj *obj) {
addReplyBulkLen(c,obj);
addReply(c,obj);
addReply(c,shared.crlf);
}
/* Add a C buffer as bulk reply */
void addReplyBulkCBuffer(redisClient *c, void *p, size_t len) {
_addReplyLongLong(c,len,'$');
addReplyString(c,p,len);
addReply(c,shared.crlf);
}
/* Add a C nul term string as bulk reply */
void addReplyBulkCString(redisClient *c, char *s) {
if (s == NULL) {
addReply(c,shared.nullbulk);
} else {
addReplyBulkCBuffer(c,s,strlen(s));
}
}
/* Add a long long as a bulk reply */
void addReplyBulkLongLong(redisClient *c, long long ll) {
char buf[64];
int len;
len = ll2string(buf,64,ll);
addReplyBulkCBuffer(c,buf,len);
}
static void acceptCommonHandler(int fd) {
redisClient *c;
if ((c = createClient(fd)) == NULL) {
redisLog(REDIS_WARNING,"Error allocating resoures for the client");
close(fd); /* May be already closed, just ingore errors */
return;
}
/* If maxclient directive is set and this is one client more... close the
* connection. Note that we create the client instead to check before
* for this condition, since now the socket is already set in nonblocking
* mode and we can send an error for free using the Kernel I/O */
if (server.maxclients && listLength(server.clients) > server.maxclients) {
char *err = "-ERR max number of clients reached\r\n";
/* That's a best effort error message, don't check write errors */
if (write(c->fd,err,strlen(err)) == -1) {
/* Nothing to do, Just to avoid the warning... */
}
freeClient(c);
return;
}
server.stat_numconnections++;
}
void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
int cport, cfd;
char cip[128];
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
REDIS_NOTUSED(privdata);
cfd = anetTcpAccept(server.neterr, fd, cip, &cport);
if (cfd == AE_ERR) {
redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
return;
}
redisLog(REDIS_VERBOSE,"Accepted %s:%d", cip, cport);
acceptCommonHandler(cfd);
}
void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) {
int cfd;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
REDIS_NOTUSED(privdata);
cfd = anetUnixAccept(server.neterr, fd);
if (cfd == AE_ERR) {
redisLog(REDIS_VERBOSE,"Accepting client connection: %s", server.neterr);
return;
}
redisLog(REDIS_VERBOSE,"Accepted connection to %s", server.unixsocket);
acceptCommonHandler(cfd);
}
static void freeClientArgv(redisClient *c) {
int j;
for (j = 0; j < c->argc; j++)
decrRefCount(c->argv[j]);
c->argc = 0;
}
void freeClient(redisClient *c) {
listNode *ln;
/* Note that if the client we are freeing is blocked into a blocking
* call, we have to set querybuf to NULL *before* to call
* unblockClientWaitingData() to avoid processInputBuffer() will get
* called. Also it is important to remove the file events after
* this, because this call adds the READABLE event. */
sdsfree(c->querybuf);
c->querybuf = NULL;
if (c->flags & REDIS_BLOCKED)
unblockClientWaitingData(c);
/* UNWATCH all the keys */
unwatchAllKeys(c);
listRelease(c->watched_keys);
/* Unsubscribe from all the pubsub channels */
pubsubUnsubscribeAllChannels(c,0);
pubsubUnsubscribeAllPatterns(c,0);
dictRelease(c->pubsub_channels);
listRelease(c->pubsub_patterns);
/* Obvious cleanup */
aeDeleteFileEvent(server.el,c->fd,AE_READABLE);
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
listRelease(c->reply);
freeClientArgv(c);
close(c->fd);
/* Remove from the list of clients */
ln = listSearchKey(server.clients,c);
redisAssert(ln != NULL);
listDelNode(server.clients,ln);
/* Remove from the list of clients waiting for swapped keys, or ready
* to be restarted, but not yet woken up again. */
if (c->flags & REDIS_IO_WAIT) {
redisAssert(server.vm_enabled);
if (listLength(c->io_keys) == 0) {
ln = listSearchKey(server.io_ready_clients,c);
/* When this client is waiting to be woken up (REDIS_IO_WAIT),
* it should be present in the list io_ready_clients */
redisAssert(ln != NULL);
listDelNode(server.io_ready_clients,ln);
} else {
while (listLength(c->io_keys)) {
ln = listFirst(c->io_keys);
dontWaitForSwappedKey(c,ln->value);
}
}
server.vm_blocked_clients--;
}
listRelease(c->io_keys);
/* Master/slave cleanup.
* Case 1: we lost the connection with a slave. */
if (c->flags & REDIS_SLAVE) {
if (c->replstate == REDIS_REPL_SEND_BULK && c->repldbfd != -1)
close(c->repldbfd);
list *l = (c->flags & REDIS_MONITOR) ? server.monitors : server.slaves;
ln = listSearchKey(l,c);
redisAssert(ln != NULL);
listDelNode(l,ln);
}
/* Case 2: we lost the connection with the master. */
if (c->flags & REDIS_MASTER) {
server.master = NULL;
/* FIXME */
server.replstate = REDIS_REPL_CONNECT;
/* Since we lost the connection with the master, we should also
* close the connection with all our slaves if we have any, so
* when we'll resync with the master the other slaves will sync again
* with us as well. Note that also when the slave is not connected
* to the master it will keep refusing connections by other slaves. */
while (listLength(server.slaves)) {
ln = listFirst(server.slaves);
freeClient((redisClient*)ln->value);
}
}
/* Release memory */
zfree(c->argv);
freeClientMultiState(c);
zfree(c);
}
void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) {
redisClient *c = privdata;
int nwritten = 0, totwritten = 0, objlen;
robj *o;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
/* Use writev() if we have enough buffers to send */
if (!server.glueoutputbuf &&
listLength(c->reply) > REDIS_WRITEV_THRESHOLD &&
!(c->flags & REDIS_MASTER))
{
sendReplyToClientWritev(el, fd, privdata, mask);
return;
}
while(c->bufpos > 0 || listLength(c->reply)) {
if (c->bufpos > 0) {
if (c->flags & REDIS_MASTER) {
/* Don't reply to a master */
nwritten = c->bufpos - c->sentlen;
} else {
nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen);
if (nwritten <= 0) break;
}
c->sentlen += nwritten;
totwritten += nwritten;
/* If the buffer was sent, set bufpos to zero to continue with
* the remainder of the reply. */
if (c->sentlen == c->bufpos) {
c->bufpos = 0;
c->sentlen = 0;
}
} else {
o = listNodeValue(listFirst(c->reply));
objlen = sdslen(o->ptr);
if (objlen == 0) {
listDelNode(c->reply,listFirst(c->reply));
continue;
}
if (c->flags & REDIS_MASTER) {
/* Don't reply to a master */
nwritten = objlen - c->sentlen;
} else {
nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen);
if (nwritten <= 0) break;
}
c->sentlen += nwritten;
totwritten += nwritten;
/* If we fully sent the object on head go to the next one */
if (c->sentlen == objlen) {
listDelNode(c->reply,listFirst(c->reply));
c->sentlen = 0;
}
}
/* Note that we avoid to send more thank REDIS_MAX_WRITE_PER_EVENT
* bytes, in a single threaded server it's a good idea to serve
* other clients as well, even if a very large request comes from
* super fast link that is always able to accept data (in real world
* scenario think about 'KEYS *' against the loopback interfae) */
if (totwritten > REDIS_MAX_WRITE_PER_EVENT) break;
}
if (nwritten == -1) {
if (errno == EAGAIN) {
nwritten = 0;
} else {
redisLog(REDIS_VERBOSE,
"Error writing to client: %s", strerror(errno));
freeClient(c);
return;
}
}
if (totwritten > 0) c->lastinteraction = time(NULL);
if (listLength(c->reply) == 0) {
c->sentlen = 0;
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
/* Close connection after entire reply has been sent. */
if (c->flags & REDIS_CLOSE_AFTER_REPLY) freeClient(c);
}
}
void sendReplyToClientWritev(aeEventLoop *el, int fd, void *privdata, int mask)
{
redisClient *c = privdata;
int nwritten = 0, totwritten = 0, objlen, willwrite;
robj *o;
struct iovec iov[REDIS_WRITEV_IOVEC_COUNT];
int offset, ion = 0;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
listNode *node;
while (listLength(c->reply)) {
offset = c->sentlen;
ion = 0;
willwrite = 0;
/* fill-in the iov[] array */
for(node = listFirst(c->reply); node; node = listNextNode(node)) {
o = listNodeValue(node);
objlen = sdslen(o->ptr);
if (totwritten + objlen - offset > REDIS_MAX_WRITE_PER_EVENT)
break;
if(ion == REDIS_WRITEV_IOVEC_COUNT)
break; /* no more iovecs */
iov[ion].iov_base = ((char*)o->ptr) + offset;
iov[ion].iov_len = objlen - offset;
willwrite += objlen - offset;
offset = 0; /* just for the first item */
ion++;
}
if(willwrite == 0)
break;
/* write all collected blocks at once */
if((nwritten = writev(fd, iov, ion)) < 0) {
if (errno != EAGAIN) {
redisLog(REDIS_VERBOSE,
"Error writing to client: %s", strerror(errno));
freeClient(c);
return;
}
break;
}
totwritten += nwritten;
offset = c->sentlen;
/* remove written robjs from c->reply */
while (nwritten && listLength(c->reply)) {
o = listNodeValue(listFirst(c->reply));
objlen = sdslen(o->ptr);
if(nwritten >= objlen - offset) {
listDelNode(c->reply, listFirst(c->reply));
nwritten -= objlen - offset;
c->sentlen = 0;
} else {
/* partial write */
c->sentlen += nwritten;
break;
}
offset = 0;
}
}
if (totwritten > 0)
c->lastinteraction = time(NULL);
if (listLength(c->reply) == 0) {
c->sentlen = 0;
aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE);
}
}
/* resetClient prepare the client to process the next command */
void resetClient(redisClient *c) {
freeClientArgv(c);
c->reqtype = 0;
c->multibulklen = 0;
c->bulklen = -1;
}
void closeTimedoutClients(void) {
redisClient *c;
listNode *ln;
time_t now = time(NULL);
listIter li;
listRewind(server.clients,&li);
while ((ln = listNext(&li)) != NULL) {
c = listNodeValue(ln);
if (server.maxidletime &&
!(c->flags & REDIS_SLAVE) && /* no timeout for slaves */
!(c->flags & REDIS_MASTER) && /* no timeout for masters */
!(c->flags & REDIS_BLOCKED) && /* no timeout for BLPOP */
dictSize(c->pubsub_channels) == 0 && /* no timeout for pubsub */
listLength(c->pubsub_patterns) == 0 &&
(now - c->lastinteraction > server.maxidletime))
{
redisLog(REDIS_VERBOSE,"Closing idle client");
freeClient(c);
} else if (c->flags & REDIS_BLOCKED) {
if (c->bpop.timeout != 0 && c->bpop.timeout < now) {
addReply(c,shared.nullmultibulk);
unblockClientWaitingData(c);
}
}
}
}
int processInlineBuffer(redisClient *c) {
char *newline = strstr(c->querybuf,"\r\n");
int argc, j;
sds *argv;
size_t querylen;
/* Nothing to do without a \r\n */
if (newline == NULL)
return REDIS_ERR;
/* Split the input buffer up to the \r\n */
querylen = newline-(c->querybuf);
argv = sdssplitlen(c->querybuf,querylen," ",1,&argc);
/* Leave data after the first line of the query in the buffer */
c->querybuf = sdsrange(c->querybuf,querylen+2,-1);
/* Setup argv array on client structure */
if (c->argv) zfree(c->argv);
c->argv = zmalloc(sizeof(robj*)*argc);
/* Create redis objects for all arguments. */
for (c->argc = 0, j = 0; j < argc; j++) {
if (sdslen(argv[j])) {
c->argv[c->argc] = createObject(REDIS_STRING,argv[j]);
c->argc++;
} else {
sdsfree(argv[j]);
}
}
zfree(argv);
return REDIS_OK;
}
/* Helper function. Trims query buffer to make the function that processes
* multi bulk requests idempotent. */
static void setProtocolError(redisClient *c, int pos) {
c->flags |= REDIS_CLOSE_AFTER_REPLY;
c->querybuf = sdsrange(c->querybuf,pos,-1);
}
int processMultibulkBuffer(redisClient *c) {
char *newline = NULL;
char *eptr;
int pos = 0, tolerr;
long bulklen;
if (c->multibulklen == 0) {
/* The client should have been reset */
redisAssert(c->argc == 0);
/* Multi bulk length cannot be read without a \r\n */
newline = strstr(c->querybuf,"\r\n");
if (newline == NULL)
return REDIS_ERR;
/* We know for sure there is a whole line since newline != NULL,
* so go ahead and find out the multi bulk length. */
redisAssert(c->querybuf[0] == '*');
c->multibulklen = strtol(c->querybuf+1,&eptr,10);
pos = (newline-c->querybuf)+2;
if (c->multibulklen <= 0) {
c->querybuf = sdsrange(c->querybuf,pos,-1);
return REDIS_OK;
} else if (c->multibulklen > 1024*1024) {
addReplyError(c,"Protocol error: invalid multibulk length");
setProtocolError(c,pos);
return REDIS_ERR;
}
/* Setup argv array on client structure */
if (c->argv) zfree(c->argv);
c->argv = zmalloc(sizeof(robj*)*c->multibulklen);
/* Search new newline */
newline = strstr(c->querybuf+pos,"\r\n");
}
redisAssert(c->multibulklen > 0);
while(c->multibulklen) {
/* Read bulk length if unknown */
if (c->bulklen == -1) {
newline = strstr(c->querybuf+pos,"\r\n");
if (newline != NULL) {
if (c->querybuf[pos] != '$') {
addReplyErrorFormat(c,
"Protocol error: expected '$', got '%c'",
c->querybuf[pos]);
setProtocolError(c,pos);
return REDIS_ERR;
}
bulklen = strtol(c->querybuf+pos+1,&eptr,10);
tolerr = (eptr[0] != '\r');
if (tolerr || bulklen == LONG_MIN || bulklen == LONG_MAX ||
bulklen < 0 || bulklen > 512*1024*1024)
{
addReplyError(c,"Protocol error: invalid bulk length");
setProtocolError(c,pos);
return REDIS_ERR;
}
pos += eptr-(c->querybuf+pos)+2;
c->bulklen = bulklen;
} else {
/* No newline in current buffer, so wait for more data */
break;
}
}
/* Read bulk argument */
if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) {
/* Not enough data (+2 == trailing \r\n) */
break;
} else {
c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen);
pos += c->bulklen+2;
c->bulklen = -1;
c->multibulklen--;
}
}
/* Trim to pos */
c->querybuf = sdsrange(c->querybuf,pos,-1);
/* We're done when c->multibulk == 0 */
if (c->multibulklen == 0) {
return REDIS_OK;
}
return REDIS_ERR;
}
void processInputBuffer(redisClient *c) {
/* Keep processing while there is something in the input buffer */
while(sdslen(c->querybuf)) {
/* Immediately abort if the client is in the middle of something. */
if (c->flags & REDIS_BLOCKED || c->flags & REDIS_IO_WAIT) return;
/* REDIS_CLOSE_AFTER_REPLY closes the connection once the reply is
* written to the client. Make sure to not let the reply grow after
* this flag has been set (i.e. don't process more commands). */
if (c->flags & REDIS_CLOSE_AFTER_REPLY) return;
/* Determine request type when unknown. */
if (!c->reqtype) {
if (c->querybuf[0] == '*') {
c->reqtype = REDIS_REQ_MULTIBULK;
} else {
c->reqtype = REDIS_REQ_INLINE;
}
}
if (c->reqtype == REDIS_REQ_INLINE) {
if (processInlineBuffer(c) != REDIS_OK) break;
} else if (c->reqtype == REDIS_REQ_MULTIBULK) {
if (processMultibulkBuffer(c) != REDIS_OK) break;
} else {
redisPanic("Unknown request type");
}
/* Multibulk processing could see a <= 0 length. */
if (c->argc == 0) {
resetClient(c);
} else {
/* Only reset the client when the command was executed. */
if (processCommand(c) == REDIS_OK)
resetClient(c);
}
}
}
void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) {
redisClient *c = (redisClient*) privdata;
char buf[REDIS_IOBUF_LEN];
int nread;
REDIS_NOTUSED(el);
REDIS_NOTUSED(mask);
nread = read(fd, buf, REDIS_IOBUF_LEN);
if (nread == -1) {
if (errno == EAGAIN) {
nread = 0;
} else {
redisLog(REDIS_VERBOSE, "Reading from client: %s",strerror(errno));
freeClient(c);
return;
}
} else if (nread == 0) {
redisLog(REDIS_VERBOSE, "Client closed connection");
freeClient(c);
return;
}
if (nread) {
c->querybuf = sdscatlen(c->querybuf,buf,nread);
c->lastinteraction = time(NULL);
} else {
return;
}
processInputBuffer(c);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5533_1 |
crossvul-cpp_data_good_5109_0 | /* toshiba.c
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "toshiba.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/* This module reads the output of the 'snoop' command in the Toshiba
* TR-600 and TR-650 "Compact" ISDN Routers. You can telnet to the
* router and run 'snoop' on the different channels, and at different
* detail levels. Be sure to choose the 'dump' level to get the hex dump.
* The 'snoop' command has nothing to do with the Solaris 'snoop'
* command, except that they both capture packets.
*/
/*
Example 'snoop' output data:
Script started on Thu Sep 9 21:48:49 1999
]0;gram@nirvana:/tmp$ telnet 10.0.0.254
Trying 10.0.0.254...
Connected to 10.0.0.254.
Escape character is '^]'.
TR-600(tr600) System Console
Login:admin
Password:*******
*--------------------------------------------------------*
| T O S H I B A T R - 6 0 0 |
| < Compact Router > |
| V1.02.02 |
| |
| (C) Copyright TOSHIBA Corp. 1997 All rights reserved. |
*--------------------------------------------------------*
tr600>snoop dump b1
Trace start?(on/off/dump/dtl)->dump
IP Address?->b1
B1 Port Filetering
Trace start(Dump Mode)...
tr600>[No.1] 00:00:09.14 B1:1 Tx 207.193.26.136->151.164.1.8 DNS SPORT=1028 LEN=38 CHKSUM=4FD4 ID=2390 Query RD QCNT=1 pow.zing.org?
OFFSET 0001-0203-0405-0607-0809-0A0B-0C0D-0E0F 0123456789ABCDEF LEN=67
0000 : FF03 003D C000 0008 2145 0000 3A12 6500 ...=....!E..:.e.
0010 : 003F 11E6 58CF C11A 8897 A401 0804 0400 .?..X...........
0020 : 3500 264F D409 5601 0000 0100 0000 0000 5.&O..V.........
0030 : 0003 706F 7704 7A69 6E67 036F 7267 0000 ..pow.zing.org..
0040 : 0100 01 ...
[No.2] 00:00:09.25 B1:1 Rx 151.164.1.8->207.193.26.136 DNS DPORT=1028 LEN=193 CHKSUM=3E06 ID=2390 Answer RD RA QCNT=1 pow.zing.org? ANCNT=1 pow.zing.org=206.57.36.90 TTL=2652
OFFSET 0001-0203-0405-0607-0809-0A0B-0C0D-0E0F 0123456789ABCDEF LEN=222
0000 : FF03 003D C000 0013 2145 0000 D590 9340 ...=....!E.....@
0010 : 00F7 116F 8E97 A401 08CF C11A 8800 3504 ...o..........5.
0020 : 0400 C13E 0609 5681 8000 0100 0100 0300 ...>..V.........
0030 : 0303 706F 7704 7A69 6E67 036F 7267 0000 ..pow.zing.org..
0040 : 0100 01C0 0C00 0100 0100 000A 5C00 04CE ............\...
0050 : 3924 5A04 5A49 4E47 036F 7267 0000 0200 9$Z.ZING.org....
0060 : 0100 016F 5B00 0D03 4841 4E03 5449 5703 ...o[...HAN.TIW.
0070 : 4E45 5400 C02E 0002 0001 0001 6F5B 0006 NET.........o[..
0080 : 034E 5331 C02E C02E 0002 0001 0001 6F5B .NS1..........o[
0090 : 001C 0854 414C 4945 5349 4E0D 434F 4E46 ...TALIESIN.CONF
00A0 : 4142 554C 4154 494F 4E03 434F 4D00 C042 ABULATION.COM..B
00B0 : 0001 0001 0001 51EC 0004 CE39 2406 C05B ......Q....9$..[
00C0 : 0001 0001 0001 6F5B 0004 CE39 245A C06D ......o[...9$Z.m
00D0 : 0001 0001 0001 4521 0004 187C 1F01 ......E!...|..
*/
/* Magic text to check for toshiba-ness of file */
static const char toshiba_hdr_magic[] =
{ 'T', ' ', 'O', ' ', 'S', ' ', 'H', ' ', 'I', ' ', 'B', ' ', 'A' };
#define TOSHIBA_HDR_MAGIC_SIZE (sizeof toshiba_hdr_magic / sizeof toshiba_hdr_magic[0])
/* Magic text for start of packet */
static const char toshiba_rec_magic[] = { '[', 'N', 'o', '.' };
#define TOSHIBA_REC_MAGIC_SIZE (sizeof toshiba_rec_magic / sizeof toshiba_rec_magic[0])
static gboolean toshiba_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean toshiba_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info);
static gboolean parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
static gboolean parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr,
Buffer *buf, int *err, gchar **err_info);
/* Seeks to the beginning of the next packet, and returns the
byte offset. Returns -1 on failure, and sets "*err" to the error
and "*err_info" to null or an additional error string. */
static gint64 toshiba_seek_next_packet(wtap *wth, int *err, gchar **err_info)
{
int byte;
guint level = 0;
gint64 cur_off;
while ((byte = file_getc(wth->fh)) != EOF) {
if (byte == toshiba_rec_magic[level]) {
level++;
if (level >= TOSHIBA_REC_MAGIC_SIZE) {
/* note: we're leaving file pointer right after the magic characters */
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error. */
*err = file_error(wth->fh, err_info);
return -1;
}
return cur_off + 1;
}
} else {
level = 0;
}
}
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return -1;
}
#define TOSHIBA_HEADER_LINES_TO_CHECK 200
#define TOSHIBA_LINE_LENGTH 240
/* Look through the first part of a file to see if this is
* a Toshiba trace file.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" will be set to null or an additional error string.
*/
static gboolean toshiba_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[TOSHIBA_LINE_LENGTH];
guint i, reclen, level, line;
char byte;
buf[TOSHIBA_LINE_LENGTH-1] = 0;
for (line = 0; line < TOSHIBA_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, TOSHIBA_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = (guint) strlen(buf);
if (reclen < TOSHIBA_HDR_MAGIC_SIZE) {
continue;
}
level = 0;
for (i = 0; i < reclen; i++) {
byte = buf[i];
if (byte == toshiba_hdr_magic[level]) {
level++;
if (level >= TOSHIBA_HDR_MAGIC_SIZE) {
return TRUE;
}
}
else {
level = 0;
}
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val toshiba_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for Toshiba header */
if (!toshiba_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
wth->file_encap = WTAP_ENCAP_PER_PACKET;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_TOSHIBA;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = toshiba_read;
wth->subtype_seek_read = toshiba_seek_read;
wth->file_tsprec = WTAP_TSPREC_CSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean toshiba_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
/* Find the next packet */
offset = toshiba_seek_next_packet(wth, err, err_info);
if (offset < 1)
return FALSE;
*data_offset = offset;
/* Parse the packet */
return parse_toshiba_packet(wth->fh, &wth->phdr, wth->frame_buffer,
err, err_info);
}
/* Used to read packets in random-access fashion */
static gboolean
toshiba_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
if (file_seek(wth->random_fh, seek_off - 1, SEEK_SET, err) == -1)
return FALSE;
if (!parse_toshiba_packet(wth->random_fh, phdr, buf, err, err_info)) {
if (*err == 0)
*err = WTAP_ERR_SHORT_READ;
return FALSE;
}
return TRUE;
}
/* Parses a packet. */
static gboolean
parse_toshiba_packet(FILE_T fh, struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
char line[TOSHIBA_LINE_LENGTH];
int num_items_scanned;
int pkt_len, pktnum, hr, min, sec, csec;
char channel[10], direction[10];
int i, hex_lines;
guint8 *pd;
/* Our file pointer should be on the line containing the
* summary information for a packet. Read in that line and
* extract the useful information
*/
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Find text in line after "[No.". Limit the length of the
* two strings since we have fixed buffers for channel[] and
* direction[] */
num_items_scanned = sscanf(line, "%9d] %2d:%2d:%2d.%9d %9s %9s",
&pktnum, &hr, &min, &sec, &csec, channel, direction);
if (num_items_scanned != 7) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: record header isn't valid");
return FALSE;
}
/* Scan lines until we find the OFFSET line. In a "telnet" trace,
* this will be the next line. But if you save your telnet session
* to a file from within a Windows-based telnet client, it may
* put in line breaks at 80 columns (or however big your "telnet" box
* is). CRT (a Windows telnet app from VanDyke) does this.
* Here we assume that 80 columns will be the minimum size, and that
* the OFFSET line is not broken in the middle. It's the previous
* line that is normally long and can thus be broken at column 80.
*/
do {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
/* Check for "OFFSET 0001-0203" at beginning of line */
line[16] = '\0';
} while (strcmp(line, "OFFSET 0001-0203") != 0);
num_items_scanned = sscanf(line+64, "LEN=%9d", &pkt_len);
if (num_items_scanned != 1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: OFFSET line doesn't have valid LEN item");
return FALSE;
}
if (pkt_len < 0) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: packet header has a negative packet length");
return FALSE;
}
if (pkt_len > WTAP_MAX_PACKET_SIZE) {
/*
* Probably a corrupt capture file; don't blow up trying
* to allocate space for an immensely-large packet.
*/
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup_printf("toshiba: File has %u-byte packet, bigger than maximum of %u",
pkt_len, WTAP_MAX_PACKET_SIZE);
return FALSE;
}
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
phdr->ts.secs = hr * 3600 + min * 60 + sec;
phdr->ts.nsecs = csec * 10000000;
phdr->caplen = pkt_len;
phdr->len = pkt_len;
switch (channel[0]) {
case 'B':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = (guint8)
strtol(&channel[1], NULL, 10);
break;
case 'D':
phdr->pkt_encap = WTAP_ENCAP_ISDN;
pseudo_header->isdn.uton = (direction[0] == 'T');
pseudo_header->isdn.channel = 0;
break;
default:
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
/* XXX - is there an FCS in the frame? */
pseudo_header->eth.fcs_len = -1;
break;
}
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, pkt_len);
pd = ws_buffer_start_ptr(buf);
/* Calculate the number of hex dump lines, each
* containing 16 bytes of data */
hex_lines = pkt_len / 16 + ((pkt_len % 16) ? 1 : 0);
for (i = 0; i < hex_lines; i++) {
if (file_gets(line, TOSHIBA_LINE_LENGTH, fh) == NULL) {
*err = file_error(fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
if (!parse_single_hex_dump_line(line, pd, i * 16)) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("toshiba: hex dump not valid");
return FALSE;
}
}
return TRUE;
}
/*
1 2 3 4
0123456789012345678901234567890123456789012345
0000 : FF03 003D C000 0008 2145 0000 3A12 6500 ...=....!E..:.e.
0010 : 003F 11E6 58CF C11A 8897 A401 0804 0400 .?..X...........
0020 : 0100 01 ...
*/
#define START_POS 7
#define HEX_LENGTH ((8 * 4) + 7) /* eight clumps of 4 bytes with 7 inner spaces */
/* Take a string representing one line from a hex dump and converts the
* text to binary data. We check the printed offset with the offset
* we are passed to validate the record. We place the bytes in the buffer
* at the specified offset.
*
* In the process, we're going to write all over the string.
*
* Returns TRUE if good hex dump, FALSE if bad.
*/
static gboolean
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset) {
int pos, i;
char *s;
unsigned long value;
guint16 word_value;
/* Get the byte_offset directly from the record */
rec[4] = '\0';
s = rec;
value = strtoul(s, NULL, 16);
if (value != byte_offset) {
return FALSE;
}
/* Go through the substring representing the values and:
* 1. Replace any spaces with '0's
* 2. Place \0's every 5 bytes (to terminate the string)
*
* Then read the eight sets of hex bytes
*/
for (pos = START_POS; pos < START_POS + HEX_LENGTH; pos++) {
if (rec[pos] == ' ') {
rec[pos] = '0';
}
}
pos = START_POS;
for (i = 0; i < 8; i++) {
rec[pos+4] = '\0';
word_value = (guint16) strtoul(&rec[pos], NULL, 16);
buf[byte_offset + i * 2 + 0] = (guint8) (word_value >> 8);
buf[byte_offset + i * 2 + 1] = (guint8) (word_value & 0x00ff);
pos += 5;
}
return TRUE;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5109_0 |
crossvul-cpp_data_good_5845_1 | /*
* algif_skcipher: User-space interface for skcipher algorithms
*
* This file provides the user-space API for symmetric key ciphers.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/scatterwalk.h>
#include <crypto/skcipher.h>
#include <crypto/if_alg.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/net.h>
#include <net/sock.h>
struct skcipher_sg_list {
struct list_head list;
int cur;
struct scatterlist sg[0];
};
struct skcipher_ctx {
struct list_head tsgl;
struct af_alg_sgl rsgl;
void *iv;
struct af_alg_completion completion;
unsigned used;
unsigned int len;
bool more;
bool merge;
bool enc;
struct ablkcipher_request req;
};
#define MAX_SGL_ENTS ((PAGE_SIZE - sizeof(struct skcipher_sg_list)) / \
sizeof(struct scatterlist) - 1)
static inline int skcipher_sndbuf(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
return max_t(int, max_t(int, sk->sk_sndbuf & PAGE_MASK, PAGE_SIZE) -
ctx->used, 0);
}
static inline bool skcipher_writable(struct sock *sk)
{
return PAGE_SIZE <= skcipher_sndbuf(sk);
}
static int skcipher_alloc_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg = NULL;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
if (!list_empty(&ctx->tsgl))
sg = sgl->sg;
if (!sg || sgl->cur >= MAX_SGL_ENTS) {
sgl = sock_kmalloc(sk, sizeof(*sgl) +
sizeof(sgl->sg[0]) * (MAX_SGL_ENTS + 1),
GFP_KERNEL);
if (!sgl)
return -ENOMEM;
sg_init_table(sgl->sg, MAX_SGL_ENTS + 1);
sgl->cur = 0;
if (sg)
scatterwalk_sg_chain(sg, MAX_SGL_ENTS + 1, sgl->sg);
list_add_tail(&sgl->list, &ctx->tsgl);
}
return 0;
}
static void skcipher_pull_sgl(struct sock *sk, int used)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
int i;
while (!list_empty(&ctx->tsgl)) {
sgl = list_first_entry(&ctx->tsgl, struct skcipher_sg_list,
list);
sg = sgl->sg;
for (i = 0; i < sgl->cur; i++) {
int plen = min_t(int, used, sg[i].length);
if (!sg_page(sg + i))
continue;
sg[i].length -= plen;
sg[i].offset += plen;
used -= plen;
ctx->used -= plen;
if (sg[i].length)
return;
put_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
}
list_del(&sgl->list);
sock_kfree_s(sk, sgl,
sizeof(*sgl) + sizeof(sgl->sg[0]) *
(MAX_SGL_ENTS + 1));
}
if (!ctx->used)
ctx->merge = 0;
}
static void skcipher_free_sgl(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
skcipher_pull_sgl(sk, ctx->used);
}
static int skcipher_wait_for_wmem(struct sock *sk, unsigned flags)
{
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT)
return -EAGAIN;
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, skcipher_writable(sk))) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
return err;
}
static void skcipher_wmem_wakeup(struct sock *sk)
{
struct socket_wq *wq;
if (!skcipher_writable(sk))
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static int skcipher_wait_for_data(struct sock *sk, unsigned flags)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
long timeout;
DEFINE_WAIT(wait);
int err = -ERESTARTSYS;
if (flags & MSG_DONTWAIT) {
return -EAGAIN;
}
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
for (;;) {
if (signal_pending(current))
break;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
timeout = MAX_SCHEDULE_TIMEOUT;
if (sk_wait_event(sk, &timeout, ctx->used)) {
err = 0;
break;
}
}
finish_wait(sk_sleep(sk), &wait);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
return err;
}
static void skcipher_data_wakeup(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct socket_wq *wq;
if (!ctx->used)
return;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLRDNORM |
POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
rcu_read_unlock();
}
static int skcipher_sendmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t size)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
unsigned ivsize = crypto_ablkcipher_ivsize(tfm);
struct skcipher_sg_list *sgl;
struct af_alg_control con = {};
long copied = 0;
bool enc = 0;
int err;
int i;
if (msg->msg_controllen) {
err = af_alg_cmsg_send(msg, &con);
if (err)
return err;
switch (con.op) {
case ALG_OP_ENCRYPT:
enc = 1;
break;
case ALG_OP_DECRYPT:
enc = 0;
break;
default:
return -EINVAL;
}
if (con.iv && con.iv->ivlen != ivsize)
return -EINVAL;
}
err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!ctx->used) {
ctx->enc = enc;
if (con.iv)
memcpy(ctx->iv, con.iv->iv, ivsize);
}
while (size) {
struct scatterlist *sg;
unsigned long len = size;
int plen;
if (ctx->merge) {
sgl = list_entry(ctx->tsgl.prev,
struct skcipher_sg_list, list);
sg = sgl->sg + sgl->cur - 1;
len = min_t(unsigned long, len,
PAGE_SIZE - sg->offset - sg->length);
err = memcpy_fromiovec(page_address(sg_page(sg)) +
sg->offset + sg->length,
msg->msg_iov, len);
if (err)
goto unlock;
sg->length += len;
ctx->merge = (sg->offset + sg->length) &
(PAGE_SIZE - 1);
ctx->used += len;
copied += len;
size -= len;
continue;
}
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, msg->msg_flags);
if (err)
goto unlock;
}
len = min_t(unsigned long, len, skcipher_sndbuf(sk));
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
sg = sgl->sg;
do {
i = sgl->cur;
plen = min_t(int, len, PAGE_SIZE);
sg_assign_page(sg + i, alloc_page(GFP_KERNEL));
err = -ENOMEM;
if (!sg_page(sg + i))
goto unlock;
err = memcpy_fromiovec(page_address(sg_page(sg + i)),
msg->msg_iov, plen);
if (err) {
__free_page(sg_page(sg + i));
sg_assign_page(sg + i, NULL);
goto unlock;
}
sg[i].length = plen;
len -= plen;
ctx->used += plen;
copied += plen;
size -= plen;
sgl->cur++;
} while (len && sgl->cur < MAX_SGL_ENTS);
ctx->merge = plen & (PAGE_SIZE - 1);
}
err = 0;
ctx->more = msg->msg_flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static ssize_t skcipher_sendpage(struct socket *sock, struct page *page,
int offset, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct skcipher_sg_list *sgl;
int err = -EINVAL;
lock_sock(sk);
if (!ctx->more && ctx->used)
goto unlock;
if (!size)
goto done;
if (!skcipher_writable(sk)) {
err = skcipher_wait_for_wmem(sk, flags);
if (err)
goto unlock;
}
err = skcipher_alloc_sgl(sk);
if (err)
goto unlock;
ctx->merge = 0;
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
get_page(page);
sg_set_page(sgl->sg + sgl->cur, page, size, offset);
sgl->cur++;
ctx->used += size;
done:
ctx->more = flags & MSG_MORE;
if (!ctx->more && !list_empty(&ctx->tsgl))
sgl = list_entry(ctx->tsgl.prev, struct skcipher_sg_list, list);
unlock:
skcipher_data_wakeup(sk);
release_sock(sk);
return err ?: size;
}
static int skcipher_recvmsg(struct kiocb *unused, struct socket *sock,
struct msghdr *msg, size_t ignored, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned bs = crypto_ablkcipher_blocksize(crypto_ablkcipher_reqtfm(
&ctx->req));
struct skcipher_sg_list *sgl;
struct scatterlist *sg;
unsigned long iovlen;
struct iovec *iov;
int err = -EAGAIN;
int used;
long copied = 0;
lock_sock(sk);
for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0;
iovlen--, iov++) {
unsigned long seglen = iov->iov_len;
char __user *from = iov->iov_base;
while (seglen) {
sgl = list_first_entry(&ctx->tsgl,
struct skcipher_sg_list, list);
sg = sgl->sg;
while (!sg->length)
sg++;
used = ctx->used;
if (!used) {
err = skcipher_wait_for_data(sk, flags);
if (err)
goto unlock;
}
used = min_t(unsigned long, used, seglen);
used = af_alg_make_sg(&ctx->rsgl, from, used, 1);
err = used;
if (err < 0)
goto unlock;
if (ctx->more || used < ctx->used)
used -= used % bs;
err = -EINVAL;
if (!used)
goto free;
ablkcipher_request_set_crypt(&ctx->req, sg,
ctx->rsgl.sg, used,
ctx->iv);
err = af_alg_wait_for_completion(
ctx->enc ?
crypto_ablkcipher_encrypt(&ctx->req) :
crypto_ablkcipher_decrypt(&ctx->req),
&ctx->completion);
free:
af_alg_free_sg(&ctx->rsgl);
if (err)
goto unlock;
copied += used;
from += used;
seglen -= used;
skcipher_pull_sgl(sk, used);
}
}
err = 0;
unlock:
skcipher_wmem_wakeup(sk);
release_sock(sk);
return copied ?: err;
}
static unsigned int skcipher_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
if (ctx->used)
mask |= POLLIN | POLLRDNORM;
if (skcipher_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static struct proto_ops algif_skcipher_ops = {
.family = PF_ALG,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.getname = sock_no_getname,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.getsockopt = sock_no_getsockopt,
.mmap = sock_no_mmap,
.bind = sock_no_bind,
.accept = sock_no_accept,
.setsockopt = sock_no_setsockopt,
.release = af_alg_release,
.sendmsg = skcipher_sendmsg,
.sendpage = skcipher_sendpage,
.recvmsg = skcipher_recvmsg,
.poll = skcipher_poll,
};
static void *skcipher_bind(const char *name, u32 type, u32 mask)
{
return crypto_alloc_ablkcipher(name, type, mask);
}
static void skcipher_release(void *private)
{
crypto_free_ablkcipher(private);
}
static int skcipher_setkey(void *private, const u8 *key, unsigned int keylen)
{
return crypto_ablkcipher_setkey(private, key, keylen);
}
static void skcipher_sock_destruct(struct sock *sk)
{
struct alg_sock *ask = alg_sk(sk);
struct skcipher_ctx *ctx = ask->private;
struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(&ctx->req);
skcipher_free_sgl(sk);
sock_kfree_s(sk, ctx->iv, crypto_ablkcipher_ivsize(tfm));
sock_kfree_s(sk, ctx, ctx->len);
af_alg_release_parent(sk);
}
static int skcipher_accept_parent(void *private, struct sock *sk)
{
struct skcipher_ctx *ctx;
struct alg_sock *ask = alg_sk(sk);
unsigned int len = sizeof(*ctx) + crypto_ablkcipher_reqsize(private);
ctx = sock_kmalloc(sk, len, GFP_KERNEL);
if (!ctx)
return -ENOMEM;
ctx->iv = sock_kmalloc(sk, crypto_ablkcipher_ivsize(private),
GFP_KERNEL);
if (!ctx->iv) {
sock_kfree_s(sk, ctx, len);
return -ENOMEM;
}
memset(ctx->iv, 0, crypto_ablkcipher_ivsize(private));
INIT_LIST_HEAD(&ctx->tsgl);
ctx->len = len;
ctx->used = 0;
ctx->more = 0;
ctx->merge = 0;
ctx->enc = 0;
af_alg_init_completion(&ctx->completion);
ask->private = ctx;
ablkcipher_request_set_tfm(&ctx->req, private);
ablkcipher_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
af_alg_complete, &ctx->completion);
sk->sk_destruct = skcipher_sock_destruct;
return 0;
}
static const struct af_alg_type algif_type_skcipher = {
.bind = skcipher_bind,
.release = skcipher_release,
.setkey = skcipher_setkey,
.accept = skcipher_accept_parent,
.ops = &algif_skcipher_ops,
.name = "skcipher",
.owner = THIS_MODULE
};
static int __init algif_skcipher_init(void)
{
return af_alg_register_type(&algif_type_skcipher);
}
static void __exit algif_skcipher_exit(void)
{
int err = af_alg_unregister_type(&algif_type_skcipher);
BUG_ON(err);
}
module_init(algif_skcipher_init);
module_exit(algif_skcipher_exit);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_1 |
crossvul-cpp_data_bad_2891_4 | /* Key garbage collector
*
* Copyright (C) 2009-2011 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public Licence
* as published by the Free Software Foundation; either version
* 2 of the Licence, or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/security.h>
#include <keys/keyring-type.h>
#include "internal.h"
/*
* Delay between key revocation/expiry in seconds
*/
unsigned key_gc_delay = 5 * 60;
/*
* Reaper for unused keys.
*/
static void key_garbage_collector(struct work_struct *work);
DECLARE_WORK(key_gc_work, key_garbage_collector);
/*
* Reaper for links from keyrings to dead keys.
*/
static void key_gc_timer_func(unsigned long);
static DEFINE_TIMER(key_gc_timer, key_gc_timer_func, 0, 0);
static time_t key_gc_next_run = LONG_MAX;
static struct key_type *key_gc_dead_keytype;
static unsigned long key_gc_flags;
#define KEY_GC_KEY_EXPIRED 0 /* A key expired and needs unlinking */
#define KEY_GC_REAP_KEYTYPE 1 /* A keytype is being unregistered */
#define KEY_GC_REAPING_KEYTYPE 2 /* Cleared when keytype reaped */
/*
* Any key whose type gets unregistered will be re-typed to this if it can't be
* immediately unlinked.
*/
struct key_type key_type_dead = {
.name = ".dead",
};
/*
* Schedule a garbage collection run.
* - time precision isn't particularly important
*/
void key_schedule_gc(time_t gc_at)
{
unsigned long expires;
time_t now = current_kernel_time().tv_sec;
kenter("%ld", gc_at - now);
if (gc_at <= now || test_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags)) {
kdebug("IMMEDIATE");
schedule_work(&key_gc_work);
} else if (gc_at < key_gc_next_run) {
kdebug("DEFERRED");
key_gc_next_run = gc_at;
expires = jiffies + (gc_at - now) * HZ;
mod_timer(&key_gc_timer, expires);
}
}
/*
* Schedule a dead links collection run.
*/
void key_schedule_gc_links(void)
{
set_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags);
schedule_work(&key_gc_work);
}
/*
* Some key's cleanup time was met after it expired, so we need to get the
* reaper to go through a cycle finding expired keys.
*/
static void key_gc_timer_func(unsigned long data)
{
kenter("");
key_gc_next_run = LONG_MAX;
key_schedule_gc_links();
}
/*
* Reap keys of dead type.
*
* We use three flags to make sure we see three complete cycles of the garbage
* collector: the first to mark keys of that type as being dead, the second to
* collect dead links and the third to clean up the dead keys. We have to be
* careful as there may already be a cycle in progress.
*
* The caller must be holding key_types_sem.
*/
void key_gc_keytype(struct key_type *ktype)
{
kenter("%s", ktype->name);
key_gc_dead_keytype = ktype;
set_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
smp_mb();
set_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags);
kdebug("schedule");
schedule_work(&key_gc_work);
kdebug("sleep");
wait_on_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE,
TASK_UNINTERRUPTIBLE);
key_gc_dead_keytype = NULL;
kleave("");
}
/*
* Garbage collect a list of unreferenced, detached keys
*/
static noinline void key_gc_unused_keys(struct list_head *keys)
{
while (!list_empty(keys)) {
struct key *key =
list_entry(keys->next, struct key, graveyard_link);
list_del(&key->graveyard_link);
kdebug("- %u", key->serial);
key_check(key);
/* Throw away the key data if the key is instantiated */
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags) &&
!test_bit(KEY_FLAG_NEGATIVE, &key->flags) &&
key->type->destroy)
key->type->destroy(key);
security_key_free(key);
/* deal with the user's key tracking and quota */
if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) {
spin_lock(&key->user->lock);
key->user->qnkeys--;
key->user->qnbytes -= key->quotalen;
spin_unlock(&key->user->lock);
}
atomic_dec(&key->user->nkeys);
if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags))
atomic_dec(&key->user->nikeys);
key_user_put(key->user);
kfree(key->description);
memzero_explicit(key, sizeof(*key));
kmem_cache_free(key_jar, key);
}
}
/*
* Garbage collector for unused keys.
*
* This is done in process context so that we don't have to disable interrupts
* all over the place. key_put() schedules this rather than trying to do the
* cleanup itself, which means key_put() doesn't have to sleep.
*/
static void key_garbage_collector(struct work_struct *work)
{
static LIST_HEAD(graveyard);
static u8 gc_state; /* Internal persistent state */
#define KEY_GC_REAP_AGAIN 0x01 /* - Need another cycle */
#define KEY_GC_REAPING_LINKS 0x02 /* - We need to reap links */
#define KEY_GC_SET_TIMER 0x04 /* - We need to restart the timer */
#define KEY_GC_REAPING_DEAD_1 0x10 /* - We need to mark dead keys */
#define KEY_GC_REAPING_DEAD_2 0x20 /* - We need to reap dead key links */
#define KEY_GC_REAPING_DEAD_3 0x40 /* - We need to reap dead keys */
#define KEY_GC_FOUND_DEAD_KEY 0x80 /* - We found at least one dead key */
struct rb_node *cursor;
struct key *key;
time_t new_timer, limit;
kenter("[%lx,%x]", key_gc_flags, gc_state);
limit = current_kernel_time().tv_sec;
if (limit > key_gc_delay)
limit -= key_gc_delay;
else
limit = key_gc_delay;
/* Work out what we're going to be doing in this pass */
gc_state &= KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2;
gc_state <<= 1;
if (test_and_clear_bit(KEY_GC_KEY_EXPIRED, &key_gc_flags))
gc_state |= KEY_GC_REAPING_LINKS | KEY_GC_SET_TIMER;
if (test_and_clear_bit(KEY_GC_REAP_KEYTYPE, &key_gc_flags))
gc_state |= KEY_GC_REAPING_DEAD_1;
kdebug("new pass %x", gc_state);
new_timer = LONG_MAX;
/* As only this function is permitted to remove things from the key
* serial tree, if cursor is non-NULL then it will always point to a
* valid node in the tree - even if lock got dropped.
*/
spin_lock(&key_serial_lock);
cursor = rb_first(&key_serial_tree);
continue_scanning:
while (cursor) {
key = rb_entry(cursor, struct key, serial_node);
cursor = rb_next(cursor);
if (refcount_read(&key->usage) == 0)
goto found_unreferenced_key;
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_1)) {
if (key->type == key_gc_dead_keytype) {
gc_state |= KEY_GC_FOUND_DEAD_KEY;
set_bit(KEY_FLAG_DEAD, &key->flags);
key->perm = 0;
goto skip_dead_key;
} else if (key->type == &key_type_keyring &&
key->restrict_link) {
goto found_restricted_keyring;
}
}
if (gc_state & KEY_GC_SET_TIMER) {
if (key->expiry > limit && key->expiry < new_timer) {
kdebug("will expire %x in %ld",
key_serial(key), key->expiry - limit);
new_timer = key->expiry;
}
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2))
if (key->type == key_gc_dead_keytype)
gc_state |= KEY_GC_FOUND_DEAD_KEY;
if ((gc_state & KEY_GC_REAPING_LINKS) ||
unlikely(gc_state & KEY_GC_REAPING_DEAD_2)) {
if (key->type == &key_type_keyring)
goto found_keyring;
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3))
if (key->type == key_gc_dead_keytype)
goto destroy_dead_key;
skip_dead_key:
if (spin_is_contended(&key_serial_lock) || need_resched())
goto contended;
}
contended:
spin_unlock(&key_serial_lock);
maybe_resched:
if (cursor) {
cond_resched();
spin_lock(&key_serial_lock);
goto continue_scanning;
}
/* We've completed the pass. Set the timer if we need to and queue a
* new cycle if necessary. We keep executing cycles until we find one
* where we didn't reap any keys.
*/
kdebug("pass complete");
if (gc_state & KEY_GC_SET_TIMER && new_timer != (time_t)LONG_MAX) {
new_timer += key_gc_delay;
key_schedule_gc(new_timer);
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_2) ||
!list_empty(&graveyard)) {
/* Make sure that all pending keyring payload destructions are
* fulfilled and that people aren't now looking at dead or
* dying keys that they don't have a reference upon or a link
* to.
*/
kdebug("gc sync");
synchronize_rcu();
}
if (!list_empty(&graveyard)) {
kdebug("gc keys");
key_gc_unused_keys(&graveyard);
}
if (unlikely(gc_state & (KEY_GC_REAPING_DEAD_1 |
KEY_GC_REAPING_DEAD_2))) {
if (!(gc_state & KEY_GC_FOUND_DEAD_KEY)) {
/* No remaining dead keys: short circuit the remaining
* keytype reap cycles.
*/
kdebug("dead short");
gc_state &= ~(KEY_GC_REAPING_DEAD_1 | KEY_GC_REAPING_DEAD_2);
gc_state |= KEY_GC_REAPING_DEAD_3;
} else {
gc_state |= KEY_GC_REAP_AGAIN;
}
}
if (unlikely(gc_state & KEY_GC_REAPING_DEAD_3)) {
kdebug("dead wake");
smp_mb();
clear_bit(KEY_GC_REAPING_KEYTYPE, &key_gc_flags);
wake_up_bit(&key_gc_flags, KEY_GC_REAPING_KEYTYPE);
}
if (gc_state & KEY_GC_REAP_AGAIN)
schedule_work(&key_gc_work);
kleave(" [end %x]", gc_state);
return;
/* We found an unreferenced key - once we've removed it from the tree,
* we can safely drop the lock.
*/
found_unreferenced_key:
kdebug("unrefd key %d", key->serial);
rb_erase(&key->serial_node, &key_serial_tree);
spin_unlock(&key_serial_lock);
list_add_tail(&key->graveyard_link, &graveyard);
gc_state |= KEY_GC_REAP_AGAIN;
goto maybe_resched;
/* We found a restricted keyring and need to update the restriction if
* it is associated with the dead key type.
*/
found_restricted_keyring:
spin_unlock(&key_serial_lock);
keyring_restriction_gc(key, key_gc_dead_keytype);
goto maybe_resched;
/* We found a keyring and we need to check the payload for links to
* dead or expired keys. We don't flag another reap immediately as we
* have to wait for the old payload to be destroyed by RCU before we
* can reap the keys to which it refers.
*/
found_keyring:
spin_unlock(&key_serial_lock);
keyring_gc(key, limit);
goto maybe_resched;
/* We found a dead key that is still referenced. Reset its type and
* destroy its payload with its semaphore held.
*/
destroy_dead_key:
spin_unlock(&key_serial_lock);
kdebug("destroy key %d", key->serial);
down_write(&key->sem);
key->type = &key_type_dead;
if (key_gc_dead_keytype->destroy)
key_gc_dead_keytype->destroy(key);
memset(&key->payload, KEY_DESTROY, sizeof(key->payload));
up_write(&key->sem);
goto maybe_resched;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_4 |
crossvul-cpp_data_good_4717_0 | /*
* reflection.c: Routines for creating an image at runtime.
*
* Author:
* Paolo Molaro (lupus@ximian.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*
*/
#include <config.h>
#include "mono/utils/mono-digest.h"
#include "mono/utils/mono-membar.h"
#include "mono/metadata/reflection.h"
#include "mono/metadata/tabledefs.h"
#include "mono/metadata/metadata-internals.h"
#include <mono/metadata/profiler-private.h>
#include "mono/metadata/class-internals.h"
#include "mono/metadata/gc-internal.h"
#include "mono/metadata/tokentype.h"
#include "mono/metadata/domain-internals.h"
#include "mono/metadata/opcodes.h"
#include "mono/metadata/assembly.h"
#include "mono/metadata/object-internals.h"
#include <mono/metadata/exception.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/security-manager.h>
#include <stdio.h>
#include <glib.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include "image.h"
#include "cil-coff.h"
#include "mono-endian.h"
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/mono-ptr-array.h>
#include <mono/utils/mono-string.h>
#include <mono/utils/mono-error-internals.h>
#if HAVE_SGEN_GC
static void* reflection_info_desc = NULL;
#define MOVING_GC_REGISTER(addr) do { \
if (!reflection_info_desc) { \
gsize bmap = 1; \
reflection_info_desc = mono_gc_make_descr_from_bitmap (&bmap, 1); \
} \
mono_gc_register_root ((char*)(addr), sizeof (gpointer), reflection_info_desc); \
} while (0)
#else
#define MOVING_GC_REGISTER(addr)
#endif
static gboolean is_usertype (MonoReflectionType *ref);
static MonoReflectionType *mono_reflection_type_resolve_user_types (MonoReflectionType *type);
typedef struct {
char *p;
char *buf;
char *end;
} SigBuffer;
#define TEXT_OFFSET 512
#define CLI_H_SIZE 136
#define FILE_ALIGN 512
#define VIRT_ALIGN 8192
#define START_TEXT_RVA 0x00002000
typedef struct {
MonoReflectionILGen *ilgen;
MonoReflectionType *rtype;
MonoArray *parameters;
MonoArray *generic_params;
MonoGenericContainer *generic_container;
MonoArray *pinfo;
MonoArray *opt_types;
guint32 attrs;
guint32 iattrs;
guint32 call_conv;
guint32 *table_idx; /* note: it's a pointer */
MonoArray *code;
MonoObject *type;
MonoString *name;
MonoBoolean init_locals;
MonoBoolean skip_visibility;
MonoArray *return_modreq;
MonoArray *return_modopt;
MonoArray *param_modreq;
MonoArray *param_modopt;
MonoArray *permissions;
MonoMethod *mhandle;
guint32 nrefs;
gpointer *refs;
/* for PInvoke */
int charset, extra_flags, native_cc;
MonoString *dll, *dllentry;
} ReflectionMethodBuilder;
typedef struct {
guint32 owner;
MonoReflectionGenericParam *gparam;
} GenericParamTableEntry;
const unsigned char table_sizes [MONO_TABLE_NUM] = {
MONO_MODULE_SIZE,
MONO_TYPEREF_SIZE,
MONO_TYPEDEF_SIZE,
0,
MONO_FIELD_SIZE,
0,
MONO_METHOD_SIZE,
0,
MONO_PARAM_SIZE,
MONO_INTERFACEIMPL_SIZE,
MONO_MEMBERREF_SIZE, /* 0x0A */
MONO_CONSTANT_SIZE,
MONO_CUSTOM_ATTR_SIZE,
MONO_FIELD_MARSHAL_SIZE,
MONO_DECL_SECURITY_SIZE,
MONO_CLASS_LAYOUT_SIZE,
MONO_FIELD_LAYOUT_SIZE, /* 0x10 */
MONO_STAND_ALONE_SIGNATURE_SIZE,
MONO_EVENT_MAP_SIZE,
0,
MONO_EVENT_SIZE,
MONO_PROPERTY_MAP_SIZE,
0,
MONO_PROPERTY_SIZE,
MONO_METHOD_SEMA_SIZE,
MONO_METHODIMPL_SIZE,
MONO_MODULEREF_SIZE, /* 0x1A */
MONO_TYPESPEC_SIZE,
MONO_IMPLMAP_SIZE,
MONO_FIELD_RVA_SIZE,
0,
0,
MONO_ASSEMBLY_SIZE, /* 0x20 */
MONO_ASSEMBLY_PROCESSOR_SIZE,
MONO_ASSEMBLYOS_SIZE,
MONO_ASSEMBLYREF_SIZE,
MONO_ASSEMBLYREFPROC_SIZE,
MONO_ASSEMBLYREFOS_SIZE,
MONO_FILE_SIZE,
MONO_EXP_TYPE_SIZE,
MONO_MANIFEST_SIZE,
MONO_NESTED_CLASS_SIZE,
MONO_GENERICPARAM_SIZE, /* 0x2A */
MONO_METHODSPEC_SIZE,
MONO_GENPARCONSTRAINT_SIZE
};
#ifndef DISABLE_REFLECTION_EMIT
static guint32 mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec);
static guint32 mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec);
static guint32 mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *cb);
static guint32 mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper);
static void ensure_runtime_vtable (MonoClass *klass);
static gpointer resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context);
static guint32 mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method);
static guint32 encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context);
static gpointer register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly);
static void reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb);
static void reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb);
static guint32 create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb);
#endif
static guint32 mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type);
static guint32 mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec);
static void mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly);
static guint32 encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo);
static guint32 encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type);
static char* type_get_qualified_name (MonoType *type, MonoAssembly *ass);
static void encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf);
static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types);
static MonoReflectionType *mono_reflection_type_get_underlying_system_type (MonoReflectionType* t);
static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve);
static MonoReflectionType* mono_reflection_type_resolve_user_types (MonoReflectionType *type);
static gboolean is_sre_array (MonoClass *class);
static gboolean is_sre_byref (MonoClass *class);
static gboolean is_sre_pointer (MonoClass *class);
static gboolean is_sre_type_builder (MonoClass *class);
static gboolean is_sre_method_builder (MonoClass *class);
static gboolean is_sre_ctor_builder (MonoClass *class);
static gboolean is_sre_field_builder (MonoClass *class);
static gboolean is_sr_mono_method (MonoClass *class);
static gboolean is_sr_mono_cmethod (MonoClass *class);
static gboolean is_sr_mono_generic_method (MonoClass *class);
static gboolean is_sr_mono_generic_cmethod (MonoClass *class);
static gboolean is_sr_mono_field (MonoClass *class);
static gboolean is_sr_mono_property (MonoClass *class);
static gboolean is_sre_method_on_tb_inst (MonoClass *class);
static gboolean is_sre_ctor_on_tb_inst (MonoClass *class);
static guint32 mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method);
static guint32 mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m);
static MonoMethod * inflate_method (MonoReflectionType *type, MonoObject *obj);
#define RESOLVE_TYPE(type) do { type = (void*)mono_reflection_type_resolve_user_types ((MonoReflectionType*)type); } while (0)
#define RESOLVE_ARRAY_TYPE_ELEMENT(array, index) do { \
MonoReflectionType *__type = mono_array_get (array, MonoReflectionType*, index); \
__type = mono_reflection_type_resolve_user_types (__type); \
mono_array_set (arr, MonoReflectionType*, index, __type); \
} while (0)
#define mono_type_array_get_and_resolve(array, index) mono_reflection_type_get_handle ((MonoReflectionType*)mono_array_get (array, gpointer, index))
void
mono_reflection_init (void)
{
}
static void
sigbuffer_init (SigBuffer *buf, int size)
{
buf->buf = g_malloc (size);
buf->p = buf->buf;
buf->end = buf->buf + size;
}
static void
sigbuffer_make_room (SigBuffer *buf, int size)
{
if (buf->end - buf->p < size) {
int new_size = buf->end - buf->buf + size + 32;
char *p = g_realloc (buf->buf, new_size);
size = buf->p - buf->buf;
buf->buf = p;
buf->p = p + size;
buf->end = buf->buf + new_size;
}
}
static void
sigbuffer_add_value (SigBuffer *buf, guint32 val)
{
sigbuffer_make_room (buf, 6);
mono_metadata_encode_value (val, buf->p, &buf->p);
}
static void
sigbuffer_add_byte (SigBuffer *buf, guint8 val)
{
sigbuffer_make_room (buf, 1);
buf->p [0] = val;
buf->p++;
}
static void
sigbuffer_add_mem (SigBuffer *buf, char *p, guint32 size)
{
sigbuffer_make_room (buf, size);
memcpy (buf->p, p, size);
buf->p += size;
}
static void
sigbuffer_free (SigBuffer *buf)
{
g_free (buf->buf);
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mp_g_alloc:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc (image, size);
else
return g_malloc (size);
}
#endif /* !DISABLE_REFLECTION_EMIT */
/**
* image_g_alloc0:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc0 (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc0 (image, size);
else
return g_malloc0 (size);
}
#ifndef DISABLE_REFLECTION_EMIT
static char*
image_strdup (MonoImage *image, const char *s)
{
if (image)
return mono_image_strdup (image, s);
else
return g_strdup (s);
}
#endif
#define image_g_new(image,struct_type, n_structs) \
((struct_type *) image_g_malloc (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
#define image_g_new0(image,struct_type, n_structs) \
((struct_type *) image_g_malloc0 (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
static void
alloc_table (MonoDynamicTable *table, guint nrows)
{
table->rows = nrows;
g_assert (table->columns);
if (nrows + 1 >= table->alloc_rows) {
while (nrows + 1 >= table->alloc_rows) {
if (table->alloc_rows == 0)
table->alloc_rows = 16;
else
table->alloc_rows *= 2;
}
table->values = g_renew (guint32, table->values, (table->alloc_rows) * table->columns);
}
}
static void
make_room_in_stream (MonoDynamicStream *stream, int size)
{
if (size <= stream->alloc_size)
return;
while (stream->alloc_size <= size) {
if (stream->alloc_size < 4096)
stream->alloc_size = 4096;
else
stream->alloc_size *= 2;
}
stream->data = g_realloc (stream->data, stream->alloc_size);
}
static guint32
string_heap_insert (MonoDynamicStream *sh, const char *str)
{
guint32 idx;
guint32 len;
gpointer oldkey, oldval;
if (g_hash_table_lookup_extended (sh->hash, str, &oldkey, &oldval))
return GPOINTER_TO_UINT (oldval);
len = strlen (str) + 1;
idx = sh->index;
make_room_in_stream (sh, idx + len);
/*
* We strdup the string even if we already copy them in sh->data
* so that the string pointers in the hash remain valid even if
* we need to realloc sh->data. We may want to avoid that later.
*/
g_hash_table_insert (sh->hash, g_strdup (str), GUINT_TO_POINTER (idx));
memcpy (sh->data + idx, str, len);
sh->index += len;
return idx;
}
static guint32
string_heap_insert_mstring (MonoDynamicStream *sh, MonoString *str)
{
char *name = mono_string_to_utf8 (str);
guint32 idx;
idx = string_heap_insert (sh, name);
g_free (name);
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
string_heap_init (MonoDynamicStream *sh)
{
sh->index = 0;
sh->alloc_size = 4096;
sh->data = g_malloc (4096);
sh->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
string_heap_insert (sh, "");
}
#endif
static guint32
mono_image_add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memcpy (stream->data + stream->index, data, len);
idx = stream->index;
stream->index += len;
/*
* align index? Not without adding an additional param that controls it since
* we may store a blob value in pieces.
*/
return idx;
}
static guint32
mono_image_add_stream_zero (MonoDynamicStream *stream, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memset (stream->data + stream->index, 0, len);
idx = stream->index;
stream->index += len;
return idx;
}
static void
stream_data_align (MonoDynamicStream *stream)
{
char buf [4] = {0};
guint32 count = stream->index % 4;
/* we assume the stream data will be aligned */
if (count)
mono_image_add_stream_data (stream, buf, 4 - count);
}
#ifndef DISABLE_REFLECTION_EMIT
static int
mono_blob_entry_hash (const char* str)
{
guint len, h;
const char *end;
len = mono_metadata_decode_blob_size (str, &str);
if (len > 0) {
end = str + len;
h = *str;
for (str += 1; str < end; str++)
h = (h << 5) - h + *str;
return h;
} else {
return 0;
}
}
static gboolean
mono_blob_entry_equal (const char *str1, const char *str2) {
int len, len2;
const char *end1;
const char *end2;
len = mono_metadata_decode_blob_size (str1, &end1);
len2 = mono_metadata_decode_blob_size (str2, &end2);
if (len != len2)
return 0;
return memcmp (end1, end2, len) == 0;
}
#endif
static guint32
add_to_blob_cached (MonoDynamicImage *assembly, char *b1, int s1, char *b2, int s2)
{
guint32 idx;
char *copy;
gpointer oldkey, oldval;
copy = g_malloc (s1+s2);
memcpy (copy, b1, s1);
memcpy (copy + s1, b2, s2);
if (g_hash_table_lookup_extended (assembly->blob_cache, copy, &oldkey, &oldval)) {
g_free (copy);
idx = GPOINTER_TO_UINT (oldval);
} else {
idx = mono_image_add_stream_data (&assembly->blob, b1, s1);
mono_image_add_stream_data (&assembly->blob, b2, s2);
g_hash_table_insert (assembly->blob_cache, copy, GUINT_TO_POINTER (idx));
}
return idx;
}
static guint32
sigbuffer_add_to_blob_cached (MonoDynamicImage *assembly, SigBuffer *buf)
{
char blob_size [8];
char *b = blob_size;
guint32 size = buf->p - buf->buf;
/* store length */
g_assert (size <= (buf->end - buf->buf));
mono_metadata_encode_value (size, b, &b);
return add_to_blob_cached (assembly, blob_size, b-blob_size, buf->buf, size);
}
/*
* Copy len * nelem bytes from val to dest, swapping bytes to LE if necessary.
* dest may be misaligned.
*/
static void
swap_with_size (char *dest, const char* val, int len, int nelem) {
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
int elem;
for (elem = 0; elem < nelem; ++elem) {
switch (len) {
case 1:
*dest = *val;
break;
case 2:
dest [0] = val [1];
dest [1] = val [0];
break;
case 4:
dest [0] = val [3];
dest [1] = val [2];
dest [2] = val [1];
dest [3] = val [0];
break;
case 8:
dest [0] = val [7];
dest [1] = val [6];
dest [2] = val [5];
dest [3] = val [4];
dest [4] = val [3];
dest [5] = val [2];
dest [6] = val [1];
dest [7] = val [0];
break;
default:
g_assert_not_reached ();
}
dest += len;
val += len;
}
#else
memcpy (dest, val, len * nelem);
#endif
}
static guint32
add_mono_string_to_blob_cached (MonoDynamicImage *assembly, MonoString *str)
{
char blob_size [64];
char *b = blob_size;
guint32 idx = 0, len;
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoClass *
default_class_from_mono_type (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_OBJECT:
return mono_defaults.object_class;
case MONO_TYPE_VOID:
return mono_defaults.void_class;
case MONO_TYPE_BOOLEAN:
return mono_defaults.boolean_class;
case MONO_TYPE_CHAR:
return mono_defaults.char_class;
case MONO_TYPE_I1:
return mono_defaults.sbyte_class;
case MONO_TYPE_U1:
return mono_defaults.byte_class;
case MONO_TYPE_I2:
return mono_defaults.int16_class;
case MONO_TYPE_U2:
return mono_defaults.uint16_class;
case MONO_TYPE_I4:
return mono_defaults.int32_class;
case MONO_TYPE_U4:
return mono_defaults.uint32_class;
case MONO_TYPE_I:
return mono_defaults.int_class;
case MONO_TYPE_U:
return mono_defaults.uint_class;
case MONO_TYPE_I8:
return mono_defaults.int64_class;
case MONO_TYPE_U8:
return mono_defaults.uint64_class;
case MONO_TYPE_R4:
return mono_defaults.single_class;
case MONO_TYPE_R8:
return mono_defaults.double_class;
case MONO_TYPE_STRING:
return mono_defaults.string_class;
default:
g_warning ("default_class_from_mono_type: implement me 0x%02x\n", type->type);
g_assert_not_reached ();
}
return NULL;
}
#endif
/*
* mono_class_get_ref_info:
*
* Return the type builder/generic param builder corresponding to KLASS, if it exists.
*/
gpointer
mono_class_get_ref_info (MonoClass *klass)
{
if (klass->ref_info_handle == 0)
return NULL;
else
return mono_gchandle_get_target (klass->ref_info_handle);
}
void
mono_class_set_ref_info (MonoClass *klass, gpointer obj)
{
klass->ref_info_handle = mono_gchandle_new ((MonoObject*)obj, FALSE);
g_assert (klass->ref_info_handle != 0);
}
void
mono_class_free_ref_info (MonoClass *klass)
{
if (klass->ref_info_handle) {
mono_gchandle_free (klass->ref_info_handle);
klass->ref_info_handle = 0;
}
}
static void
encode_generic_class (MonoDynamicImage *assembly, MonoGenericClass *gclass, SigBuffer *buf)
{
int i;
MonoGenericInst *class_inst;
MonoClass *klass;
g_assert (gclass);
class_inst = gclass->context.class_inst;
sigbuffer_add_value (buf, MONO_TYPE_GENERICINST);
klass = gclass->container_class;
sigbuffer_add_value (buf, klass->byval_arg.type);
sigbuffer_add_value (buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
sigbuffer_add_value (buf, class_inst->type_argc);
for (i = 0; i < class_inst->type_argc; ++i)
encode_type (assembly, class_inst->type_argv [i], buf);
}
static void
encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf)
{
if (!type) {
g_assert_not_reached ();
return;
}
if (type->byref)
sigbuffer_add_value (buf, MONO_TYPE_BYREF);
switch (type->type){
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
sigbuffer_add_value (buf, type->type);
break;
case MONO_TYPE_PTR:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, type->data.type, buf);
break;
case MONO_TYPE_SZARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.klass->byval_arg, buf);
break;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS: {
MonoClass *k = mono_class_from_mono_type (type);
if (k->generic_container) {
MonoGenericClass *gclass = mono_metadata_lookup_generic_class (k, k->generic_container->context.class_inst, TRUE);
encode_generic_class (assembly, gclass, buf);
} else {
/*
* Make sure we use the correct type.
*/
sigbuffer_add_value (buf, k->byval_arg.type);
/*
* ensure only non-byref gets passed to mono_image_typedef_or_ref(),
* otherwise two typerefs could point to the same type, leading to
* verification errors.
*/
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, &k->byval_arg));
}
break;
}
case MONO_TYPE_ARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.array->eklass->byval_arg, buf);
sigbuffer_add_value (buf, type->data.array->rank);
sigbuffer_add_value (buf, 0); /* FIXME: set to 0 for now */
sigbuffer_add_value (buf, 0);
break;
case MONO_TYPE_GENERICINST:
encode_generic_class (assembly, type->data.generic_class, buf);
break;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
sigbuffer_add_value (buf, type->type);
sigbuffer_add_value (buf, mono_type_get_generic_param_num (type));
break;
default:
g_error ("need to encode type %x", type->type);
}
}
static void
encode_reflection_type (MonoDynamicImage *assembly, MonoReflectionType *type, SigBuffer *buf)
{
if (!type) {
sigbuffer_add_value (buf, MONO_TYPE_VOID);
return;
}
encode_type (assembly, mono_reflection_type_get_handle (type), buf);
}
static void
encode_custom_modifiers (MonoDynamicImage *assembly, MonoArray *modreq, MonoArray *modopt, SigBuffer *buf)
{
int i;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_REQD);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
method_encode_signature (MonoDynamicImage *assembly, MonoMethodSignature *sig)
{
SigBuffer buf;
int i;
guint32 nparams = sig->param_count;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
idx = sig->call_convention;
if (sig->hasthis)
idx |= 0x20; /* hasthis */
if (sig->generic_param_count)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (sig->generic_param_count)
sigbuffer_add_value (&buf, sig->generic_param_count);
sigbuffer_add_value (&buf, nparams);
encode_type (assembly, sig->ret, &buf);
for (i = 0; i < nparams; ++i) {
if (i == sig->sentinelpos)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
encode_type (assembly, sig->params [i], &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
method_builder_encode_signature (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
/*
* FIXME: reuse code from method_encode_signature().
*/
SigBuffer buf;
int i;
guint32 nparams = mb->parameters ? mono_array_length (mb->parameters): 0;
guint32 ngparams = mb->generic_params ? mono_array_length (mb->generic_params): 0;
guint32 notypes = mb->opt_types ? mono_array_length (mb->opt_types): 0;
guint32 idx;
sigbuffer_init (&buf, 32);
/* LAMESPEC: all the call conv spec is foobared */
idx = mb->call_conv & 0x60; /* has-this, explicit-this */
if (mb->call_conv & 2)
idx |= 0x5; /* vararg */
if (!(mb->attrs & METHOD_ATTRIBUTE_STATIC))
idx |= 0x20; /* hasthis */
if (ngparams)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (ngparams)
sigbuffer_add_value (&buf, ngparams);
sigbuffer_add_value (&buf, nparams + notypes);
encode_custom_modifiers (assembly, mb->return_modreq, mb->return_modopt, &buf);
encode_reflection_type (assembly, mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoArray *modreq = NULL;
MonoArray *modopt = NULL;
MonoReflectionType *pt;
if (mb->param_modreq && (i < mono_array_length (mb->param_modreq)))
modreq = mono_array_get (mb->param_modreq, MonoArray*, i);
if (mb->param_modopt && (i < mono_array_length (mb->param_modopt)))
modopt = mono_array_get (mb->param_modopt, MonoArray*, i);
encode_custom_modifiers (assembly, modreq, modopt, &buf);
pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
if (notypes)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
for (i = 0; i < notypes; ++i) {
MonoReflectionType *pt;
pt = mono_array_get (mb->opt_types, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_locals (MonoDynamicImage *assembly, MonoReflectionILGen *ilgen)
{
MonoDynamicTable *table;
guint32 *values;
guint32 idx, sig_idx;
guint nl = mono_array_length (ilgen->locals);
SigBuffer buf;
int i;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, nl);
for (i = 0; i < nl; ++i) {
MonoReflectionLocalBuilder *lb = mono_array_get (ilgen->locals, MonoReflectionLocalBuilder*, i);
if (lb->is_pinned)
sigbuffer_add_value (&buf, MONO_TYPE_PINNED);
encode_reflection_type (assembly, (MonoReflectionType*)lb->type, &buf);
}
sig_idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
if (assembly->standalonesig_cache == NULL)
assembly->standalonesig_cache = g_hash_table_new (NULL, NULL);
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx)));
if (idx)
return idx;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] = sig_idx;
g_hash_table_insert (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx), GUINT_TO_POINTER (idx));
return idx;
}
static guint32
method_count_clauses (MonoReflectionILGen *ilgen)
{
guint32 num_clauses = 0;
int i;
MonoILExceptionInfo *ex_info;
for (i = 0; i < mono_array_length (ilgen->ex_handlers); ++i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers)
num_clauses += mono_array_length (ex_info->handlers);
else
num_clauses++;
}
return num_clauses;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoExceptionClause*
method_encode_clauses (MonoImage *image, MonoDynamicImage *assembly, MonoReflectionILGen *ilgen, guint32 num_clauses)
{
MonoExceptionClause *clauses;
MonoExceptionClause *clause;
MonoILExceptionInfo *ex_info;
MonoILExceptionBlock *ex_block;
guint32 finally_start;
int i, j, clause_index;;
clauses = image_g_new0 (image, MonoExceptionClause, num_clauses);
clause_index = 0;
for (i = mono_array_length (ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
finally_start = ex_info->start + ex_info->len;
if (!ex_info->handlers)
continue;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
clause = &(clauses [clause_index]);
clause->flags = ex_block->type;
clause->try_offset = ex_info->start;
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
clause->try_len = finally_start - ex_info->start;
else
clause->try_len = ex_info->len;
clause->handler_offset = ex_block->start;
clause->handler_len = ex_block->len;
if (ex_block->extype) {
clause->data.catch_class = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
clause->data.filter_offset = ex_block->filter_offset;
else
clause->data.filter_offset = 0;
}
finally_start = ex_block->start + ex_block->len;
clause_index ++;
}
}
return clauses;
}
#endif /* !DISABLE_REFLECTION_EMIT */
static guint32
method_encode_code (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
char flags = 0;
guint32 idx;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_exception = 0;
gint maybe_small;
guint32 fat_flags;
char fat_header [12];
guint32 int_value;
guint16 short_value;
guint32 local_sig = 0;
guint32 header_size = 12;
MonoArray *code;
if ((mb->attrs & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT)) ||
(mb->iattrs & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)))
return 0;
/*if (mb->name)
g_print ("Encode method %s\n", mono_string_to_utf8 (mb->name));*/
if (mb->ilgen) {
code = mb->ilgen->code;
code_size = mb->ilgen->code_len;
max_stack = mb->ilgen->max_stack;
num_locals = mb->ilgen->locals ? mono_array_length (mb->ilgen->locals) : 0;
if (mb->ilgen->ex_handlers)
num_exception = method_count_clauses (mb->ilgen);
} else {
code = mb->code;
if (code == NULL){
char *name = mono_string_to_utf8 (mb->name);
char *str = g_strdup_printf ("Method %s does not have any IL associated", name);
MonoException *exception = mono_get_exception_argument (NULL, "a method does not have any IL associated");
g_free (str);
g_free (name);
mono_raise_exception (exception);
}
code_size = mono_array_length (code);
max_stack = 8; /* we probably need to run a verifier on the code... */
}
stream_data_align (&assembly->code);
/* check for exceptions, maxstack, locals */
maybe_small = (max_stack <= 8) && (!num_locals) && (!num_exception);
if (maybe_small) {
if (code_size < 64 && !(code_size & 1)) {
flags = (code_size << 2) | 0x2;
} else if (code_size < 32 && (code_size & 1)) {
flags = (code_size << 2) | 0x6; /* LAMESPEC: see metadata.c */
} else {
goto fat_header;
}
idx = mono_image_add_stream_data (&assembly->code, &flags, 1);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 1));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
return assembly->text_rva + idx;
}
fat_header:
if (num_locals)
local_sig = MONO_TOKEN_SIGNATURE | encode_locals (assembly, mb->ilgen);
/*
* FIXME: need to set also the header size in fat_flags.
* (and more sects and init locals flags)
*/
fat_flags = 0x03;
if (num_exception)
fat_flags |= METHOD_HEADER_MORE_SECTS;
if (mb->init_locals)
fat_flags |= METHOD_HEADER_INIT_LOCALS;
fat_header [0] = fat_flags;
fat_header [1] = (header_size / 4 ) << 4;
short_value = GUINT16_TO_LE (max_stack);
memcpy (fat_header + 2, &short_value, 2);
int_value = GUINT32_TO_LE (code_size);
memcpy (fat_header + 4, &int_value, 4);
int_value = GUINT32_TO_LE (local_sig);
memcpy (fat_header + 8, &int_value, 4);
idx = mono_image_add_stream_data (&assembly->code, fat_header, 12);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 12));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
if (num_exception) {
unsigned char sheader [4];
MonoILExceptionInfo * ex_info;
MonoILExceptionBlock * ex_block;
int j;
stream_data_align (&assembly->code);
/* always use fat format for now */
sheader [0] = METHOD_HEADER_SECTION_FAT_FORMAT | METHOD_HEADER_SECTION_EHTABLE;
num_exception *= 6 * sizeof (guint32);
num_exception += 4; /* include the size of the header */
sheader [1] = num_exception & 0xff;
sheader [2] = (num_exception >> 8) & 0xff;
sheader [3] = (num_exception >> 16) & 0xff;
mono_image_add_stream_data (&assembly->code, (char*)sheader, 4);
/* fat header, so we are already aligned */
/* reverse order */
for (i = mono_array_length (mb->ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo *)mono_array_addr (mb->ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers) {
int finally_start = ex_info->start + ex_info->len;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
guint32 val;
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
/* the flags */
val = GUINT32_TO_LE (ex_block->type);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* try offset */
val = GUINT32_TO_LE (ex_info->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* need fault, too, probably */
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
val = GUINT32_TO_LE (finally_start - ex_info->start);
else
val = GUINT32_TO_LE (ex_info->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler offset */
val = GUINT32_TO_LE (ex_block->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler len */
val = GUINT32_TO_LE (ex_block->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
finally_start = ex_block->start + ex_block->len;
if (ex_block->extype) {
val = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype)));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
val = ex_block->filter_offset;
else
val = 0;
}
val = GUINT32_TO_LE (val);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/*g_print ("out clause %d: from %d len=%d, handler at %d, %d, finally_start=%d, ex_info->start=%d, ex_info->len=%d, ex_block->type=%d, j=%d, i=%d\n",
clause.flags, clause.try_offset, clause.try_len, clause.handler_offset, clause.handler_len, finally_start, ex_info->start, ex_info->len, ex_block->type, j, i);*/
}
} else {
g_error ("No clauses for ex info block %d", i);
}
}
}
return assembly->text_rva + idx;
}
static guint32
find_index_in_table (MonoDynamicImage *assembly, int table_idx, int col, guint32 token)
{
int i;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [table_idx];
g_assert (col < table->columns);
values = table->values + table->columns;
for (i = 1; i <= table->rows; ++i) {
if (values [col] == token)
return i;
values += table->columns;
}
return 0;
}
/*
* LOCKING: Acquires the loader lock.
*/
static MonoCustomAttrInfo*
lookup_custom_attr (MonoImage *image, gpointer member)
{
MonoCustomAttrInfo* res;
res = mono_image_property_lookup (image, member, MONO_PROP_DYNAMIC_CATTR);
if (!res)
return NULL;
return g_memdup (res, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * res->num_attrs);
}
static gboolean
custom_attr_visible (MonoImage *image, MonoReflectionCustomAttr *cattr)
{
/* FIXME: Need to do more checks */
if (cattr->ctor->method && (cattr->ctor->method->klass->image != image)) {
int visibility = cattr->ctor->method->klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if ((visibility != TYPE_ATTRIBUTE_PUBLIC) && (visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC))
return FALSE;
}
return TRUE;
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders (MonoImage *alloc_img, MonoImage *image, MonoArray *cattrs)
{
int i, index, count, not_visible;
MonoCustomAttrInfo *ainfo;
MonoReflectionCustomAttr *cattr;
if (!cattrs)
return NULL;
/* FIXME: check in assembly the Run flag is set */
count = mono_array_length (cattrs);
/* Skip nonpublic attributes since MS.NET seems to do the same */
/* FIXME: This needs to be done more globally */
not_visible = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (!custom_attr_visible (image, cattr))
not_visible ++;
}
count -= not_visible;
ainfo = image_g_malloc0 (alloc_img, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * count);
ainfo->image = image;
ainfo->num_attrs = count;
ainfo->cached = alloc_img != NULL;
index = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (custom_attr_visible (image, cattr)) {
unsigned char *saved = mono_image_alloc (image, mono_array_length (cattr->data));
memcpy (saved, mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
ainfo->attrs [index].ctor = cattr->ctor->method;
ainfo->attrs [index].data = saved;
ainfo->attrs [index].data_size = mono_array_length (cattr->data);
index ++;
}
}
return ainfo;
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* LOCKING: Acquires the loader lock.
*/
static void
mono_save_custom_attrs (MonoImage *image, void *obj, MonoArray *cattrs)
{
MonoCustomAttrInfo *ainfo, *tmp;
if (!cattrs || !mono_array_length (cattrs))
return;
ainfo = mono_custom_attrs_from_builders (image, image, cattrs);
mono_loader_lock ();
tmp = mono_image_property_lookup (image, obj, MONO_PROP_DYNAMIC_CATTR);
if (tmp)
mono_custom_attrs_free (tmp);
mono_image_property_insert (image, obj, MONO_PROP_DYNAMIC_CATTR, ainfo);
mono_loader_unlock ();
}
#endif
void
mono_custom_attrs_free (MonoCustomAttrInfo *ainfo)
{
if (!ainfo->cached)
g_free (ainfo);
}
/*
* idx is the table index of the object
* type is one of MONO_CUSTOM_ATTR_*
*/
static void
mono_image_add_cattrs (MonoDynamicImage *assembly, guint32 idx, guint32 type, MonoArray *cattrs)
{
MonoDynamicTable *table;
MonoReflectionCustomAttr *cattr;
guint32 *values;
guint32 count, i, token;
char blob_size [6];
char *p = blob_size;
/* it is legal to pass a NULL cattrs: we avoid to use the if in a lot of places */
if (!cattrs)
return;
count = mono_array_length (cattrs);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_CUSTOM_ATTR_SIZE;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= type;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
values [MONO_CUSTOM_ATTR_PARENT] = idx;
token = mono_image_create_token (assembly, (MonoObject*)cattr->ctor, FALSE, FALSE);
type = mono_metadata_token_index (token);
type <<= MONO_CUSTOM_ATTR_TYPE_BITS;
switch (mono_metadata_token_table (token)) {
case MONO_TABLE_METHOD:
type |= MONO_CUSTOM_ATTR_TYPE_METHODDEF;
break;
case MONO_TABLE_MEMBERREF:
type |= MONO_CUSTOM_ATTR_TYPE_MEMBERREF;
break;
default:
g_warning ("got wrong token in custom attr");
continue;
}
values [MONO_CUSTOM_ATTR_TYPE] = type;
p = blob_size;
mono_metadata_encode_value (mono_array_length (cattr->data), p, &p);
values [MONO_CUSTOM_ATTR_VALUE] = add_to_blob_cached (assembly, blob_size, p - blob_size,
mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
values += MONO_CUSTOM_ATTR_SIZE;
++table->next_idx;
}
}
static void
mono_image_add_decl_security (MonoDynamicImage *assembly, guint32 parent_token, MonoArray *permissions)
{
MonoDynamicTable *table;
guint32 *values;
guint32 count, i, idx;
MonoReflectionPermissionSet *perm;
if (!permissions)
return;
count = mono_array_length (permissions);
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
table->rows += count;
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (permissions); ++i) {
perm = (MonoReflectionPermissionSet*)mono_array_addr (permissions, MonoReflectionPermissionSet, i);
values = table->values + table->next_idx * MONO_DECL_SECURITY_SIZE;
idx = mono_metadata_token_index (parent_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
switch (mono_metadata_token_table (parent_token)) {
case MONO_TABLE_TYPEDEF:
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
break;
case MONO_TABLE_METHOD:
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
break;
case MONO_TABLE_ASSEMBLY:
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
break;
default:
g_assert_not_reached ();
}
values [MONO_DECL_SECURITY_ACTION] = perm->action;
values [MONO_DECL_SECURITY_PARENT] = idx;
values [MONO_DECL_SECURITY_PERMISSIONSET] = add_mono_string_to_blob_cached (assembly, perm->pset);
++table->next_idx;
}
}
/*
* Fill in the MethodDef and ParamDef tables for a method.
* This is used for both normal methods and constructors.
*/
static void
mono_image_basic_method (ReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint i, count;
/* room in this table is already allocated */
table = &assembly->tables [MONO_TABLE_METHOD];
*mb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->method_to_table_idx, mb->mhandle, GUINT_TO_POINTER ((*mb->table_idx)));
values = table->values + *mb->table_idx * MONO_METHOD_SIZE;
values [MONO_METHOD_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
values [MONO_METHOD_FLAGS] = mb->attrs;
values [MONO_METHOD_IMPLFLAGS] = mb->iattrs;
values [MONO_METHOD_SIGNATURE] = method_builder_encode_signature (assembly, mb);
values [MONO_METHOD_RVA] = method_encode_code (assembly, mb);
table = &assembly->tables [MONO_TABLE_PARAM];
values [MONO_METHOD_PARAMLIST] = table->next_idx;
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_METHOD, *mb->table_idx), mb->permissions);
if (mb->pinfo) {
MonoDynamicTable *mtable;
guint32 *mvalues;
mtable = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
mvalues = mtable->values + mtable->next_idx * MONO_FIELD_MARSHAL_SIZE;
count = 0;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
if (mono_array_get (mb->pinfo, gpointer, i))
count++;
}
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_PARAM_SIZE;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (mb->pinfo, MonoReflectionParamBuilder*, i))) {
values [MONO_PARAM_FLAGS] = pb->attrs;
values [MONO_PARAM_SEQUENCE] = i;
if (pb->name != NULL) {
values [MONO_PARAM_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
} else {
values [MONO_PARAM_NAME] = 0;
}
values += MONO_PARAM_SIZE;
if (pb->marshal_info) {
mtable->rows++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_FIELD_MARSHAL_SIZE;
mvalues [MONO_FIELD_MARSHAL_PARENT] = (table->next_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_PARAMDEF;
mvalues [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, pb->marshal_info);
}
pb->table_idx = table->next_idx++;
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
guint32 field_type = 0;
mtable = &assembly->tables [MONO_TABLE_CONSTANT];
mtable->rows ++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_CONSTANT_SIZE;
mvalues [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_PARAM | (pb->table_idx << MONO_HASCONSTANT_BITS);
mvalues [MONO_CONSTANT_VALUE] = encode_constant (assembly, pb->def_value, &field_type);
mvalues [MONO_CONSTANT_TYPE] = field_type;
mvalues [MONO_CONSTANT_PADDING] = 0;
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static void
reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_reflection_type_resolve_user_types ((MonoReflectionType*)mb->rtype);
rmb->parameters = mb->parameters;
rmb->generic_params = mb->generic_params;
rmb->generic_container = mb->generic_container;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = mb->code;
rmb->type = mb->type;
rmb->name = mb->name;
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = mb->return_modreq;
rmb->return_modopt = mb->return_modopt;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
if (mb->dll) {
rmb->charset = mb->charset;
rmb->extra_flags = mb->extra_flags;
rmb->native_cc = mb->native_cc;
rmb->dllentry = mb->dllentry;
rmb->dll = mb->dll;
}
}
static void
reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb)
{
const char *name = mb->attrs & METHOD_ATTRIBUTE_STATIC ? ".cctor": ".ctor";
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_type_get_object (mono_domain_get (), &mono_defaults.void_class->byval_arg);
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = mb->type;
rmb->name = mono_string_new (mono_domain_get (), name);
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
static void
reflection_methodbuilder_from_dynamic_method (ReflectionMethodBuilder *rmb, MonoReflectionDynamicMethod *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mb->rtype;
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = NULL;
rmb->attrs = mb->attrs;
rmb->iattrs = 0;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = (MonoObject *) mb->owner;
rmb->name = mb->name;
rmb->table_idx = NULL;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = mb->skip_visibility;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = NULL;
rmb->param_modopt = NULL;
rmb->permissions = NULL;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
#endif
static void
mono_image_add_methodimpl (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
MonoDynamicTable *table;
guint32 *values;
guint32 tok;
if (!mb->override_method)
return;
table = &assembly->tables [MONO_TABLE_METHODIMPL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_METHODIMPL_SIZE;
values [MONO_METHODIMPL_CLASS] = tb->table_idx;
values [MONO_METHODIMPL_BODY] = MONO_METHODDEFORREF_METHODDEF | (mb->table_idx << MONO_METHODDEFORREF_BITS);
tok = mono_image_create_token (assembly, (MonoObject*)mb->override_method, FALSE, FALSE);
switch (mono_metadata_token_table (tok)) {
case MONO_TABLE_MEMBERREF:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
values [MONO_METHODIMPL_DECLARATION] = tok;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
mono_image_get_method_info (MonoReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
ReflectionMethodBuilder rmb;
int i;
reflection_methodbuilder_from_method_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
if (mb->dll) { /* It's a P/Invoke method */
guint32 moduleref;
/* map CharSet values to on-disk values */
int ncharset = (mb->charset ? (mb->charset - 1) * 2 : 0);
int extra_flags = mb->extra_flags;
table = &assembly->tables [MONO_TABLE_IMPLMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_IMPLMAP_SIZE;
values [MONO_IMPLMAP_FLAGS] = (mb->native_cc << 8) | ncharset | extra_flags;
values [MONO_IMPLMAP_MEMBER] = (mb->table_idx << 1) | 1; /* memberforwarded: method */
if (mb->dllentry)
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->dllentry);
else
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
moduleref = string_heap_insert_mstring (&assembly->sheap, mb->dll);
if (!(values [MONO_IMPLMAP_SCOPE] = find_index_in_table (assembly, MONO_TABLE_MODULEREF, MONO_MODULEREF_NAME, moduleref))) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
table->rows ++;
alloc_table (table, table->rows);
table->values [table->rows * MONO_MODULEREF_SIZE + MONO_MODULEREF_NAME] = moduleref;
values [MONO_IMPLMAP_SCOPE] = table->rows;
}
}
if (mb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (mb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (mb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_METHOD | (mb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (mb->generic_params, gpointer, i), owner, assembly);
}
}
}
static void
mono_image_get_ctor_info (MonoDomain *domain, MonoReflectionCtorBuilder *mb, MonoDynamicImage *assembly)
{
ReflectionMethodBuilder rmb;
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
}
#endif
static char*
type_get_fully_qualified_name (MonoType *type)
{
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
static char*
type_get_qualified_name (MonoType *type, MonoAssembly *ass) {
MonoClass *klass;
MonoAssembly *ta;
klass = mono_class_from_mono_type (type);
if (!klass)
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
ta = klass->image->assembly;
if (ta->dynamic || (ta == ass)) {
if (klass->generic_class || klass->generic_container)
/* For generic type definitions, we want T, while REFLECTION returns T<K> */
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_FULL_NAME);
else
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
}
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
#ifndef DISABLE_REFLECTION_EMIT
/*field_image is the image to which the eventual custom mods have been encoded against*/
static guint32
fieldref_encode_signature (MonoDynamicImage *assembly, MonoImage *field_image, MonoType *type)
{
SigBuffer buf;
guint32 idx, i, token;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
/* encode custom attributes before the type */
if (type->num_mods) {
for (i = 0; i < type->num_mods; ++i) {
if (field_image) {
MonoClass *class = mono_class_get (field_image, type->modifiers [i].token);
g_assert (class);
token = mono_image_typedef_or_ref (assembly, &class->byval_arg);
} else {
token = type->modifiers [i].token;
}
if (type->modifiers [i].required)
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_REQD);
else
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (&buf, token);
}
}
encode_type (assembly, type, &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
field_encode_signature (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
SigBuffer buf;
guint32 idx;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
encode_custom_modifiers (assembly, fb->modreq, fb->modopt, &buf);
/* encode custom attributes before the type */
encode_reflection_type (assembly, (MonoReflectionType*)fb->type, &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type) {
char blob_size [64];
char *b = blob_size;
char *p, *box_val;
char* buf;
guint32 idx = 0, len = 0, dummy = 0;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
guint32 fpa_double [2];
guint32 *fpa_p;
#endif
#endif
p = buf = g_malloc (64);
if (!val) {
*ret_type = MONO_TYPE_CLASS;
len = 4;
box_val = (char*)&dummy;
} else {
box_val = ((char*)val) + sizeof (MonoObject);
*ret_type = val->vtable->klass->byval_arg.type;
}
handle_enum:
switch (*ret_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
len = 1;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
len = 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
len = 4;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
len = 8;
break;
case MONO_TYPE_R8:
len = 8;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
fpa_p = (guint32*)box_val;
fpa_double [0] = fpa_p [1];
fpa_double [1] = fpa_p [0];
box_val = (char*)fpa_double;
#endif
#endif
break;
case MONO_TYPE_VALUETYPE: {
MonoClass *klass = val->vtable->klass;
if (klass->enumtype) {
*ret_type = mono_class_enum_basetype (klass)->type;
goto handle_enum;
} else if (mono_is_corlib_image (klass->image) && strcmp (klass->name_space, "System") == 0 && strcmp (klass->name, "DateTime") == 0) {
len = 8;
} else
g_error ("we can't encode valuetypes, we should have never reached this line");
break;
}
case MONO_TYPE_CLASS:
break;
case MONO_TYPE_STRING: {
MonoString *str = (MonoString*)val;
/* there is no signature */
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
g_free (buf);
return idx;
}
case MONO_TYPE_GENERICINST:
*ret_type = val->vtable->klass->generic_class->container_class->byval_arg.type;
goto handle_enum;
default:
g_error ("we don't encode constant type 0x%02x yet", *ret_type);
}
/* there is no signature */
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
idx = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
swap_with_size (blob_size, box_val, len, 1);
mono_image_add_stream_data (&assembly->blob, blob_size, len);
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, box_val, len);
#endif
g_free (buf);
return idx;
}
static guint32
encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo) {
char *str;
SigBuffer buf;
guint32 idx, len;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, minfo->type);
switch (minfo->type) {
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
sigbuffer_add_value (&buf, minfo->count);
break;
case MONO_NATIVE_LPARRAY:
if (minfo->eltype || minfo->has_size) {
sigbuffer_add_value (&buf, minfo->eltype);
if (minfo->has_size) {
sigbuffer_add_value (&buf, minfo->param_num != -1? minfo->param_num: 0);
sigbuffer_add_value (&buf, minfo->count != -1? minfo->count: 0);
/* LAMESPEC: ElemMult is undocumented */
sigbuffer_add_value (&buf, minfo->param_num != -1? 1: 0);
}
}
break;
case MONO_NATIVE_SAFEARRAY:
if (minfo->eltype)
sigbuffer_add_value (&buf, minfo->eltype);
break;
case MONO_NATIVE_CUSTOM:
if (minfo->guid) {
str = mono_string_to_utf8 (minfo->guid);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
/* native type name */
sigbuffer_add_value (&buf, 0);
/* custom marshaler type name */
if (minfo->marshaltype || minfo->marshaltyperef) {
if (minfo->marshaltyperef)
str = type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
else
str = mono_string_to_utf8 (minfo->marshaltype);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
/* FIXME: Actually a bug, since this field is required. Punting for now ... */
sigbuffer_add_value (&buf, 0);
}
if (minfo->mcookie) {
str = mono_string_to_utf8 (minfo->mcookie);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
break;
default:
break;
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_field_info (MonoReflectionFieldBuilder *fb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
/* maybe this fixup should be done in the C# code */
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL)
fb->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
table = &assembly->tables [MONO_TABLE_FIELD];
fb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->field_to_table_idx, fb->handle, GUINT_TO_POINTER (fb->table_idx));
values = table->values + fb->table_idx * MONO_FIELD_SIZE;
values [MONO_FIELD_NAME] = string_heap_insert_mstring (&assembly->sheap, fb->name);
values [MONO_FIELD_FLAGS] = fb->attrs;
values [MONO_FIELD_SIGNATURE] = field_encode_signature (assembly, fb);
if (fb->offset != -1) {
table = &assembly->tables [MONO_TABLE_FIELDLAYOUT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_LAYOUT_SIZE;
values [MONO_FIELD_LAYOUT_FIELD] = fb->table_idx;
values [MONO_FIELD_LAYOUT_OFFSET] = fb->offset;
}
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL) {
guint32 field_type = 0;
table = &assembly->tables [MONO_TABLE_CONSTANT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CONSTANT_SIZE;
values [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_FIEDDEF | (fb->table_idx << MONO_HASCONSTANT_BITS);
values [MONO_CONSTANT_VALUE] = encode_constant (assembly, fb->def_value, &field_type);
values [MONO_CONSTANT_TYPE] = field_type;
values [MONO_CONSTANT_PADDING] = 0;
}
if (fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
guint32 rva_idx;
table = &assembly->tables [MONO_TABLE_FIELDRVA];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_RVA_SIZE;
values [MONO_FIELD_RVA_FIELD] = fb->table_idx;
/*
* We store it in the code section because it's simpler for now.
*/
if (fb->rva_data) {
if (mono_array_length (fb->rva_data) >= 10)
stream_data_align (&assembly->code);
rva_idx = mono_image_add_stream_data (&assembly->code, mono_array_addr (fb->rva_data, char, 0), mono_array_length (fb->rva_data));
} else
rva_idx = mono_image_add_stream_zero (&assembly->code, mono_class_value_size (fb->handle->parent, NULL));
values [MONO_FIELD_RVA_RVA] = rva_idx + assembly->text_rva;
}
if (fb->marshal_info) {
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_MARSHAL_SIZE;
values [MONO_FIELD_MARSHAL_PARENT] = (fb->table_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_FIELDSREF;
values [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, fb->marshal_info);
}
}
static guint32
property_encode_signature (MonoDynamicImage *assembly, MonoReflectionPropertyBuilder *fb)
{
SigBuffer buf;
guint32 nparams = 0;
MonoReflectionMethodBuilder *mb = fb->get_method;
MonoReflectionMethodBuilder *smb = fb->set_method;
guint32 idx, i;
if (mb && mb->parameters)
nparams = mono_array_length (mb->parameters);
if (!mb && smb && smb->parameters)
nparams = mono_array_length (smb->parameters) - 1;
sigbuffer_init (&buf, 32);
if (fb->call_conv & 0x20)
sigbuffer_add_byte (&buf, 0x28);
else
sigbuffer_add_byte (&buf, 0x08);
sigbuffer_add_value (&buf, nparams);
if (mb) {
encode_reflection_type (assembly, (MonoReflectionType*)mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else if (smb && smb->parameters) {
/* the property type is the last param */
encode_reflection_type (assembly, mono_array_get (smb->parameters, MonoReflectionType*, nparams), &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (smb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else {
encode_reflection_type (assembly, (MonoReflectionType*)fb->type, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_property_info (MonoReflectionPropertyBuilder *pb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* PROPERTYMAP (info already filled in _get_type_info ())
* PROPERTY (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
* CONSTANT
*/
table = &assembly->tables [MONO_TABLE_PROPERTY];
pb->table_idx = table->next_idx ++;
values = table->values + pb->table_idx * MONO_PROPERTY_SIZE;
values [MONO_PROPERTY_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
values [MONO_PROPERTY_FLAGS] = pb->attrs;
values [MONO_PROPERTY_TYPE] = property_encode_signature (assembly, pb);
/* FIXME: we still don't handle 'other' methods */
if (pb->get_method) num_methods ++;
if (pb->set_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (pb->get_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_GETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->get_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
if (pb->set_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_SETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->set_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
if (pb->attrs & PROPERTY_ATTRIBUTE_HAS_DEFAULT) {
guint32 field_type = 0;
table = &assembly->tables [MONO_TABLE_CONSTANT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CONSTANT_SIZE;
values [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_PROPERTY | (pb->table_idx << MONO_HASCONSTANT_BITS);
values [MONO_CONSTANT_VALUE] = encode_constant (assembly, pb->def_value, &field_type);
values [MONO_CONSTANT_TYPE] = field_type;
values [MONO_CONSTANT_PADDING] = 0;
}
}
static void
mono_image_get_event_info (MonoReflectionEventBuilder *eb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* EVENTMAP (info already filled in _get_type_info ())
* EVENT (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
*/
table = &assembly->tables [MONO_TABLE_EVENT];
eb->table_idx = table->next_idx ++;
values = table->values + eb->table_idx * MONO_EVENT_SIZE;
values [MONO_EVENT_NAME] = string_heap_insert_mstring (&assembly->sheap, eb->name);
values [MONO_EVENT_FLAGS] = eb->attrs;
values [MONO_EVENT_TYPE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (eb->type));
/*
* FIXME: we still don't handle 'other' methods
*/
if (eb->add_method) num_methods ++;
if (eb->remove_method) num_methods ++;
if (eb->raise_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (eb->add_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_ADD_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->add_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->remove_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_REMOVE_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->remove_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->raise_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_FIRE;
values [MONO_METHOD_SEMA_METHOD] = eb->raise_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
}
static void
encode_constraints (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 num_constraints, i;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
num_constraints = gparam->iface_constraints ?
mono_array_length (gparam->iface_constraints) : 0;
table->rows += num_constraints;
if (gparam->base_type)
table->rows++;
alloc_table (table, table->rows);
if (gparam->base_type) {
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (gparam->base_type));
}
for (i = 0; i < num_constraints; i++) {
MonoReflectionType *constraint = mono_array_get (
gparam->iface_constraints, gpointer, i);
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (constraint));
}
}
static void
mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
GenericParamTableEntry *entry;
/*
* The GenericParam table must be sorted according to the `owner' field.
* We need to do this sorting prior to writing the GenericParamConstraint
* table, since we have to use the final GenericParam table indices there
* and they must also be sorted.
*/
entry = g_new0 (GenericParamTableEntry, 1);
entry->owner = owner;
/* FIXME: track where gen_params should be freed and remove the GC root as well */
MOVING_GC_REGISTER (&entry->gparam);
entry->gparam = gparam;
g_ptr_array_add (assembly->gen_params, entry);
}
static void
write_generic_param_entry (MonoDynamicImage *assembly, GenericParamTableEntry *entry)
{
MonoDynamicTable *table;
MonoGenericParam *param;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENERICPARAM_SIZE;
param = mono_reflection_type_get_handle ((MonoReflectionType*)entry->gparam)->data.generic_param;
values [MONO_GENERICPARAM_OWNER] = entry->owner;
values [MONO_GENERICPARAM_FLAGS] = entry->gparam->attrs;
values [MONO_GENERICPARAM_NUMBER] = mono_generic_param_num (param);
values [MONO_GENERICPARAM_NAME] = string_heap_insert (&assembly->sheap, mono_generic_param_info (param)->name);
mono_image_add_cattrs (assembly, table_idx, MONO_CUSTOM_ATTR_GENERICPAR, entry->gparam->cattrs);
encode_constraints (entry->gparam, table_idx, assembly);
}
static guint32
resolution_scope_from_image (MonoDynamicImage *assembly, MonoImage *image)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
guint32 cols [MONO_ASSEMBLY_SIZE];
const char *pubkey;
guint32 publen;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, image))))
return token;
if (image->assembly->dynamic && (image->assembly == assembly->image.assembly)) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_MODULEREF_SIZE;
values [MONO_MODULEREF_NAME] = string_heap_insert (&assembly->sheap, image->module_name);
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_MODULEREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
if (image->assembly->dynamic)
/* FIXME: */
memset (cols, 0, sizeof (cols));
else {
/* image->assembly->image is the manifest module */
image = image->assembly->image;
mono_metadata_decode_row (&image->tables [MONO_TABLE_ASSEMBLY], 0, cols, MONO_ASSEMBLY_SIZE);
}
table = &assembly->tables [MONO_TABLE_ASSEMBLYREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_ASSEMBLYREF_SIZE;
values [MONO_ASSEMBLYREF_NAME] = string_heap_insert (&assembly->sheap, image->assembly_name);
values [MONO_ASSEMBLYREF_MAJOR_VERSION] = cols [MONO_ASSEMBLY_MAJOR_VERSION];
values [MONO_ASSEMBLYREF_MINOR_VERSION] = cols [MONO_ASSEMBLY_MINOR_VERSION];
values [MONO_ASSEMBLYREF_BUILD_NUMBER] = cols [MONO_ASSEMBLY_BUILD_NUMBER];
values [MONO_ASSEMBLYREF_REV_NUMBER] = cols [MONO_ASSEMBLY_REV_NUMBER];
values [MONO_ASSEMBLYREF_FLAGS] = 0;
values [MONO_ASSEMBLYREF_CULTURE] = 0;
values [MONO_ASSEMBLYREF_HASH_VALUE] = 0;
if (strcmp ("", image->assembly->aname.culture)) {
values [MONO_ASSEMBLYREF_CULTURE] = string_heap_insert (&assembly->sheap,
image->assembly->aname.culture);
}
if ((pubkey = mono_image_get_public_key (image, &publen))) {
guchar pubtoken [9];
pubtoken [0] = 8;
mono_digest_get_public_token (pubtoken + 1, (guchar*)pubkey, publen);
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = mono_image_add_stream_data (&assembly->blob, (char*)pubtoken, 9);
} else {
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = 0;
}
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_ASSEMBLYREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
static guint32
create_typespec (MonoDynamicImage *assembly, MonoType *type)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token;
SigBuffer buf;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type))))
return token;
sigbuffer_init (&buf, 32);
switch (type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_GENERICINST:
encode_type (assembly, type, &buf);
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE: {
MonoClass *k = mono_class_from_mono_type (type);
if (!k || !k->generic_container) {
sigbuffer_free (&buf);
return 0;
}
encode_type (assembly, type, &buf);
break;
}
default:
sigbuffer_free (&buf);
return 0;
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
static guint32
mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, scope, enclosing;
MonoClass *klass;
/* if the type requires a typespec, we must try that first*/
if (try_typespec && (token = create_typespec (assembly, type)))
return token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typeref, type));
if (token)
return token;
klass = mono_class_from_mono_type (type);
if (!klass)
klass = mono_class_from_mono_type (type);
/*
* If it's in the same module and not a generic type parameter:
*/
if ((klass->image == &assembly->image) && (type->type != MONO_TYPE_VAR) &&
(type->type != MONO_TYPE_MVAR)) {
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
token = MONO_TYPEDEFORREF_TYPEDEF | (tb->table_idx << MONO_TYPEDEFORREF_BITS);
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), mono_class_get_ref_info (klass));
return token;
}
if (klass->nested_in) {
enclosing = mono_image_typedef_or_ref_full (assembly, &klass->nested_in->byval_arg, FALSE);
/* get the typeref idx of the enclosing type */
enclosing >>= MONO_TYPEDEFORREF_BITS;
scope = (enclosing << MONO_RESOLTION_SCOPE_BITS) | MONO_RESOLTION_SCOPE_TYPEREF;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
}
table = &assembly->tables [MONO_TABLE_TYPEREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPEREF_SIZE;
values [MONO_TYPEREF_SCOPE] = scope;
values [MONO_TYPEREF_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_TYPEREF_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
}
token = MONO_TYPEDEFORREF_TYPEREF | (table->next_idx << MONO_TYPEDEFORREF_BITS); /* typeref */
g_hash_table_insert (assembly->typeref, type, GUINT_TO_POINTER(token));
table->next_idx ++;
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), mono_class_get_ref_info (klass));
return token;
}
/*
* Despite the name, we handle also TypeSpec (with the above helper).
*/
static guint32
mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type)
{
return mono_image_typedef_or_ref_full (assembly, type, TRUE);
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_add_memberef_row (MonoDynamicImage *assembly, guint32 parent, const char *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, pclass;
switch (parent & MONO_TYPEDEFORREF_MASK) {
case MONO_TYPEDEFORREF_TYPEREF:
pclass = MONO_MEMBERREF_PARENT_TYPEREF;
break;
case MONO_TYPEDEFORREF_TYPESPEC:
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
break;
case MONO_TYPEDEFORREF_TYPEDEF:
pclass = MONO_MEMBERREF_PARENT_TYPEDEF;
break;
default:
g_warning ("unknown typeref or def token 0x%08x for %s", parent, name);
return 0;
}
/* extract the index */
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
/*
* Insert a memberef row into the metadata: the token that point to the memberref
* is returned. Caching is done in the caller (mono_image_get_methodref_token() or
* mono_image_get_fieldref_token()).
* The sig param is an index to an already built signature.
*/
static guint32
mono_image_get_memberref_token (MonoDynamicImage *assembly, MonoType *type, const char *name, guint32 sig)
{
guint32 parent = mono_image_typedef_or_ref (assembly, type);
return mono_image_add_memberef_row (assembly, parent, name, sig);
}
static guint32
mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec)
{
guint32 token;
MonoMethodSignature *sig;
create_typespec = create_typespec && method->is_generic && method->klass->image != &assembly->image;
if (create_typespec) {
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1)));
if (token)
return token;
}
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token && !create_typespec)
return token;
g_assert (!method->is_inflated);
if (!token) {
/*
* A methodref signature can't contain an unmanaged calling convention.
*/
sig = mono_metadata_signature_dup (mono_method_signature (method));
if ((sig->call_convention != MONO_CALL_DEFAULT) && (sig->call_convention != MONO_CALL_VARARG))
sig->call_convention = MONO_CALL_DEFAULT;
token = mono_image_get_memberref_token (assembly, &method->klass->byval_arg,
method->name, method_encode_signature (assembly, sig));
g_free (sig);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
}
if (create_typespec) {
MonoDynamicTable *table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF);
token = (mono_metadata_token_index (token) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
if (assembly->save) {
guint32 *values;
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = token;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_sig (assembly, &mono_method_get_generic_container (method)->context);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
/*methodspec and memberef tokens are diferent, */
g_hash_table_insert (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1), GUINT_TO_POINTER (token));
return token;
}
return token;
}
static guint32
mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method)
{
guint32 token, parent, sig;
ReflectionMethodBuilder rmb;
char *name;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)method->type;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
name = mono_string_to_utf8 (method->name);
reflection_methodbuilder_from_method_builder (&rmb, method);
/*
* A methodref signature can't contain an unmanaged calling convention.
* Since some flags are encoded as part of call_conv, we need to check against it.
*/
if ((rmb.call_conv & ~0x60) != MONO_CALL_DEFAULT && (rmb.call_conv & ~0x60) != MONO_CALL_VARARG)
rmb.call_conv = (rmb.call_conv & 0x60) | MONO_CALL_DEFAULT;
sig = method_builder_encode_signature (assembly, &rmb);
if (tb->generic_params)
parent = create_generic_typespec (assembly, tb);
else
parent = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type));
token = mono_image_add_memberef_row (assembly, parent, name, sig);
g_free (name);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_varargs_method_token (MonoDynamicImage *assembly, guint32 original,
const gchar *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = original;
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
encode_generic_method_definition_sig (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
SigBuffer buf;
int i;
guint32 nparams = mono_array_length (mb->generic_params);
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0xa);
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++) {
sigbuffer_add_value (&buf, MONO_TYPE_MVAR);
sigbuffer_add_value (&buf, i);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_methodspec_token_for_generic_method_definition (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->methodspec, mb));
if (token)
return token;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
mtoken = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_definition_sig (assembly, mb);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
mono_g_hash_table_insert (assembly->methodspec, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec)
{
guint32 token;
if (mb->generic_params && create_methodspec)
return mono_image_get_methodspec_token_for_generic_method_definition (assembly, mb);
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
if (token)
return token;
token = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *mb)
{
guint32 token, parent, sig;
ReflectionMethodBuilder rmb;
char *name;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, mb));
if (token)
return token;
g_assert (tb->generic_params);
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
parent = create_generic_typespec (assembly, tb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_add_memberef_row (assembly, parent, name, sig);
g_free (name);
mono_g_hash_table_insert (assembly->handleref_managed, mb, GUINT_TO_POINTER(token));
return token;
}
#endif
static gboolean
is_field_on_inst (MonoClassField *field)
{
return (field->parent->generic_class && field->parent->generic_class->is_dynamic && ((MonoDynamicGenericClass*)field->parent->generic_class)->fields);
}
/*
* If FIELD is a field of a MonoDynamicGenericClass, return its non-inflated type.
*/
static MonoType*
get_field_on_inst_generic_type (MonoClassField *field)
{
MonoClass *class, *gtd;
MonoDynamicGenericClass *dgclass;
int field_index;
g_assert (is_field_on_inst (field));
dgclass = (MonoDynamicGenericClass*)field->parent->generic_class;
if (field >= dgclass->fields && field - dgclass->fields < dgclass->count_fields) {
field_index = field - dgclass->fields;
return dgclass->field_generic_types [field_index];
}
class = field->parent;
gtd = class->generic_class->container_class;
if (field >= class->fields && field - class->fields < class->field.count) {
field_index = field - class->fields;
return gtd->fields [field_index].type;
}
g_assert_not_reached ();
return 0;
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoObject *f, MonoClassField *field)
{
MonoType *type;
guint32 token;
g_assert (field);
g_assert (field->parent);
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, f));
if (token)
return token;
if (field->parent->generic_class && field->parent->generic_class->container_class && field->parent->generic_class->container_class->fields) {
int index = field - field->parent->fields;
type = field->parent->generic_class->container_class->fields [index].type;
} else {
if (is_field_on_inst (field))
type = get_field_on_inst_generic_type (field);
else
type = field->type;
}
token = mono_image_get_memberref_token (assembly, &field->parent->byval_arg,
mono_field_get_name (field),
fieldref_encode_signature (assembly, field->parent->image, type));
mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_field_on_inst_token (MonoDynamicImage *assembly, MonoReflectionFieldOnTypeBuilderInst *f)
{
guint32 token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoType *type;
char *name;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, f));
if (token)
return token;
if (is_sre_field_builder (mono_object_class (f->fb))) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)f->fb;
type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
name = mono_string_to_utf8 (fb->name);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name,
field_encode_signature (assembly, fb));
g_free (name);
} else if (is_sr_mono_field (mono_object_class (f->fb))) {
guint32 sig;
MonoClassField *field = ((MonoReflectionField *)f->fb)->field;
type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
klass = mono_class_from_mono_type (type);
sig = fieldref_encode_signature (assembly, field->parent->image, field->type);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, field->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (f->fb));
g_error ("mono_image_get_field_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, f, GUINT_TO_POINTER (token));
return token;
}
static guint32
mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCtorOnTypeBuilderInst *c, gboolean create_methodspec)
{
guint32 sig, token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoType *type;
/* A ctor cannot be a generic method, so we can ignore create_methodspec */
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, c));
if (token)
return token;
if (is_sre_ctor_builder (mono_object_class (c->cb))) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder *)c->cb;
MonoDynamicGenericClass *dgclass;
ReflectionMethodBuilder rmb;
char *name;
type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
reflection_methodbuilder_from_ctor_builder (&rmb, cb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
} else if (is_sr_mono_cmethod (mono_object_class (c->cb))) {
MonoMethod *mm = ((MonoReflectionMethod *)c->cb)->method;
type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
klass = mono_class_from_mono_type (type);
sig = method_encode_signature (assembly, mono_method_signature (mm));
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (c->cb));
g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, c, GUINT_TO_POINTER (token));
return token;
}
static MonoMethod*
mono_reflection_method_on_tb_inst_get_handle (MonoReflectionMethodOnTypeBuilderInst *m)
{
MonoClass *klass;
MonoGenericContext tmp_context;
MonoType **type_argv;
MonoGenericInst *ginst;
MonoMethod *method, *inflated;
int count, i;
method = inflate_method (m->inst, (MonoObject*)m->mb);
klass = method->klass;
if (m->method_args == NULL)
return method;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_array_length (m->method_args);
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (m->method_args, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
return inflated;
}
static guint32
mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionMethodOnTypeBuilderInst *m, gboolean create_methodspec)
{
guint32 sig, token = 0;
MonoType *type;
MonoClass *klass;
if (m->method_args) {
MonoMethod *inflated;
inflated = mono_reflection_method_on_tb_inst_get_handle (m);
if (create_methodspec)
token = mono_image_get_methodspec_token (assembly, inflated);
else
token = mono_image_get_inflated_method_token (assembly, inflated);
return token;
}
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, m));
if (token)
return token;
if (is_sre_method_builder (mono_object_class (m->mb))) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)m->mb;
MonoGenericClass *gclass;
ReflectionMethodBuilder rmb;
char *name;
type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
reflection_methodbuilder_from_method_builder (&rmb, mb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
} else if (is_sr_mono_method (mono_object_class (m->mb))) {
MonoMethod *mm = ((MonoReflectionMethod *)m->mb)->method;
type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
klass = mono_class_from_mono_type (type);
sig = method_encode_signature (assembly, mono_method_signature (mm));
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, mm->name, sig);
} else {
char *name = mono_type_get_full_name (mono_object_class (m->mb));
g_error ("mono_image_get_method_on_inst_token: don't know how to handle %s", name);
}
mono_g_hash_table_insert (assembly->handleref_managed, m, GUINT_TO_POINTER (token));
return token;
}
static guint32
encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context)
{
SigBuffer buf;
int i;
guint32 nparams = context->method_inst->type_argc;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
sigbuffer_add_value (&buf, 0xa); /* FIXME FIXME FIXME */
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++)
encode_type (assembly, context->method_inst->type_argv [i], &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
method_encode_methodspec (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0, sig;
MonoMethodInflated *imethod;
MonoMethod *declaring;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
declaring = imethod->declaring;
sig = method_encode_signature (assembly, mono_method_signature (declaring));
mtoken = mono_image_get_memberref_token (assembly, &method->klass->byval_arg, declaring->name, sig);
if (!mono_method_signature (declaring)->generic_param_count)
return mtoken;
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
sig = encode_generic_method_sig (assembly, mono_method_get_context (method));
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = sig;
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoMethodInflated *imethod;
guint32 token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
if (mono_method_signature (imethod->declaring)->generic_param_count) {
token = method_encode_methodspec (assembly, method);
} else {
guint32 sig = method_encode_signature (
assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &method->klass->byval_arg, method->name, sig);
}
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m)
{
MonoMethodInflated *imethod = (MonoMethodInflated *) m;
guint32 sig, token;
sig = method_encode_signature (assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &m->klass->byval_arg, m->name, sig);
return token;
}
static guint32
create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *type;
guint32 *values;
guint32 token;
SigBuffer buf;
int count, i;
/*
* We're creating a TypeSpec for the TypeBuilder of a generic type declaration,
* ie. what we'd normally use as the generic type in a TypeSpec signature.
* Because of this, we must not insert it into the `typeref' hash table.
*/
type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type));
if (token)
return token;
sigbuffer_init (&buf, 32);
g_assert (tb->generic_params);
klass = mono_class_from_mono_type (type);
if (tb->generic_container)
mono_reflection_create_generic_class (tb);
sigbuffer_add_value (&buf, MONO_TYPE_GENERICINST);
g_assert (klass->generic_container);
sigbuffer_add_value (&buf, klass->byval_arg.type);
sigbuffer_add_value (&buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
count = mono_array_length (tb->generic_params);
sigbuffer_add_value (&buf, count);
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam;
gparam = mono_array_get (tb->generic_params, MonoReflectionGenericParam *, i);
encode_type (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)gparam), &buf);
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
/*
* Return a copy of TYPE, adding the custom modifiers in MODREQ and MODOPT.
*/
static MonoType*
add_custom_modifiers (MonoDynamicImage *assembly, MonoType *type, MonoArray *modreq, MonoArray *modopt)
{
int i, count, len, pos;
MonoType *t;
count = 0;
if (modreq)
count += mono_array_length (modreq);
if (modopt)
count += mono_array_length (modopt);
if (count == 0)
return mono_metadata_type_dup (NULL, type);
len = MONO_SIZEOF_TYPE + ((gint32)count) * sizeof (MonoCustomMod);
t = g_malloc (len);
memcpy (t, type, MONO_SIZEOF_TYPE);
t->num_mods = count;
pos = 0;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
t->modifiers [pos].required = 1;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
t->modifiers [pos].required = 0;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
return t;
}
static guint32
mono_image_get_generic_field_token (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *custom = NULL;
guint32 *values;
guint32 token, pclass, parent, sig;
gchar *name;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->handleref_managed, fb));
if (token)
return token;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (fb->typeb));
name = mono_string_to_utf8 (fb->name);
/* fb->type does not include the custom modifiers */
/* FIXME: We should do this in one place when a fieldbuilder is created */
if (fb->modreq || fb->modopt) {
custom = add_custom_modifiers (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type), fb->modreq, fb->modopt);
sig = fieldref_encode_signature (assembly, NULL, custom);
g_free (custom);
} else {
sig = fieldref_encode_signature (assembly, NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
}
parent = create_generic_typespec (assembly, (MonoReflectionTypeBuilder *) fb->typeb);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_TYPEDEFORREF_TYPESPEC);
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
mono_g_hash_table_insert (assembly->handleref_managed, fb, GUINT_TO_POINTER(token));
g_free (name);
return token;
}
static guint32
mono_reflection_encode_sighelper (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
SigBuffer buf;
guint32 nargs;
guint32 size;
guint32 i, idx;
if (!assembly->save)
return 0;
/* FIXME: this means SignatureHelper.SignatureHelpType.HELPER_METHOD */
g_assert (helper->type == 2);
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
size = 10 + (nargs * 10);
sigbuffer_init (&buf, 32);
/* Encode calling convention */
/* Change Any to Standard */
if ((helper->call_conv & 0x03) == 0x03)
helper->call_conv = 0x01;
/* explicit_this implies has_this */
if (helper->call_conv & 0x40)
helper->call_conv &= 0x20;
if (helper->call_conv == 0) { /* Unmanaged */
idx = helper->unmanaged_call_conv - 1;
} else {
/* Managed */
idx = helper->call_conv & 0x60; /* has_this + explicit_this */
if (helper->call_conv & 0x02) /* varargs */
idx += 0x05;
}
sigbuffer_add_byte (&buf, idx);
sigbuffer_add_value (&buf, nargs);
encode_reflection_type (assembly, helper->return_type, &buf);
for (i = 0; i < nargs; ++i) {
MonoArray *modreqs = NULL;
MonoArray *modopts = NULL;
MonoReflectionType *pt;
if (helper->modreqs && (i < mono_array_length (helper->modreqs)))
modreqs = mono_array_get (helper->modreqs, MonoArray*, i);
if (helper->modopts && (i < mono_array_length (helper->modopts)))
modopts = mono_array_get (helper->modopts, MonoArray*, i);
encode_custom_modifiers (assembly, modreqs, modopts, &buf);
pt = mono_array_get (helper->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
guint32 idx;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] =
mono_reflection_encode_sighelper (assembly, helper);
return idx;
}
static int
reflection_cc_to_file (int call_conv) {
switch (call_conv & 0x3) {
case 0:
case 1: return MONO_CALL_DEFAULT;
case 2: return MONO_CALL_VARARG;
default:
g_assert_not_reached ();
}
return 0;
}
#endif /* !DISABLE_REFLECTION_EMIT */
typedef struct {
MonoType *parent;
MonoMethodSignature *sig;
char *name;
guint32 token;
} ArrayMethod;
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_array_token (MonoDynamicImage *assembly, MonoReflectionArrayMethod *m)
{
guint32 nparams, i;
GList *tmp;
char *name;
MonoMethodSignature *sig;
ArrayMethod *am;
MonoType *mtype;
name = mono_string_to_utf8 (m->name);
nparams = mono_array_length (m->parameters);
sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * nparams);
sig->hasthis = 1;
sig->sentinelpos = -1;
sig->call_convention = reflection_cc_to_file (m->call_conv);
sig->param_count = nparams;
sig->ret = m->ret ? mono_reflection_type_get_handle (m->ret): &mono_defaults.void_class->byval_arg;
mtype = mono_reflection_type_get_handle (m->parent);
for (i = 0; i < nparams; ++i)
sig->params [i] = mono_type_array_get_and_resolve (m->parameters, i);
for (tmp = assembly->array_methods; tmp; tmp = tmp->next) {
am = tmp->data;
if (strcmp (name, am->name) == 0 &&
mono_metadata_type_equal (am->parent, mtype) &&
mono_metadata_signature_equal (am->sig, sig)) {
g_free (name);
g_free (sig);
m->table_idx = am->token & 0xffffff;
return am->token;
}
}
am = g_new0 (ArrayMethod, 1);
am->name = name;
am->sig = sig;
am->parent = mtype;
am->token = mono_image_get_memberref_token (assembly, am->parent, name,
method_encode_signature (assembly, sig));
assembly->array_methods = g_list_prepend (assembly->array_methods, am);
m->table_idx = am->token & 0xffffff;
return am->token;
}
/*
* Insert into the metadata tables all the info about the TypeBuilder tb.
* Data in the tables is inserted in a predefined order, since some tables need to be sorted.
*/
static void
mono_image_get_type_info (MonoDomain *domain, MonoReflectionTypeBuilder *tb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint *values;
int i, is_object = 0, is_system = 0;
char *n;
table = &assembly->tables [MONO_TABLE_TYPEDEF];
values = table->values + tb->table_idx * MONO_TYPEDEF_SIZE;
values [MONO_TYPEDEF_FLAGS] = tb->attrs;
n = mono_string_to_utf8 (tb->name);
if (strcmp (n, "Object") == 0)
is_object++;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, n);
g_free (n);
n = mono_string_to_utf8 (tb->nspace);
if (strcmp (n, "System") == 0)
is_system++;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, n);
g_free (n);
if (tb->parent && !(is_system && is_object) &&
!(tb->attrs & TYPE_ATTRIBUTE_INTERFACE)) { /* interfaces don't have a parent */
values [MONO_TYPEDEF_EXTENDS] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
} else {
values [MONO_TYPEDEF_EXTENDS] = 0;
}
values [MONO_TYPEDEF_FIELD_LIST] = assembly->tables [MONO_TABLE_FIELD].next_idx;
values [MONO_TYPEDEF_METHOD_LIST] = assembly->tables [MONO_TABLE_METHOD].next_idx;
/*
* if we have explicitlayout or sequentiallayouts, output data in the
* ClassLayout table.
*/
if (((tb->attrs & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT) &&
((tb->class_size > 0) || (tb->packing_size > 0))) {
table = &assembly->tables [MONO_TABLE_CLASSLAYOUT];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CLASS_LAYOUT_SIZE;
values [MONO_CLASS_LAYOUT_PARENT] = tb->table_idx;
values [MONO_CLASS_LAYOUT_CLASS_SIZE] = tb->class_size;
values [MONO_CLASS_LAYOUT_PACKING_SIZE] = tb->packing_size;
}
/* handle interfaces */
if (tb->interfaces) {
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
i = table->rows;
table->rows += mono_array_length (tb->interfaces);
alloc_table (table, table->rows);
values = table->values + (i + 1) * MONO_INTERFACEIMPL_SIZE;
for (i = 0; i < mono_array_length (tb->interfaces); ++i) {
MonoReflectionType* iface = (MonoReflectionType*) mono_array_get (tb->interfaces, gpointer, i);
values [MONO_INTERFACEIMPL_CLASS] = tb->table_idx;
values [MONO_INTERFACEIMPL_INTERFACE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (iface));
values += MONO_INTERFACEIMPL_SIZE;
}
}
/* handle fields */
if (tb->fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += tb->num_fields;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_fields; ++i)
mono_image_get_field_info (
mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i), assembly);
}
/* handle constructors */
if (tb->ctors) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (tb->ctors);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->ctors); ++i)
mono_image_get_ctor_info (domain,
mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i), assembly);
}
/* handle methods */
if (tb->methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += tb->num_methods;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_methods; ++i)
mono_image_get_method_info (
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i), assembly);
}
/* Do the same with properties etc.. */
if (tb->events && mono_array_length (tb->events)) {
table = &assembly->tables [MONO_TABLE_EVENT];
table->rows += mono_array_length (tb->events);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_EVENTMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_EVENT_MAP_SIZE;
values [MONO_EVENT_MAP_PARENT] = tb->table_idx;
values [MONO_EVENT_MAP_EVENTLIST] = assembly->tables [MONO_TABLE_EVENT].next_idx;
for (i = 0; i < mono_array_length (tb->events); ++i)
mono_image_get_event_info (
mono_array_get (tb->events, MonoReflectionEventBuilder*, i), assembly);
}
if (tb->properties && mono_array_length (tb->properties)) {
table = &assembly->tables [MONO_TABLE_PROPERTY];
table->rows += mono_array_length (tb->properties);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_PROPERTYMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_PROPERTY_MAP_SIZE;
values [MONO_PROPERTY_MAP_PARENT] = tb->table_idx;
values [MONO_PROPERTY_MAP_PROPERTY_LIST] = assembly->tables [MONO_TABLE_PROPERTY].next_idx;
for (i = 0; i < mono_array_length (tb->properties); ++i)
mono_image_get_property_info (
mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i), assembly);
}
/* handle generic parameters */
if (tb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (tb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_TYPE | (tb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (tb->generic_params, MonoReflectionGenericParam*, i), owner, assembly);
}
}
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx), tb->permissions);
if (tb->subtypes) {
MonoDynamicTable *ntable;
ntable = &assembly->tables [MONO_TABLE_NESTEDCLASS];
ntable->rows += mono_array_length (tb->subtypes);
alloc_table (ntable, ntable->rows);
values = ntable->values + ntable->next_idx * MONO_NESTED_CLASS_SIZE;
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
values [MONO_NESTED_CLASS_NESTED] = subtype->table_idx;
values [MONO_NESTED_CLASS_ENCLOSING] = tb->table_idx;
/*g_print ("nesting %s (%d) in %s (%d) (rows %d/%d)\n",
mono_string_to_utf8 (subtype->name), subtype->table_idx,
mono_string_to_utf8 (tb->name), tb->table_idx,
ntable->next_idx, ntable->rows);*/
values += MONO_NESTED_CLASS_SIZE;
ntable->next_idx++;
}
}
}
#endif
static void
collect_types (MonoPtrArray *types, MonoReflectionTypeBuilder *type)
{
int i;
mono_ptr_array_append (*types, type);
if (!type->subtypes)
return;
for (i = 0; i < mono_array_length (type->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (type->subtypes, MonoReflectionTypeBuilder*, i);
collect_types (types, subtype);
}
}
static gint
compare_types_by_table_idx (MonoReflectionTypeBuilder **type1, MonoReflectionTypeBuilder **type2)
{
if ((*type1)->table_idx < (*type2)->table_idx)
return -1;
else
if ((*type1)->table_idx > (*type2)->table_idx)
return 1;
else
return 0;
}
static void
params_add_cattrs (MonoDynamicImage *assembly, MonoArray *pinfo) {
int i;
if (!pinfo)
return;
for (i = 0; i < mono_array_length (pinfo); ++i) {
MonoReflectionParamBuilder *pb;
pb = mono_array_get (pinfo, MonoReflectionParamBuilder *, i);
if (!pb)
continue;
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PARAMDEF, pb->cattrs);
}
}
static void
type_add_cattrs (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb) {
int i;
mono_image_add_cattrs (assembly, tb->table_idx, MONO_CUSTOM_ATTR_TYPEDEF, tb->cattrs);
if (tb->fields) {
for (i = 0; i < tb->num_fields; ++i) {
MonoReflectionFieldBuilder* fb;
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (tb->events) {
for (i = 0; i < mono_array_length (tb->events); ++i) {
MonoReflectionEventBuilder* eb;
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
mono_image_add_cattrs (assembly, eb->table_idx, MONO_CUSTOM_ATTR_EVENT, eb->cattrs);
}
}
if (tb->properties) {
for (i = 0; i < mono_array_length (tb->properties); ++i) {
MonoReflectionPropertyBuilder* pb;
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PROPERTY, pb->cattrs);
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder* cb;
cb = mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i);
mono_image_add_cattrs (assembly, cb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, cb->cattrs);
params_add_cattrs (assembly, cb->pinfo);
}
}
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder* mb;
mb = mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
type_add_cattrs (assembly, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i));
}
}
static void
module_add_cattrs (MonoDynamicImage *assembly, MonoReflectionModuleBuilder *moduleb)
{
int i;
mono_image_add_cattrs (assembly, moduleb->table_idx, MONO_CUSTOM_ATTR_MODULE, moduleb->cattrs);
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder* mb = mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (moduleb->global_fields) {
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (moduleb->types) {
for (i = 0; i < moduleb->num_types; ++i)
type_add_cattrs (assembly, mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i));
}
}
static void
mono_image_fill_file_table (MonoDomain *domain, MonoReflectionModule *module, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *dir, *path;
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, module->image->module_name);
if (module->image->dynamic) {
/* This depends on the fact that the main module is emitted last */
dir = mono_string_to_utf8 (((MonoReflectionModuleBuilder*)module)->assemblyb->dir);
path = g_strdup_printf ("%s%c%s", dir, G_DIR_SEPARATOR, module->image->module_name);
} else {
dir = NULL;
path = g_strdup (module->image->name);
}
mono_sha1_get_digest_from_file (path, hash);
g_free (dir);
g_free (path);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
table->next_idx ++;
}
static void
mono_image_fill_module_table (MonoDomain *domain, MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
table = &assembly->tables [MONO_TABLE_MODULE];
mb->table_idx = table->next_idx ++;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->module.name);
i = mono_image_add_stream_data (&assembly->guid, mono_array_addr (mb->guid, char, 0), 16);
i /= 16;
++i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_GENERATION] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_MVID] = i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENC] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENCBASE] = 0;
}
static guint32
mono_image_fill_export_table_from_class (MonoDomain *domain, MonoClass *klass,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 visib, res;
visib = klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if (! ((visib & TYPE_ATTRIBUTE_PUBLIC) || (visib & TYPE_ATTRIBUTE_NESTED_PUBLIC)))
return 0;
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = klass->flags;
values [MONO_EXP_TYPE_TYPEDEF] = klass->type_token;
if (klass->nested_in)
values [MONO_EXP_TYPE_IMPLEMENTATION] = (parent_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
else
values [MONO_EXP_TYPE_IMPLEMENTATION] = (module_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_FILE;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
res = table->next_idx;
table->next_idx ++;
/* Emit nested types */
if (klass->ext && klass->ext->nested_classes) {
GList *tmp;
for (tmp = klass->ext->nested_classes; tmp; tmp = tmp->next)
mono_image_fill_export_table_from_class (domain, tmp->data, module_index, table->next_idx - 1, assembly);
}
return res;
}
static void
mono_image_fill_export_table (MonoDomain *domain, MonoReflectionTypeBuilder *tb,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoClass *klass;
guint32 idx, i;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
klass->type_token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx);
idx = mono_image_fill_export_table_from_class (domain, klass, module_index,
parent_index, assembly);
/*
* Emit nested types
* We need to do this ourselves since klass->nested_classes is not set up.
*/
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
mono_image_fill_export_table (domain, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i), module_index, idx, assembly);
}
}
static void
mono_image_fill_export_table_from_module (MonoDomain *domain, MonoReflectionModule *module,
guint32 module_index, MonoDynamicImage *assembly)
{
MonoImage *image = module->image;
MonoTableInfo *t;
guint32 i;
t = &image->tables [MONO_TABLE_TYPEDEF];
for (i = 0; i < t->rows; ++i) {
MonoClass *klass = mono_class_get (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, i + 1));
if (klass->flags & TYPE_ATTRIBUTE_PUBLIC)
mono_image_fill_export_table_from_class (domain, klass, module_index, 0, assembly);
}
}
static void
add_exported_type (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly, MonoClass *klass, guint32 parent_index)
{
MonoDynamicTable *table;
guint32 *values;
guint32 scope, scope_idx, impl, current_idx;
gboolean forwarder = TRUE;
gpointer iter = NULL;
MonoClass *nested;
if (klass->nested_in) {
impl = (parent_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
forwarder = FALSE;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
g_assert ((scope & MONO_RESOLTION_SCOPE_MASK) == MONO_RESOLTION_SCOPE_ASSEMBLYREF);
scope_idx = scope >> MONO_RESOLTION_SCOPE_BITS;
impl = (scope_idx << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_ASSEMBLYREF;
}
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
current_idx = table->next_idx;
values = table->values + current_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = forwarder ? TYPE_ATTRIBUTE_FORWARDER : 0;
values [MONO_EXP_TYPE_TYPEDEF] = 0;
values [MONO_EXP_TYPE_IMPLEMENTATION] = impl;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
table->next_idx++;
while ((nested = mono_class_get_nested_types (klass, &iter)))
add_exported_type (assemblyb, assembly, nested, current_idx);
}
static void
mono_image_fill_export_table_from_type_forwarders (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly)
{
MonoClass *klass;
int i;
if (!assemblyb->type_forwarders)
return;
for (i = 0; i < mono_array_length (assemblyb->type_forwarders); ++i) {
MonoReflectionType *t = mono_array_get (assemblyb->type_forwarders, MonoReflectionType *, i);
MonoType *type;
if (!t)
continue;
type = mono_reflection_type_get_handle (t);
g_assert (type);
klass = mono_class_from_mono_type (type);
add_exported_type (assemblyb, assembly, klass, 0);
}
}
#define align_pointer(base,p)\
do {\
guint32 __diff = (unsigned char*)(p)-(unsigned char*)(base);\
if (__diff & 3)\
(p) += 4 - (__diff & 3);\
} while (0)
static int
compare_constants (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CONSTANT_PARENT] - b_values [MONO_CONSTANT_PARENT];
}
static int
compare_semantics (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int assoc = a_values [MONO_METHOD_SEMA_ASSOCIATION] - b_values [MONO_METHOD_SEMA_ASSOCIATION];
if (assoc)
return assoc;
return a_values [MONO_METHOD_SEMA_SEMANTICS] - b_values [MONO_METHOD_SEMA_SEMANTICS];
}
static int
compare_custom_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CUSTOM_ATTR_PARENT] - b_values [MONO_CUSTOM_ATTR_PARENT];
}
static int
compare_field_marshal (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_FIELD_MARSHAL_PARENT] - b_values [MONO_FIELD_MARSHAL_PARENT];
}
static int
compare_nested (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_NESTED_CLASS_NESTED] - b_values [MONO_NESTED_CLASS_NESTED];
}
static int
compare_genericparam (const void *a, const void *b)
{
const GenericParamTableEntry **a_entry = (const GenericParamTableEntry **) a;
const GenericParamTableEntry **b_entry = (const GenericParamTableEntry **) b;
if ((*b_entry)->owner == (*a_entry)->owner)
return
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*a_entry)->gparam)) -
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*b_entry)->gparam));
else
return (*a_entry)->owner - (*b_entry)->owner;
}
static int
compare_declsecurity_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_DECL_SECURITY_PARENT] - b_values [MONO_DECL_SECURITY_PARENT];
}
static int
compare_interface_impl (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int klass = a_values [MONO_INTERFACEIMPL_CLASS] - b_values [MONO_INTERFACEIMPL_CLASS];
if (klass)
return klass;
return a_values [MONO_INTERFACEIMPL_INTERFACE] - b_values [MONO_INTERFACEIMPL_INTERFACE];
}
static void
pad_heap (MonoDynamicStream *sh)
{
if (sh->index & 3) {
int sz = 4 - (sh->index & 3);
memset (sh->data + sh->index, 0, sz);
sh->index += sz;
}
}
struct StreamDesc {
const char *name;
MonoDynamicStream *stream;
};
/*
* build_compressed_metadata() fills in the blob of data that represents the
* raw metadata as it will be saved in the PE file. The five streams are output
* and the metadata tables are comnpressed from the guint32 array representation,
* to the compressed on-disk format.
*/
static void
build_compressed_metadata (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
guint64 valid_mask = 0;
guint64 sorted_mask;
guint32 heapt_size = 0;
guint32 meta_size = 256; /* allow for header and other stuff */
guint32 table_offset;
guint32 ntables = 0;
guint64 *int64val;
guint32 *int32val;
guint16 *int16val;
MonoImage *meta;
unsigned char *p;
struct StreamDesc stream_desc [5];
qsort (assembly->gen_params->pdata, assembly->gen_params->len, sizeof (gpointer), compare_genericparam);
for (i = 0; i < assembly->gen_params->len; i++){
GenericParamTableEntry *entry = g_ptr_array_index (assembly->gen_params, i);
write_generic_param_entry (assembly, entry);
}
stream_desc [0].name = "#~";
stream_desc [0].stream = &assembly->tstream;
stream_desc [1].name = "#Strings";
stream_desc [1].stream = &assembly->sheap;
stream_desc [2].name = "#US";
stream_desc [2].stream = &assembly->us;
stream_desc [3].name = "#Blob";
stream_desc [3].stream = &assembly->blob;
stream_desc [4].name = "#GUID";
stream_desc [4].stream = &assembly->guid;
/* tables that are sorted */
sorted_mask = ((guint64)1 << MONO_TABLE_CONSTANT) | ((guint64)1 << MONO_TABLE_FIELDMARSHAL)
| ((guint64)1 << MONO_TABLE_METHODSEMANTICS) | ((guint64)1 << MONO_TABLE_CLASSLAYOUT)
| ((guint64)1 << MONO_TABLE_FIELDLAYOUT) | ((guint64)1 << MONO_TABLE_FIELDRVA)
| ((guint64)1 << MONO_TABLE_IMPLMAP) | ((guint64)1 << MONO_TABLE_NESTEDCLASS)
| ((guint64)1 << MONO_TABLE_METHODIMPL) | ((guint64)1 << MONO_TABLE_CUSTOMATTRIBUTE)
| ((guint64)1 << MONO_TABLE_DECLSECURITY) | ((guint64)1 << MONO_TABLE_GENERICPARAM)
| ((guint64)1 << MONO_TABLE_INTERFACEIMPL);
/* Compute table sizes */
/* the MonoImage has already been created in mono_image_basic_init() */
meta = &assembly->image;
/* sizes should be multiple of 4 */
pad_heap (&assembly->blob);
pad_heap (&assembly->guid);
pad_heap (&assembly->sheap);
pad_heap (&assembly->us);
/* Setup the info used by compute_sizes () */
meta->idx_blob_wide = assembly->blob.index >= 65536 ? 1 : 0;
meta->idx_guid_wide = assembly->guid.index >= 65536 ? 1 : 0;
meta->idx_string_wide = assembly->sheap.index >= 65536 ? 1 : 0;
meta_size += assembly->blob.index;
meta_size += assembly->guid.index;
meta_size += assembly->sheap.index;
meta_size += assembly->us.index;
for (i=0; i < MONO_TABLE_NUM; ++i)
meta->tables [i].rows = assembly->tables [i].rows;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
valid_mask |= (guint64)1 << i;
ntables ++;
meta->tables [i].row_size = mono_metadata_compute_size (
meta, i, &meta->tables [i].size_bitfield);
heapt_size += meta->tables [i].row_size * meta->tables [i].rows;
}
heapt_size += 24; /* #~ header size */
heapt_size += ntables * 4;
/* make multiple of 4 */
heapt_size += 3;
heapt_size &= ~3;
meta_size += heapt_size;
meta->raw_metadata = g_malloc0 (meta_size);
p = (unsigned char*)meta->raw_metadata;
/* the metadata signature */
*p++ = 'B'; *p++ = 'S'; *p++ = 'J'; *p++ = 'B';
/* version numbers and 4 bytes reserved */
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (meta->md_version_major);
*int16val = GUINT16_TO_LE (meta->md_version_minor);
p += 8;
/* version string */
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE ((strlen (meta->version) + 3) & (~3)); /* needs to be multiple of 4 */
p += 4;
memcpy (p, meta->version, strlen (meta->version));
p += GUINT32_FROM_LE (*int32val);
align_pointer (meta->raw_metadata, p);
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (0); /* flags must be 0 */
*int16val = GUINT16_TO_LE (5); /* number of streams */
p += 4;
/*
* write the stream info.
*/
table_offset = (p - (unsigned char*)meta->raw_metadata) + 5 * 8 + 40; /* room needed for stream headers */
table_offset += 3; table_offset &= ~3;
assembly->tstream.index = heapt_size;
for (i = 0; i < 5; ++i) {
int32val = (guint32*)p;
stream_desc [i].stream->offset = table_offset;
*int32val++ = GUINT32_TO_LE (table_offset);
*int32val = GUINT32_TO_LE (stream_desc [i].stream->index);
table_offset += GUINT32_FROM_LE (*int32val);
table_offset += 3; table_offset &= ~3;
p += 8;
strcpy ((char*)p, stream_desc [i].name);
p += strlen (stream_desc [i].name) + 1;
align_pointer (meta->raw_metadata, p);
}
/*
* now copy the data, the table stream header and contents goes first.
*/
g_assert ((p - (unsigned char*)meta->raw_metadata) < assembly->tstream.offset);
p = (guchar*)meta->raw_metadata + assembly->tstream.offset;
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE (0); /* reserved */
p += 4;
*p++ = 2; /* version */
*p++ = 0;
if (meta->idx_string_wide)
*p |= 0x01;
if (meta->idx_guid_wide)
*p |= 0x02;
if (meta->idx_blob_wide)
*p |= 0x04;
++p;
*p++ = 1; /* reserved */
int64val = (guint64*)p;
*int64val++ = GUINT64_TO_LE (valid_mask);
*int64val++ = GUINT64_TO_LE (valid_mask & sorted_mask); /* bitvector of sorted tables */
p += 16;
int32val = (guint32*)p;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
*int32val++ = GUINT32_TO_LE (meta->tables [i].rows);
}
p = (unsigned char*)int32val;
/* sort the tables that still need sorting */
table = &assembly->tables [MONO_TABLE_CONSTANT];
if (table->rows)
qsort (table->values + MONO_CONSTANT_SIZE, table->rows, sizeof (guint32) * MONO_CONSTANT_SIZE, compare_constants);
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
if (table->rows)
qsort (table->values + MONO_METHOD_SEMA_SIZE, table->rows, sizeof (guint32) * MONO_METHOD_SEMA_SIZE, compare_semantics);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
if (table->rows)
qsort (table->values + MONO_CUSTOM_ATTR_SIZE, table->rows, sizeof (guint32) * MONO_CUSTOM_ATTR_SIZE, compare_custom_attrs);
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
if (table->rows)
qsort (table->values + MONO_FIELD_MARSHAL_SIZE, table->rows, sizeof (guint32) * MONO_FIELD_MARSHAL_SIZE, compare_field_marshal);
table = &assembly->tables [MONO_TABLE_NESTEDCLASS];
if (table->rows)
qsort (table->values + MONO_NESTED_CLASS_SIZE, table->rows, sizeof (guint32) * MONO_NESTED_CLASS_SIZE, compare_nested);
/* Section 21.11 DeclSecurity in Partition II doesn't specify this to be sorted by MS implementation requires it */
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
if (table->rows)
qsort (table->values + MONO_DECL_SECURITY_SIZE, table->rows, sizeof (guint32) * MONO_DECL_SECURITY_SIZE, compare_declsecurity_attrs);
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
if (table->rows)
qsort (table->values + MONO_INTERFACEIMPL_SIZE, table->rows, sizeof (guint32) * MONO_INTERFACEIMPL_SIZE, compare_interface_impl);
/* compress the tables */
for (i = 0; i < MONO_TABLE_NUM; i++){
int row, col;
guint32 *values;
guint32 bitfield = meta->tables [i].size_bitfield;
if (!meta->tables [i].rows)
continue;
if (assembly->tables [i].columns != mono_metadata_table_count (bitfield))
g_error ("col count mismatch in %d: %d %d", i, assembly->tables [i].columns, mono_metadata_table_count (bitfield));
meta->tables [i].base = (char*)p;
for (row = 1; row <= meta->tables [i].rows; ++row) {
values = assembly->tables [i].values + row * assembly->tables [i].columns;
for (col = 0; col < assembly->tables [i].columns; ++col) {
switch (mono_metadata_table_size (bitfield, col)) {
case 1:
*p++ = values [col];
break;
case 2:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
break;
case 4:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
*p++ = (values [col] >> 16) & 0xff;
*p++ = (values [col] >> 24) & 0xff;
break;
default:
g_assert_not_reached ();
}
}
}
g_assert ((p - (const unsigned char*)meta->tables [i].base) == (meta->tables [i].rows * meta->tables [i].row_size));
}
g_assert (assembly->guid.offset + assembly->guid.index < meta_size);
memcpy (meta->raw_metadata + assembly->sheap.offset, assembly->sheap.data, assembly->sheap.index);
memcpy (meta->raw_metadata + assembly->us.offset, assembly->us.data, assembly->us.index);
memcpy (meta->raw_metadata + assembly->blob.offset, assembly->blob.data, assembly->blob.index);
memcpy (meta->raw_metadata + assembly->guid.offset, assembly->guid.data, assembly->guid.index);
assembly->meta_size = assembly->guid.offset + assembly->guid.index;
}
/*
* Some tables in metadata need to be sorted according to some criteria, but
* when methods and fields are first created with reflection, they may be assigned a token
* that doesn't correspond to the final token they will get assigned after the sorting.
* ILGenerator.cs keeps a fixup table that maps the position of tokens in the IL code stream
* with the reflection objects that represent them. Once all the tables are set up, the
* reflection objects will contains the correct table index. fixup_method() will fixup the
* tokens for the method with ILGenerator @ilgen.
*/
static void
fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *assembly)
{
guint32 code_idx = GPOINTER_TO_UINT (value);
MonoReflectionILTokenInfo *iltoken;
MonoReflectionFieldBuilder *field;
MonoReflectionCtorBuilder *ctor;
MonoReflectionMethodBuilder *method;
MonoReflectionTypeBuilder *tb;
MonoReflectionArrayMethod *am;
guint32 i, idx = 0;
unsigned char *target;
for (i = 0; i < ilgen->num_token_fixups; ++i) {
iltoken = (MonoReflectionILTokenInfo *)mono_array_addr_with_size (ilgen->token_fixups, sizeof (MonoReflectionILTokenInfo), i);
target = (guchar*)assembly->code.data + code_idx + iltoken->code_pos;
switch (target [3]) {
case MONO_TABLE_FIELD:
if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
field = (MonoReflectionFieldBuilder *)iltoken->member;
idx = field->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->field_to_table_idx, f));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHOD:
if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
method = (MonoReflectionMethodBuilder *)iltoken->member;
idx = method->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
ctor = (MonoReflectionCtorBuilder *)iltoken->member;
idx = ctor->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_TYPEDEF:
if (strcmp (iltoken->member->vtable->klass->name, "TypeBuilder"))
g_assert_not_reached ();
tb = (MonoReflectionTypeBuilder *)iltoken->member;
idx = tb->table_idx;
break;
case MONO_TABLE_MEMBERREF:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoArrayMethod")) {
am = (MonoReflectionArrayMethod*)iltoken->member;
idx = am->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (m->klass->generic_class || m->klass->generic_container);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
g_assert (is_field_on_inst (f));
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder") ||
!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHODSPEC:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (mono_method_signature (m)->generic_param_count);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
default:
g_error ("got unexpected table 0x%02x in fixup", target [3]);
}
target [0] = idx & 0xff;
target [1] = (idx >> 8) & 0xff;
target [2] = (idx >> 16) & 0xff;
}
}
/*
* fixup_cattrs:
*
* The CUSTOM_ATTRIBUTE table might contain METHODDEF tokens whose final
* value is not known when the table is emitted.
*/
static void
fixup_cattrs (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 type, i, idx, token;
MonoObject *ctor;
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
for (i = 0; i < table->rows; ++i) {
values = table->values + ((i + 1) * MONO_CUSTOM_ATTR_SIZE);
type = values [MONO_CUSTOM_ATTR_TYPE];
if ((type & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_METHODDEF) {
idx = type >> MONO_CUSTOM_ATTR_TYPE_BITS;
token = mono_metadata_make_token (MONO_TABLE_METHOD, idx);
ctor = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
g_assert (ctor);
if (!strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)ctor)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
values [MONO_CUSTOM_ATTR_TYPE] = (idx << MONO_CUSTOM_ATTR_TYPE_BITS) | MONO_CUSTOM_ATTR_TYPE_METHODDEF;
}
}
}
}
static void
assembly_add_resource_manifest (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc, guint32 implementation)
{
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MANIFESTRESOURCE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_MANIFEST_SIZE;
values [MONO_MANIFEST_OFFSET] = rsrc->offset;
values [MONO_MANIFEST_FLAGS] = rsrc->attrs;
values [MONO_MANIFEST_NAME] = string_heap_insert_mstring (&assembly->sheap, rsrc->name);
values [MONO_MANIFEST_IMPLEMENTATION] = implementation;
table->next_idx++;
}
static void
assembly_add_resource (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *name, *sname;
guint32 idx, offset;
if (rsrc->filename) {
name = mono_string_to_utf8 (rsrc->filename);
sname = g_path_get_basename (name);
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_NO_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, sname);
g_free (sname);
mono_sha1_get_digest_from_file (name, hash);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
g_free (name);
idx = table->next_idx++;
rsrc->offset = 0;
idx = MONO_IMPLEMENTATION_FILE | (idx << MONO_IMPLEMENTATION_BITS);
} else {
char sizebuf [4];
char *data;
guint len;
if (rsrc->data) {
data = mono_array_addr (rsrc->data, char, 0);
len = mono_array_length (rsrc->data);
} else {
data = NULL;
len = 0;
}
offset = len;
sizebuf [0] = offset; sizebuf [1] = offset >> 8;
sizebuf [2] = offset >> 16; sizebuf [3] = offset >> 24;
rsrc->offset = mono_image_add_stream_data (&assembly->resources, sizebuf, 4);
mono_image_add_stream_data (&assembly->resources, data, len);
if (!mb->is_main)
/*
* The entry should be emitted into the MANIFESTRESOURCE table of
* the main module, but that needs to reference the FILE table
* which isn't emitted yet.
*/
return;
else
idx = 0;
}
assembly_add_resource_manifest (mb, assembly, rsrc, idx);
}
static void
set_version_from_string (MonoString *version, guint32 *values)
{
gchar *ver, *p, *str;
guint32 i;
values [MONO_ASSEMBLY_MAJOR_VERSION] = 0;
values [MONO_ASSEMBLY_MINOR_VERSION] = 0;
values [MONO_ASSEMBLY_REV_NUMBER] = 0;
values [MONO_ASSEMBLY_BUILD_NUMBER] = 0;
if (!version)
return;
ver = str = mono_string_to_utf8 (version);
for (i = 0; i < 4; ++i) {
values [MONO_ASSEMBLY_MAJOR_VERSION + i] = strtol (ver, &p, 10);
switch (*p) {
case '.':
p++;
break;
case '*':
/* handle Revision and Build */
p++;
break;
}
ver = p;
}
g_free (str);
}
static guint32
load_public_key (MonoArray *pkey, MonoDynamicImage *assembly) {
gsize len;
guint32 token = 0;
char blob_size [6];
char *b = blob_size;
if (!pkey)
return token;
len = mono_array_length (pkey);
mono_metadata_encode_value (len, b, &b);
token = mono_image_add_stream_data (&assembly->blob, blob_size, b - blob_size);
mono_image_add_stream_data (&assembly->blob, mono_array_addr (pkey, char, 0), len);
assembly->public_key = g_malloc (len);
memcpy (assembly->public_key, mono_array_addr (pkey, char, 0), len);
assembly->public_key_len = len;
/* Special case: check for ECMA key (16 bytes) */
if ((len == MONO_ECMA_KEY_LENGTH) && mono_is_ecma_key (mono_array_addr (pkey, char, 0), len)) {
/* In this case we must reserve 128 bytes (1024 bits) for the signature */
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH;
} else if (len >= MONO_PUBLIC_KEY_HEADER_LENGTH + MONO_MINIMUM_PUBLIC_KEY_LENGTH) {
/* minimum key size (in 2.0) is 384 bits */
assembly->strong_name_size = len - MONO_PUBLIC_KEY_HEADER_LENGTH;
} else {
/* FIXME - verifier */
g_warning ("Invalid public key length: %d bits (total: %d)", (int)MONO_PUBLIC_KEY_BIT_SIZE (len), (int)len);
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH; /* to be safe */
}
assembly->strong_name = g_malloc0 (assembly->strong_name_size);
return token;
}
static void
mono_image_emit_manifest (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
guint32 *values;
int i;
guint32 module_index;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
/* Emit ASSEMBLY table */
table = &assembly->tables [MONO_TABLE_ASSEMBLY];
alloc_table (table, 1);
values = table->values + MONO_ASSEMBLY_SIZE;
values [MONO_ASSEMBLY_HASH_ALG] = assemblyb->algid? assemblyb->algid: ASSEMBLY_HASH_SHA1;
values [MONO_ASSEMBLY_NAME] = string_heap_insert_mstring (&assembly->sheap, assemblyb->name);
if (assemblyb->culture) {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert_mstring (&assembly->sheap, assemblyb->culture);
} else {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert (&assembly->sheap, "");
}
values [MONO_ASSEMBLY_PUBLIC_KEY] = load_public_key (assemblyb->public_key, assembly);
values [MONO_ASSEMBLY_FLAGS] = assemblyb->flags;
set_version_from_string (assemblyb->version, values);
/* Emit FILE + EXPORTED_TYPE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
if (file_module != moduleb) {
mono_image_fill_file_table (domain, (MonoReflectionModule*)file_module, assembly);
module_index ++;
if (file_module->types) {
for (j = 0; j < file_module->num_types; ++j) {
MonoReflectionTypeBuilder *tb = mono_array_get (file_module->types, MonoReflectionTypeBuilder*, j);
mono_image_fill_export_table (domain, tb, module_index, 0, assembly);
}
}
}
}
if (assemblyb->loaded_modules) {
for (i = 0; i < mono_array_length (assemblyb->loaded_modules); ++i) {
MonoReflectionModule *file_module =
mono_array_get (assemblyb->loaded_modules, MonoReflectionModule*, i);
mono_image_fill_file_table (domain, file_module, assembly);
module_index ++;
mono_image_fill_export_table_from_module (domain, file_module, module_index, assembly);
}
}
if (assemblyb->type_forwarders)
mono_image_fill_export_table_from_type_forwarders (assemblyb, assembly);
/* Emit MANIFESTRESOURCE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
/* The table for the main module is emitted later */
if (file_module != moduleb) {
module_index ++;
if (file_module->resources) {
int len = mono_array_length (file_module->resources);
for (j = 0; j < len; ++j) {
MonoReflectionResource* res = (MonoReflectionResource*)mono_array_addr (file_module->resources, MonoReflectionResource, j);
assembly_add_resource_manifest (file_module, assembly, res, MONO_IMPLEMENTATION_FILE | (module_index << MONO_IMPLEMENTATION_BITS));
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT_SAVE
/*
* mono_image_build_metadata() will fill the info in all the needed metadata tables
* for the modulebuilder @moduleb.
* At the end of the process, method and field tokens are fixed up and the
* on-disk compressed metadata representation is created.
*/
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
MonoPtrArray types;
guint32 *values;
int i, j;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
if (assembly->text_rva)
return;
assembly->text_rva = START_TEXT_RVA;
if (moduleb->is_main) {
mono_image_emit_manifest (moduleb);
}
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows = 1; /* .<Module> */
table->next_idx++;
alloc_table (table, table->rows);
/*
* Set the first entry.
*/
values = table->values + table->columns;
values [MONO_TYPEDEF_FLAGS] = 0;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, "<Module>") ;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, "") ;
values [MONO_TYPEDEF_EXTENDS] = 0;
values [MONO_TYPEDEF_FIELD_LIST] = 1;
values [MONO_TYPEDEF_METHOD_LIST] = 1;
/*
* handle global methods
* FIXME: test what to do when global methods are defined in multiple modules.
*/
if (moduleb->global_methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (moduleb->global_methods);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i)
mono_image_get_method_info (
mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i), assembly);
}
if (moduleb->global_fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += mono_array_length (moduleb->global_fields);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i)
mono_image_get_field_info (
mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i), assembly);
}
table = &assembly->tables [MONO_TABLE_MODULE];
alloc_table (table, 1);
mono_image_fill_module_table (domain, moduleb, assembly);
/* Collect all types into a list sorted by their table_idx */
mono_ptr_array_init (types, moduleb->num_types);
if (moduleb->types)
for (i = 0; i < moduleb->num_types; ++i) {
MonoReflectionTypeBuilder *type = mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i);
collect_types (&types, type);
}
mono_ptr_array_sort (types, (gpointer)compare_types_by_table_idx);
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows += mono_ptr_array_size (types);
alloc_table (table, table->rows);
/*
* Emit type names + namespaces at one place inside the string heap,
* so load_class_names () needs to touch fewer pages.
*/
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *tb = mono_ptr_array_get (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->nspace);
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *tb = mono_ptr_array_get (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->name);
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *type = mono_ptr_array_get (types, i);
mono_image_get_type_info (domain, type, assembly);
}
/*
* table->rows is already set above and in mono_image_fill_module_table.
*/
/* add all the custom attributes at the end, once all the indexes are stable */
mono_image_add_cattrs (assembly, 1, MONO_CUSTOM_ATTR_ASSEMBLY, assemblyb->cattrs);
/* CAS assembly permissions */
if (assemblyb->permissions_minimum)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_minimum);
if (assemblyb->permissions_optional)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_optional);
if (assemblyb->permissions_refused)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_refused);
module_add_cattrs (assembly, moduleb);
/* fixup tokens */
mono_g_hash_table_foreach (assembly->token_fixups, (GHFunc)fixup_method, assembly);
/* Create the MethodImpl table. We do this after emitting all methods so we already know
* the final tokens and don't need another fixup pass. */
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (
moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_methodimpl (assembly, mb);
}
}
for (i = 0; i < mono_ptr_array_size (types); ++i) {
MonoReflectionTypeBuilder *type = mono_ptr_array_get (types, i);
if (type->methods) {
for (j = 0; j < type->num_methods; ++j) {
MonoReflectionMethodBuilder *mb = mono_array_get (
type->methods, MonoReflectionMethodBuilder*, j);
mono_image_add_methodimpl (assembly, mb);
}
}
}
mono_ptr_array_destroy (types);
fixup_cattrs (assembly);
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit_save, so saving of dynamic assemblies is not supported.");
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
typedef struct {
guint32 import_lookup_table;
guint32 timestamp;
guint32 forwarder;
guint32 name_rva;
guint32 import_address_table_rva;
} MonoIDT;
typedef struct {
guint32 name_rva;
guint32 flags;
} MonoILT;
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_insert_string:
* @module: module builder object
* @str: a string
*
* Insert @str into the user string stream of @module.
*/
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
MonoDynamicImage *assembly;
guint32 idx;
char buf [16];
char *b = buf;
MONO_ARCH_SAVE_REGS;
if (!module->dynamic_image)
mono_image_module_basic_init (module);
assembly = module->dynamic_image;
if (assembly->save) {
mono_metadata_encode_value (1 | (str->length * 2), b, &b);
idx = mono_image_add_stream_data (&assembly->us, buf, b-buf);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
mono_image_add_stream_data (&assembly->us, swapped, str->length * 2);
g_free (swapped);
}
#else
mono_image_add_stream_data (&assembly->us, (const char*)mono_string_chars (str), str->length * 2);
#endif
mono_image_add_stream_data (&assembly->us, "", 1);
} else {
idx = assembly->us.index ++;
}
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (MONO_TOKEN_STRING | idx), str);
return MONO_TOKEN_STRING | idx;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
MonoClass *klass;
guint32 token = 0;
MonoMethodSignature *sig;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MonoMethod") == 0) {
MonoMethod *method = ((MonoReflectionMethod *)obj)->method;
MonoMethodSignature *old;
guint32 sig_token, parent;
int nargs, i;
g_assert (opt_param_types && (mono_method_signature (method)->sentinelpos >= 0));
nargs = mono_array_length (opt_param_types);
old = mono_method_signature (method);
sig = mono_metadata_signature_alloc ( &assembly->image, old->param_count + nargs);
sig->hasthis = old->hasthis;
sig->explicit_this = old->explicit_this;
sig->call_convention = old->call_convention;
sig->generic_param_count = old->generic_param_count;
sig->param_count = old->param_count + nargs;
sig->sentinelpos = old->param_count;
sig->ret = old->ret;
for (i = 0; i < old->param_count; i++)
sig->params [i] = old->params [i];
for (i = 0; i < nargs; i++) {
MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
sig->params [old->param_count + i] = mono_reflection_type_get_handle (rt);
}
parent = mono_image_typedef_or_ref (assembly, &method->klass->byval_arg);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_MEMBERREF_PARENT_TYPEREF);
parent >>= MONO_TYPEDEFORREF_BITS;
parent <<= MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_TYPEREF;
sig_token = method_encode_signature (assembly, sig);
token = mono_image_get_varargs_method_token (assembly, parent, method->name, sig_token);
} else if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
ReflectionMethodBuilder rmb;
guint32 parent, sig_token;
int nopt_args, nparams, ngparams, i;
char *name;
reflection_methodbuilder_from_method_builder (&rmb, mb);
rmb.opt_types = opt_param_types;
nopt_args = mono_array_length (opt_param_types);
nparams = rmb.parameters ? mono_array_length (rmb.parameters): 0;
ngparams = rmb.generic_params ? mono_array_length (rmb.generic_params): 0;
sig = mono_metadata_signature_alloc (&assembly->image, nparams + nopt_args);
sig->hasthis = !(rmb.attrs & METHOD_ATTRIBUTE_STATIC);
sig->explicit_this = (rmb.call_conv & 0x40) == 0x40;
sig->call_convention = rmb.call_conv;
sig->generic_param_count = ngparams;
sig->param_count = nparams + nopt_args;
sig->sentinelpos = nparams;
sig->ret = mono_reflection_type_get_handle (rmb.rtype);
for (i = 0; i < nparams; i++) {
MonoReflectionType *rt = mono_array_get (rmb.parameters, MonoReflectionType *, i);
sig->params [i] = mono_reflection_type_get_handle (rt);
}
for (i = 0; i < nopt_args; i++) {
MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
sig->params [nparams + i] = mono_reflection_type_get_handle (rt);
}
sig_token = method_builder_encode_signature (assembly, &rmb);
parent = mono_image_create_token (assembly, obj, TRUE, TRUE);
g_assert (mono_metadata_token_table (parent) == MONO_TABLE_METHOD);
parent = mono_metadata_token_index (parent) << MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_METHODDEF;
name = mono_string_to_utf8 (rmb.name);
token = mono_image_get_varargs_method_token (
assembly, parent, name, sig_token);
g_free (name);
} else {
g_error ("requested method token for %s\n", klass->name);
}
g_hash_table_insert (assembly->vararg_aux_hash, GUINT_TO_POINTER (token), sig);
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), obj);
return token;
}
/*
* mono_image_create_token:
* @assembly: a dynamic assembly
* @obj:
* @register_token: Whenever to register the token in the assembly->tokens hash.
*
* Get a token to insert in the IL code stream for the given MemberInfo.
* The metadata emission routines need to pass FALSE as REGISTER_TOKEN, since by that time,
* the table_idx-es were recomputed, so registering the token would overwrite an existing
* entry.
*/
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_methodspec, gboolean register_token)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
/* Check for user defined reflection objects */
/* TypeDelegator is the only corlib type which doesn't look like a MonoReflectionType */
if (klass->image != mono_defaults.corlib || (strcmp (klass->name, "TypeDelegator") == 0))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported")); \
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params && !mb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_methodbuilder_token (assembly, mb, create_methodspec);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_ctorbuilder_token (assembly, mb);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)fb->typeb;
if (tb->generic_params) {
token = mono_image_get_generic_field_token (assembly, fb);
} else {
if ((tb->module->dynamic_image == assembly)) {
token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
} else {
token = mono_image_get_fieldref_token (assembly, (MonoObject*)fb, fb->handle);
}
}
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref_full (assembly, type, mc->generic_container == NULL));
} else if (strcmp (klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
if (create_methodspec)
token = mono_image_get_methodspec_token (assembly, m->method);
else
token = mono_image_get_inflated_method_token (assembly, m->method);
} else if ((m->method->klass->image == &assembly->image) &&
!m->method->klass->generic_class) {
static guint32 method_table_idx = 0xffffff;
if (m->method->klass->wastypebuilder) {
/* we use the same token as the one that was assigned
* to the Methodbuilder.
* FIXME: do the equivalent for Fields.
*/
token = m->method->token;
} else {
/*
* Each token should have a unique index, but the indexes are
* assigned by managed code, so we don't know about them. An
* easy solution is to count backwards...
*/
method_table_idx --;
token = MONO_TOKEN_METHOD_DEF | method_table_idx;
}
} else {
token = mono_image_get_methodref_token (assembly, m->method, create_methodspec);
}
/*g_print ("got token 0x%08x for %s\n", token, m->method->name);*/
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField *)obj;
if ((f->field->parent->image == &assembly->image) && !is_field_on_inst (f->field)) {
static guint32 field_table_idx = 0xffffff;
field_table_idx --;
token = MONO_TOKEN_FIELD_DEF | field_table_idx;
} else {
token = mono_image_get_fieldref_token (assembly, (MonoObject*)f, f->field);
}
/*g_print ("got token 0x%08x for %s\n", token, f->field->name);*/
} else if (strcmp (klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod *)obj;
token = mono_image_get_array_token (assembly, m);
} else if (strcmp (klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *s = (MonoReflectionSigHelper*)obj;
token = MONO_TOKEN_SIGNATURE | mono_image_get_sighelper_token (assembly, s);
} else if (strcmp (klass->name, "EnumBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
token = mono_image_get_field_on_inst_token (assembly, f);
} else if (strcmp (klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
token = mono_image_get_ctor_on_inst_token (assembly, c, create_methodspec);
} else if (strcmp (klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
token = mono_image_get_method_on_inst_token (assembly, m, create_methodspec);
} else if (is_sre_array (klass) || is_sre_byref (klass) || is_sre_pointer (klass)) {
MonoReflectionType *type = (MonoReflectionType *)obj;
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (type)));
} else {
g_error ("requested token for %s\n", klass->name);
}
if (register_token)
mono_image_register_token (assembly, token, obj);
return token;
}
/*
* mono_image_register_token:
*
* Register the TOKEN->OBJ mapping in the mapping table in ASSEMBLY. This is required for
* the Module.ResolveXXXToken () methods to work.
*/
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
MonoObject *prev = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
if (prev) {
/* There could be multiple MethodInfo objects with the same token */
//g_assert (prev == obj);
} else {
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), obj);
}
}
static MonoDynamicImage*
create_dynamic_mono_image (MonoDynamicAssembly *assembly, char *assembly_name, char *module_name)
{
static const guchar entrycode [16] = {0xff, 0x25, 0};
MonoDynamicImage *image;
int i;
const char *version;
if (!strcmp (mono_get_runtime_info ()->framework_version, "2.1"))
version = "v2.0.50727"; /* HACK: SL 2 enforces the .net 2 metadata version */
else
version = mono_get_runtime_info ()->runtime_version;
#if HAVE_BOEHM_GC
/* The MonoGHashTable's need GC tracking */
image = GC_MALLOC (sizeof (MonoDynamicImage));
#else
image = g_new0 (MonoDynamicImage, 1);
#endif
mono_profiler_module_event (&image->image, MONO_PROFILE_START_LOAD);
/*g_print ("created image %p\n", image);*/
/* keep in sync with image.c */
image->image.name = assembly_name;
image->image.assembly_name = image->image.name; /* they may be different */
image->image.module_name = module_name;
image->image.version = g_strdup (version);
image->image.md_version_major = 1;
image->image.md_version_minor = 1;
image->image.dynamic = TRUE;
image->image.references = g_new0 (MonoAssembly*, 1);
image->image.references [0] = NULL;
mono_image_init (&image->image);
image->token_fixups = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->method_to_table_idx = g_hash_table_new (NULL, NULL);
image->field_to_table_idx = g_hash_table_new (NULL, NULL);
image->method_aux_hash = g_hash_table_new (NULL, NULL);
image->vararg_aux_hash = g_hash_table_new (NULL, NULL);
image->handleref = g_hash_table_new (NULL, NULL);
image->handleref_managed = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->tokens = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->generic_def_objects = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->methodspec = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->typespec = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->typeref = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->blob_cache = g_hash_table_new ((GHashFunc)mono_blob_entry_hash, (GCompareFunc)mono_blob_entry_equal);
image->gen_params = g_ptr_array_new ();
/*g_print ("string heap create for image %p (%s)\n", image, module_name);*/
string_heap_init (&image->sheap);
mono_image_add_stream_data (&image->us, "", 1);
add_to_blob_cached (image, (char*) "", 1, NULL, 0);
/* import tables... */
mono_image_add_stream_data (&image->code, (char*)entrycode, sizeof (entrycode));
image->iat_offset = mono_image_add_stream_zero (&image->code, 8); /* two IAT entries */
image->idt_offset = mono_image_add_stream_zero (&image->code, 2 * sizeof (MonoIDT)); /* two IDT entries */
image->imp_names_offset = mono_image_add_stream_zero (&image->code, 2); /* flags for name entry */
mono_image_add_stream_data (&image->code, "_CorExeMain", 12);
mono_image_add_stream_data (&image->code, "mscoree.dll", 12);
image->ilt_offset = mono_image_add_stream_zero (&image->code, 8); /* two ILT entries */
stream_data_align (&image->code);
image->cli_header_offset = mono_image_add_stream_zero (&image->code, sizeof (MonoCLIHeader));
for (i=0; i < MONO_TABLE_NUM; ++i) {
image->tables [i].next_idx = 1;
image->tables [i].columns = table_sizes [i];
}
image->image.assembly = (MonoAssembly*)assembly;
image->run = assembly->run;
image->save = assembly->save;
image->pe_kind = 0x1; /* ILOnly */
image->machine = 0x14c; /* I386 */
mono_profiler_module_loaded (&image->image, MONO_PROFILE_OK);
return image;
}
#endif
static void
free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
{
g_free (key);
}
void
mono_dynamic_image_free (MonoDynamicImage *image)
{
MonoDynamicImage *di = image;
GList *list;
int i;
if (di->methodspec)
mono_g_hash_table_destroy (di->methodspec);
if (di->typespec)
g_hash_table_destroy (di->typespec);
if (di->typeref)
g_hash_table_destroy (di->typeref);
if (di->handleref)
g_hash_table_destroy (di->handleref);
if (di->handleref_managed)
mono_g_hash_table_destroy (di->handleref_managed);
if (di->tokens)
mono_g_hash_table_destroy (di->tokens);
if (di->generic_def_objects)
mono_g_hash_table_destroy (di->generic_def_objects);
if (di->blob_cache) {
g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
g_hash_table_destroy (di->blob_cache);
}
if (di->standalonesig_cache)
g_hash_table_destroy (di->standalonesig_cache);
for (list = di->array_methods; list; list = list->next) {
ArrayMethod *am = (ArrayMethod *)list->data;
g_free (am->sig);
g_free (am->name);
g_free (am);
}
g_list_free (di->array_methods);
if (di->gen_params) {
for (i = 0; i < di->gen_params->len; i++) {
GenericParamTableEntry *entry = g_ptr_array_index (di->gen_params, i);
if (entry->gparam->type.type) {
MonoGenericParam *param = entry->gparam->type.type->data.generic_param;
g_free ((char*)mono_generic_param_info (param)->name);
g_free (param);
}
mono_gc_deregister_root ((char*) &entry->gparam);
g_free (entry);
}
g_ptr_array_free (di->gen_params, TRUE);
}
if (di->token_fixups)
mono_g_hash_table_destroy (di->token_fixups);
if (di->method_to_table_idx)
g_hash_table_destroy (di->method_to_table_idx);
if (di->field_to_table_idx)
g_hash_table_destroy (di->field_to_table_idx);
if (di->method_aux_hash)
g_hash_table_destroy (di->method_aux_hash);
if (di->vararg_aux_hash)
g_hash_table_destroy (di->vararg_aux_hash);
g_free (di->strong_name);
g_free (di->win32_res);
if (di->public_key)
g_free (di->public_key);
/*g_print ("string heap destroy for image %p\n", di);*/
mono_dynamic_stream_reset (&di->sheap);
mono_dynamic_stream_reset (&di->code);
mono_dynamic_stream_reset (&di->resources);
mono_dynamic_stream_reset (&di->us);
mono_dynamic_stream_reset (&di->blob);
mono_dynamic_stream_reset (&di->tstream);
mono_dynamic_stream_reset (&di->guid);
for (i = 0; i < MONO_TABLE_NUM; ++i) {
g_free (di->tables [i].values);
}
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_basic_init:
* @assembly: an assembly builder object
*
* Create the MonoImage that represents the assembly builder and setup some
* of the helper hash table and the basic metadata streams.
*/
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
MonoDynamicAssembly *assembly;
MonoDynamicImage *image;
MonoDomain *domain = mono_object_domain (assemblyb);
MONO_ARCH_SAVE_REGS;
if (assemblyb->dynamic_assembly)
return;
#if HAVE_BOEHM_GC
/* assembly->assembly.image might be GC allocated */
assembly = assemblyb->dynamic_assembly = GC_MALLOC (sizeof (MonoDynamicAssembly));
#else
assembly = assemblyb->dynamic_assembly = g_new0 (MonoDynamicAssembly, 1);
#endif
mono_profiler_assembly_event (&assembly->assembly, MONO_PROFILE_START_LOAD);
assembly->assembly.ref_count = 1;
assembly->assembly.dynamic = TRUE;
assembly->assembly.corlib_internal = assemblyb->corlib_internal;
assemblyb->assembly.assembly = (MonoAssembly*)assembly;
assembly->assembly.basedir = mono_string_to_utf8 (assemblyb->dir);
if (assemblyb->culture)
assembly->assembly.aname.culture = mono_string_to_utf8 (assemblyb->culture);
else
assembly->assembly.aname.culture = g_strdup ("");
if (assemblyb->version) {
char *vstr = mono_string_to_utf8 (assemblyb->version);
char **version = g_strsplit (vstr, ".", 4);
char **parts = version;
assembly->assembly.aname.major = atoi (*parts++);
assembly->assembly.aname.minor = atoi (*parts++);
assembly->assembly.aname.build = *parts != NULL ? atoi (*parts++) : 0;
assembly->assembly.aname.revision = *parts != NULL ? atoi (*parts) : 0;
g_strfreev (version);
g_free (vstr);
} else {
assembly->assembly.aname.major = 0;
assembly->assembly.aname.minor = 0;
assembly->assembly.aname.build = 0;
assembly->assembly.aname.revision = 0;
}
assembly->run = assemblyb->access != 2;
assembly->save = assemblyb->access != 1;
assembly->domain = domain;
image = create_dynamic_mono_image (assembly, mono_string_to_utf8 (assemblyb->name), g_strdup ("RefEmit_YouForgotToDefineAModule"));
image->initial_image = TRUE;
assembly->assembly.aname.name = image->image.name;
assembly->assembly.image = &image->image;
if (assemblyb->pktoken && assemblyb->pktoken->max_length) {
/* -1 to correct for the trailing NULL byte */
if (assemblyb->pktoken->max_length != MONO_PUBLIC_KEY_TOKEN_LENGTH - 1) {
g_error ("Public key token length invalid for assembly %s: %i", assembly->assembly.aname.name, assemblyb->pktoken->max_length);
}
memcpy (&assembly->assembly.aname.public_key_token, mono_array_addr (assemblyb->pktoken, guint8, 0), assemblyb->pktoken->max_length);
}
mono_domain_assemblies_lock (domain);
domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, assembly);
mono_domain_assemblies_unlock (domain);
register_assembly (mono_object_domain (assemblyb), &assemblyb->assembly, &assembly->assembly);
mono_profiler_assembly_loaded (&assembly->assembly, MONO_PROFILE_OK);
mono_assembly_invoke_load_hook ((MonoAssembly*)assembly);
}
#endif /* !DISABLE_REFLECTION_EMIT */
#ifndef DISABLE_REFLECTION_EMIT_SAVE
static int
calc_section_size (MonoDynamicImage *assembly)
{
int nsections = 0;
/* alignment constraints */
mono_image_add_stream_zero (&assembly->code, 4 - (assembly->code.index % 4));
g_assert ((assembly->code.index % 4) == 0);
assembly->meta_size += 3;
assembly->meta_size &= ~3;
mono_image_add_stream_zero (&assembly->resources, 4 - (assembly->resources.index % 4));
g_assert ((assembly->resources.index % 4) == 0);
assembly->sections [MONO_SECTION_TEXT].size = assembly->meta_size + assembly->code.index + assembly->resources.index + assembly->strong_name_size;
assembly->sections [MONO_SECTION_TEXT].attrs = SECT_FLAGS_HAS_CODE | SECT_FLAGS_MEM_EXECUTE | SECT_FLAGS_MEM_READ;
nsections++;
if (assembly->win32_res) {
guint32 res_size = (assembly->win32_res_size + 3) & ~3;
assembly->sections [MONO_SECTION_RSRC].size = res_size;
assembly->sections [MONO_SECTION_RSRC].attrs = SECT_FLAGS_HAS_INITIALIZED_DATA | SECT_FLAGS_MEM_READ;
nsections++;
}
assembly->sections [MONO_SECTION_RELOC].size = 12;
assembly->sections [MONO_SECTION_RELOC].attrs = SECT_FLAGS_MEM_READ | SECT_FLAGS_MEM_DISCARDABLE | SECT_FLAGS_HAS_INITIALIZED_DATA;
nsections++;
return nsections;
}
typedef struct {
guint32 id;
guint32 offset;
GSList *children;
MonoReflectionWin32Resource *win32_res; /* Only for leaf nodes */
} ResTreeNode;
static int
resource_tree_compare_by_id (gconstpointer a, gconstpointer b)
{
ResTreeNode *t1 = (ResTreeNode*)a;
ResTreeNode *t2 = (ResTreeNode*)b;
return t1->id - t2->id;
}
/*
* resource_tree_create:
*
* Organize the resources into a resource tree.
*/
static ResTreeNode *
resource_tree_create (MonoArray *win32_resources)
{
ResTreeNode *tree, *res_node, *type_node, *lang_node;
GSList *l;
int i;
tree = g_new0 (ResTreeNode, 1);
for (i = 0; i < mono_array_length (win32_resources); ++i) {
MonoReflectionWin32Resource *win32_res =
(MonoReflectionWin32Resource*)mono_array_addr (win32_resources, MonoReflectionWin32Resource, i);
/* Create node */
/* FIXME: BUG: this stores managed references in unmanaged memory */
lang_node = g_new0 (ResTreeNode, 1);
lang_node->id = win32_res->lang_id;
lang_node->win32_res = win32_res;
/* Create type node if neccesary */
type_node = NULL;
for (l = tree->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_type) {
type_node = (ResTreeNode*)l->data;
break;
}
if (!type_node) {
type_node = g_new0 (ResTreeNode, 1);
type_node->id = win32_res->res_type;
/*
* The resource types have to be sorted otherwise
* Windows Explorer can't display the version information.
*/
tree->children = g_slist_insert_sorted (tree->children,
type_node, resource_tree_compare_by_id);
}
/* Create res node if neccesary */
res_node = NULL;
for (l = type_node->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_id) {
res_node = (ResTreeNode*)l->data;
break;
}
if (!res_node) {
res_node = g_new0 (ResTreeNode, 1);
res_node->id = win32_res->res_id;
type_node->children = g_slist_append (type_node->children, res_node);
}
res_node->children = g_slist_append (res_node->children, lang_node);
}
return tree;
}
/*
* resource_tree_encode:
*
* Encode the resource tree into the format used in the PE file.
*/
static void
resource_tree_encode (ResTreeNode *node, char *begin, char *p, char **endbuf)
{
char *entries;
MonoPEResourceDir dir;
MonoPEResourceDirEntry dir_entry;
MonoPEResourceDataEntry data_entry;
GSList *l;
guint32 res_id_entries;
/*
* For the format of the resource directory, see the article
* "An In-Depth Look into the Win32 Portable Executable File Format" by
* Matt Pietrek
*/
memset (&dir, 0, sizeof (dir));
memset (&dir_entry, 0, sizeof (dir_entry));
memset (&data_entry, 0, sizeof (data_entry));
g_assert (sizeof (dir) == 16);
g_assert (sizeof (dir_entry) == 8);
g_assert (sizeof (data_entry) == 16);
node->offset = p - begin;
/* IMAGE_RESOURCE_DIRECTORY */
res_id_entries = g_slist_length (node->children);
dir.res_id_entries = GUINT16_TO_LE (res_id_entries);
memcpy (p, &dir, sizeof (dir));
p += sizeof (dir);
/* Reserve space for entries */
entries = p;
p += sizeof (dir_entry) * res_id_entries;
/* Write children */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
if (child->win32_res) {
guint32 size;
child->offset = p - begin;
/* IMAGE_RESOURCE_DATA_ENTRY */
data_entry.rde_data_offset = GUINT32_TO_LE (p - begin + sizeof (data_entry));
size = mono_array_length (child->win32_res->res_data);
data_entry.rde_size = GUINT32_TO_LE (size);
memcpy (p, &data_entry, sizeof (data_entry));
p += sizeof (data_entry);
memcpy (p, mono_array_addr (child->win32_res->res_data, char, 0), size);
p += size;
} else {
resource_tree_encode (child, begin, p, &p);
}
}
/* IMAGE_RESOURCE_ENTRY */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
MONO_PE_RES_DIR_ENTRY_SET_NAME (dir_entry, FALSE, child->id);
MONO_PE_RES_DIR_ENTRY_SET_DIR (dir_entry, !child->win32_res, child->offset);
memcpy (entries, &dir_entry, sizeof (dir_entry));
entries += sizeof (dir_entry);
}
*endbuf = p;
}
static void
resource_tree_free (ResTreeNode * node)
{
GSList * list;
for (list = node->children; list; list = list->next)
resource_tree_free ((ResTreeNode*)list->data);
g_slist_free(node->children);
g_free (node);
}
static void
assembly_add_win32_resources (MonoDynamicImage *assembly, MonoReflectionAssemblyBuilder *assemblyb)
{
char *buf;
char *p;
guint32 size, i;
MonoReflectionWin32Resource *win32_res;
ResTreeNode *tree;
if (!assemblyb->win32_resources)
return;
/*
* Resources are stored in a three level tree inside the PE file.
* - level one contains a node for each type of resource
* - level two contains a node for each resource
* - level three contains a node for each instance of a resource for a
* specific language.
*/
tree = resource_tree_create (assemblyb->win32_resources);
/* Estimate the size of the encoded tree */
size = 0;
for (i = 0; i < mono_array_length (assemblyb->win32_resources); ++i) {
win32_res = (MonoReflectionWin32Resource*)mono_array_addr (assemblyb->win32_resources, MonoReflectionWin32Resource, i);
size += mono_array_length (win32_res->res_data);
}
/* Directory structure */
size += mono_array_length (assemblyb->win32_resources) * 256;
p = buf = g_malloc (size);
resource_tree_encode (tree, p, p, &p);
g_assert (p - buf <= size);
assembly->win32_res = g_malloc (p - buf);
assembly->win32_res_size = p - buf;
memcpy (assembly->win32_res, buf, p - buf);
g_free (buf);
resource_tree_free (tree);
}
static void
fixup_resource_directory (char *res_section, char *p, guint32 rva)
{
MonoPEResourceDir *dir = (MonoPEResourceDir*)p;
int i;
p += sizeof (MonoPEResourceDir);
for (i = 0; i < GUINT16_FROM_LE (dir->res_named_entries) + GUINT16_FROM_LE (dir->res_id_entries); ++i) {
MonoPEResourceDirEntry *dir_entry = (MonoPEResourceDirEntry*)p;
char *child = res_section + MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*dir_entry);
if (MONO_PE_RES_DIR_ENTRY_IS_DIR (*dir_entry)) {
fixup_resource_directory (res_section, child, rva);
} else {
MonoPEResourceDataEntry *data_entry = (MonoPEResourceDataEntry*)child;
data_entry->rde_data_offset = GUINT32_TO_LE (GUINT32_FROM_LE (data_entry->rde_data_offset) + rva);
}
p += sizeof (MonoPEResourceDirEntry);
}
}
static void
checked_write_file (HANDLE f, gconstpointer buffer, guint32 numbytes)
{
guint32 dummy;
if (!WriteFile (f, buffer, numbytes, &dummy, NULL))
g_error ("WriteFile returned %d\n", GetLastError ());
}
/*
* mono_image_create_pefile:
* @mb: a module builder object
*
* This function creates the PE-COFF header, the image sections, the CLI header * etc. all the data is written in
* assembly->pefile where it can be easily retrieved later in chunks.
*/
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
MonoMSDOSHeader *msdos;
MonoDotNetHeader *header;
MonoSectionTable *section;
MonoCLIHeader *cli_header;
guint32 size, image_size, virtual_base, text_offset;
guint32 header_start, section_start, file_offset, virtual_offset;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDynamicStream pefile_stream = {0};
MonoDynamicStream *pefile = &pefile_stream;
int i, nsections;
guint32 *rva, value;
guchar *p;
static const unsigned char msheader[] = {
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
assemblyb = mb->assemblyb;
mono_image_basic_init (assemblyb);
assembly = mb->dynamic_image;
assembly->pe_kind = assemblyb->pe_kind;
assembly->machine = assemblyb->machine;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->pe_kind = assemblyb->pe_kind;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->machine = assemblyb->machine;
mono_image_build_metadata (mb);
if (mb->is_main && assemblyb->resources) {
int len = mono_array_length (assemblyb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (assemblyb->resources, MonoReflectionResource, i));
}
if (mb->resources) {
int len = mono_array_length (mb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (mb->resources, MonoReflectionResource, i));
}
build_compressed_metadata (assembly);
if (mb->is_main)
assembly_add_win32_resources (assembly, assemblyb);
nsections = calc_section_size (assembly);
/* The DOS header and stub */
g_assert (sizeof (MonoMSDOSHeader) == sizeof (msheader));
mono_image_add_stream_data (pefile, (char*)msheader, sizeof (msheader));
/* the dotnet header */
header_start = mono_image_add_stream_zero (pefile, sizeof (MonoDotNetHeader));
/* the section tables */
section_start = mono_image_add_stream_zero (pefile, sizeof (MonoSectionTable) * nsections);
file_offset = section_start + sizeof (MonoSectionTable) * nsections;
virtual_offset = VIRT_ALIGN;
image_size = 0;
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
/* align offsets */
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
virtual_offset += VIRT_ALIGN - 1;
virtual_offset &= ~(VIRT_ALIGN - 1);
assembly->sections [i].offset = file_offset;
assembly->sections [i].rva = virtual_offset;
file_offset += assembly->sections [i].size;
virtual_offset += assembly->sections [i].size;
image_size += (assembly->sections [i].size + VIRT_ALIGN - 1) & ~(VIRT_ALIGN - 1);
}
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
image_size += section_start + sizeof (MonoSectionTable) * nsections;
/* back-patch info */
msdos = (MonoMSDOSHeader*)pefile->data;
msdos->pe_offset = GUINT32_FROM_LE (sizeof (MonoMSDOSHeader));
header = (MonoDotNetHeader*)(pefile->data + header_start);
header->pesig [0] = 'P';
header->pesig [1] = 'E';
header->coff.coff_machine = GUINT16_FROM_LE (assemblyb->machine);
header->coff.coff_sections = GUINT16_FROM_LE (nsections);
header->coff.coff_time = GUINT32_FROM_LE (time (NULL));
header->coff.coff_opt_header_size = GUINT16_FROM_LE (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4);
if (assemblyb->pekind == 1) {
/* it's a dll */
header->coff.coff_attributes = GUINT16_FROM_LE (0x210e);
} else {
/* it's an exe */
header->coff.coff_attributes = GUINT16_FROM_LE (0x010e);
}
virtual_base = 0x400000; /* FIXME: 0x10000000 if a DLL */
header->pe.pe_magic = GUINT16_FROM_LE (0x10B);
header->pe.pe_major = 6;
header->pe.pe_minor = 0;
size = assembly->sections [MONO_SECTION_TEXT].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_code_size = GUINT32_FROM_LE(size);
size = assembly->sections [MONO_SECTION_RSRC].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_data_size = GUINT32_FROM_LE(size);
g_assert (START_TEXT_RVA == assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_code_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_data_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
/* pe_rva_entry_point always at the beginning of the text section */
header->pe.pe_rva_entry_point = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->nt.pe_image_base = GUINT32_FROM_LE (virtual_base);
header->nt.pe_section_align = GUINT32_FROM_LE (VIRT_ALIGN);
header->nt.pe_file_alignment = GUINT32_FROM_LE (FILE_ALIGN);
header->nt.pe_os_major = GUINT16_FROM_LE (4);
header->nt.pe_os_minor = GUINT16_FROM_LE (0);
header->nt.pe_subsys_major = GUINT16_FROM_LE (4);
size = section_start;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->nt.pe_header_size = GUINT32_FROM_LE (size);
size = image_size;
size += VIRT_ALIGN - 1;
size &= ~(VIRT_ALIGN - 1);
header->nt.pe_image_size = GUINT32_FROM_LE (size);
/*
// Translate the PEFileKind value to the value expected by the Windows loader
*/
{
short kind;
/*
// PEFileKinds.Dll == 1
// PEFileKinds.ConsoleApplication == 2
// PEFileKinds.WindowApplication == 3
//
// need to get:
// IMAGE_SUBSYSTEM_WINDOWS_GUI 2 // Image runs in the Windows GUI subsystem.
// IMAGE_SUBSYSTEM_WINDOWS_CUI 3 // Image runs in the Windows character subsystem.
*/
if (assemblyb->pekind == 3)
kind = 2;
else
kind = 3;
header->nt.pe_subsys_required = GUINT16_FROM_LE (kind);
}
header->nt.pe_stack_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_stack_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_heap_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_heap_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_loader_flags = GUINT32_FROM_LE (0);
header->nt.pe_data_dir_count = GUINT32_FROM_LE (16);
/* fill data directory entries */
header->datadir.pe_resource_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].size);
header->datadir.pe_resource_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
header->datadir.pe_reloc_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].size);
header->datadir.pe_reloc_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].rva);
header->datadir.pe_cli_header.size = GUINT32_FROM_LE (72);
header->datadir.pe_cli_header.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->cli_header_offset);
header->datadir.pe_iat.size = GUINT32_FROM_LE (8);
header->datadir.pe_iat.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
/* patch entrypoint name */
if (assemblyb->pekind == 1)
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorDllMain", 12);
else
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorExeMain", 12);
/* patch imported function RVA name */
rva = (guint32*)(assembly->code.data + assembly->iat_offset);
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset);
/* the import table */
header->datadir.pe_import_table.size = GUINT32_FROM_LE (79); /* FIXME: magic number? */
header->datadir.pe_import_table.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->idt_offset);
/* patch imported dll RVA name and other entries in the dir */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, name_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset + 14); /* 14 is hint+strlen+1 of func name */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_address_table_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_lookup_table));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->ilt_offset);
p = (guchar*)(assembly->code.data + assembly->ilt_offset);
value = (assembly->text_rva + assembly->imp_names_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & (0xff);
*p++ = (value >> 16) & (0xff);
*p++ = (value >> 24) & (0xff);
/* the CLI header info */
cli_header = (MonoCLIHeader*)(assembly->code.data + assembly->cli_header_offset);
cli_header->ch_size = GUINT32_FROM_LE (72);
cli_header->ch_runtime_major = GUINT16_FROM_LE (2);
cli_header->ch_runtime_minor = GUINT16_FROM_LE (5);
cli_header->ch_flags = GUINT32_FROM_LE (assemblyb->pe_kind);
if (assemblyb->entry_point) {
guint32 table_idx = 0;
if (!strcmp (assemblyb->entry_point->object.vtable->klass->name, "MethodBuilder")) {
MonoReflectionMethodBuilder *methodb = (MonoReflectionMethodBuilder*)assemblyb->entry_point;
table_idx = methodb->table_idx;
} else {
table_idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, assemblyb->entry_point->method));
}
cli_header->ch_entry_point = GUINT32_FROM_LE (table_idx | MONO_TOKEN_METHOD_DEF);
} else {
cli_header->ch_entry_point = GUINT32_FROM_LE (0);
}
/* The embedded managed resources */
text_offset = assembly->text_rva + assembly->code.index;
cli_header->ch_resources.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_resources.size = GUINT32_FROM_LE (assembly->resources.index);
text_offset += assembly->resources.index;
cli_header->ch_metadata.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_metadata.size = GUINT32_FROM_LE (assembly->meta_size);
text_offset += assembly->meta_size;
if (assembly->strong_name_size) {
cli_header->ch_strong_name.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_strong_name.size = GUINT32_FROM_LE (assembly->strong_name_size);
text_offset += assembly->strong_name_size;
}
/* write the section tables and section content */
section = (MonoSectionTable*)(pefile->data + section_start);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
static const char section_names [][7] = {
".text", ".rsrc", ".reloc"
};
if (!assembly->sections [i].size)
continue;
strcpy (section->st_name, section_names [i]);
/*g_print ("output section %s (%d), size: %d\n", section->st_name, i, assembly->sections [i].size);*/
section->st_virtual_address = GUINT32_FROM_LE (assembly->sections [i].rva);
section->st_virtual_size = GUINT32_FROM_LE (assembly->sections [i].size);
section->st_raw_data_size = GUINT32_FROM_LE (GUINT32_TO_LE (section->st_virtual_size) + (FILE_ALIGN - 1));
section->st_raw_data_size &= GUINT32_FROM_LE (~(FILE_ALIGN - 1));
section->st_raw_data_ptr = GUINT32_FROM_LE (assembly->sections [i].offset);
section->st_flags = GUINT32_FROM_LE (assembly->sections [i].attrs);
section ++;
}
checked_write_file (file, pefile->data, pefile->index);
mono_dynamic_stream_reset (pefile);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
if (SetFilePointer (file, assembly->sections [i].offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
switch (i) {
case MONO_SECTION_TEXT:
/* patch entry point */
p = (guchar*)(assembly->code.data + 2);
value = (virtual_base + assembly->text_rva + assembly->iat_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & 0xff;
*p++ = (value >> 16) & 0xff;
*p++ = (value >> 24) & 0xff;
checked_write_file (file, assembly->code.data, assembly->code.index);
checked_write_file (file, assembly->resources.data, assembly->resources.index);
checked_write_file (file, assembly->image.raw_metadata, assembly->meta_size);
checked_write_file (file, assembly->strong_name, assembly->strong_name_size);
g_free (assembly->image.raw_metadata);
break;
case MONO_SECTION_RELOC: {
struct {
guint32 page_rva;
guint32 block_size;
guint16 type_and_offset;
guint16 term;
} reloc;
g_assert (sizeof (reloc) == 12);
reloc.page_rva = GUINT32_FROM_LE (assembly->text_rva);
reloc.block_size = GUINT32_FROM_LE (12);
/*
* the entrypoint is always at the start of the text section
* 3 is IMAGE_REL_BASED_HIGHLOW
* 2 is patch_size_rva - text_rva
*/
reloc.type_and_offset = GUINT16_FROM_LE ((3 << 12) + (2));
reloc.term = 0;
checked_write_file (file, &reloc, sizeof (reloc));
break;
}
case MONO_SECTION_RSRC:
if (assembly->win32_res) {
/* Fixup the offsets in the IMAGE_RESOURCE_DATA_ENTRY structures */
fixup_resource_directory (assembly->win32_res, assembly->win32_res, assembly->sections [i].rva);
checked_write_file (file, assembly->win32_res, assembly->win32_res_size);
}
break;
default:
g_assert_not_reached ();
}
}
/* check that the file is properly padded */
if (SetFilePointer (file, file_offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
if (! SetEndOfFile (file))
g_error ("SetEndOfFile returned %d\n", GetLastError ());
mono_dynamic_stream_reset (&assembly->code);
mono_dynamic_stream_reset (&assembly->us);
mono_dynamic_stream_reset (&assembly->blob);
mono_dynamic_stream_reset (&assembly->guid);
mono_dynamic_stream_reset (&assembly->sheap);
g_hash_table_foreach (assembly->blob_cache, (GHFunc)g_free, NULL);
g_hash_table_destroy (assembly->blob_cache);
assembly->blob_cache = NULL;
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
g_assert_not_reached ();
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
char *name;
MonoImage *image;
MonoImageOpenStatus status;
MonoDynamicAssembly *assembly;
guint32 module_count;
MonoImage **new_modules;
gboolean *new_modules_loaded;
name = mono_string_to_utf8 (fileName);
image = mono_image_open (name, &status);
if (!image) {
MonoException *exc;
if (status == MONO_IMAGE_ERROR_ERRNO)
exc = mono_get_exception_file_not_found (fileName);
else
exc = mono_get_exception_bad_image_format (name);
g_free (name);
mono_raise_exception (exc);
}
g_free (name);
assembly = ab->dynamic_assembly;
image->assembly = (MonoAssembly*)assembly;
module_count = image->assembly->image->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
new_modules_loaded = g_new0 (gboolean, module_count + 1);
if (image->assembly->image->modules)
memcpy (new_modules, image->assembly->image->modules, module_count * sizeof (MonoImage *));
if (image->assembly->image->modules_loaded)
memcpy (new_modules_loaded, image->assembly->image->modules_loaded, module_count * sizeof (gboolean));
new_modules [module_count] = image;
new_modules_loaded [module_count] = TRUE;
mono_image_addref (image);
g_free (image->assembly->image->modules);
image->assembly->image->modules = new_modules;
image->assembly->image->modules_loaded = new_modules_loaded;
image->assembly->image->module_count ++;
mono_assembly_load_references (image, &status);
if (status) {
mono_image_close (image);
mono_raise_exception (mono_get_exception_file_not_found (fileName));
}
return mono_module_get_object (mono_domain_get (), image);
}
#endif /* DISABLE_REFLECTION_EMIT */
/*
* We need to return always the same object for MethodInfo, FieldInfo etc..
* but we need to consider the reflected type.
* type uses a different hash, since it uses custom hash/equal functions.
*/
typedef struct {
gpointer item;
MonoClass *refclass;
} ReflectedEntry;
static gboolean
reflected_equal (gconstpointer a, gconstpointer b) {
const ReflectedEntry *ea = a;
const ReflectedEntry *eb = b;
return (ea->item == eb->item) && (ea->refclass == eb->refclass);
}
static guint
reflected_hash (gconstpointer a) {
const ReflectedEntry *ea = a;
return mono_aligned_addr_hash (ea->item);
}
#define CHECK_OBJECT(t,p,k) \
do { \
t _obj; \
ReflectedEntry e; \
e.item = (p); \
e.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
if ((_obj = mono_g_hash_table_lookup (domain->refobject_hash, &e))) { \
mono_domain_unlock (domain); \
return _obj; \
} \
mono_domain_unlock (domain); \
} while (0)
#ifdef HAVE_BOEHM_GC
/* ReflectedEntry doesn't need to be GC tracked */
#define ALLOC_REFENTRY g_new0 (ReflectedEntry, 1)
#define FREE_REFENTRY(entry) g_free ((entry))
#define REFENTRY_REQUIRES_CLEANUP
#else
#define ALLOC_REFENTRY mono_mempool_alloc (domain->mp, sizeof (ReflectedEntry))
/* FIXME: */
#define FREE_REFENTRY(entry)
#endif
#define CACHE_OBJECT(t,p,o,k) \
do { \
t _obj; \
ReflectedEntry pe; \
pe.item = (p); \
pe.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
_obj = mono_g_hash_table_lookup (domain->refobject_hash, &pe); \
if (!_obj) { \
ReflectedEntry *e = ALLOC_REFENTRY; \
e->item = (p); \
e->refclass = (k); \
mono_g_hash_table_insert (domain->refobject_hash, e,o); \
_obj = o; \
} \
mono_domain_unlock (domain); \
return _obj; \
} while (0)
static void
clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass)
{
mono_domain_lock (domain);
if (domain->refobject_hash) {
ReflectedEntry pe;
gpointer orig_pe, orig_value;
pe.item = o;
pe.refclass = klass;
if (mono_g_hash_table_lookup_extended (domain->refobject_hash, &pe, &orig_pe, &orig_value)) {
mono_g_hash_table_remove (domain->refobject_hash, &pe);
FREE_REFENTRY (orig_pe);
}
}
mono_domain_unlock (domain);
}
#ifdef REFENTRY_REQUIRES_CLEANUP
static void
cleanup_refobject_hash (gpointer key, gpointer value, gpointer user_data)
{
FREE_REFENTRY (key);
}
#endif
void
mono_reflection_cleanup_domain (MonoDomain *domain)
{
if (domain->refobject_hash) {
/*let's avoid scanning the whole hashtable if not needed*/
#ifdef REFENTRY_REQUIRES_CLEANUP
mono_g_hash_table_foreach (domain->refobject_hash, cleanup_refobject_hash, NULL);
#endif
mono_g_hash_table_destroy (domain->refobject_hash);
domain->refobject_hash = NULL;
}
}
#ifndef DISABLE_REFLECTION_EMIT
static gpointer
register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly)
{
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
static gpointer
register_module (MonoDomain *domain, MonoReflectionModuleBuilder *res, MonoDynamicImage *module)
{
CACHE_OBJECT (MonoReflectionModuleBuilder *, module, res, NULL);
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicImage *image = moduleb->dynamic_image;
MonoReflectionAssemblyBuilder *ab = moduleb->assemblyb;
if (!image) {
MonoError error;
int module_count;
MonoImage **new_modules;
MonoImage *ass;
char *name, *fqname;
/*
* FIXME: we already created an image in mono_image_basic_init (), but
* we don't know which module it belongs to, since that is only
* determined at assembly save time.
*/
/*image = (MonoDynamicImage*)ab->dynamic_assembly->assembly.image; */
name = mono_string_to_utf8 (ab->name);
fqname = mono_string_to_utf8_checked (moduleb->module.fqname, &error);
if (!mono_error_ok (&error)) {
g_free (name);
mono_error_raise_exception (&error);
}
image = create_dynamic_mono_image (ab->dynamic_assembly, name, fqname);
moduleb->module.image = &image->image;
moduleb->dynamic_image = image;
register_module (mono_object_domain (moduleb), moduleb, image);
/* register the module with the assembly */
ass = ab->dynamic_assembly->assembly.image;
module_count = ass->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
if (ass->modules)
memcpy (new_modules, ass->modules, module_count * sizeof (MonoImage *));
new_modules [module_count] = &image->image;
mono_image_addref (&image->image);
g_free (ass->modules);
ass->modules = new_modules;
ass->module_count ++;
}
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
MonoDynamicImage *image = moduleb->dynamic_image;
g_assert (type->type);
image->wrappers_type = mono_class_from_mono_type (type->type);
}
#endif
/*
* mono_assembly_get_object:
* @domain: an app domain
* @assembly: an assembly
*
* Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
*/
MonoReflectionAssembly*
mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
{
static MonoClass *assembly_type;
MonoReflectionAssembly *res;
CHECK_OBJECT (MonoReflectionAssembly *, assembly, NULL);
if (!assembly_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoAssembly");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Assembly");
g_assert (class);
assembly_type = class;
}
res = (MonoReflectionAssembly *)mono_object_new (domain, assembly_type);
res->assembly = assembly;
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
MonoReflectionModule*
mono_module_get_object (MonoDomain *domain, MonoImage *image)
{
static MonoClass *module_type;
MonoReflectionModule *res;
char* basename;
CHECK_OBJECT (MonoReflectionModule *, image, NULL);
if (!module_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
g_assert (class);
module_type = class;
}
res = (MonoReflectionModule *)mono_object_new (domain, module_type);
res->image = image;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, image->name));
basename = g_path_get_basename (image->name);
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, basename));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, image->module_name));
g_free (basename);
if (image->assembly->image == image) {
res->token = mono_metadata_make_token (MONO_TABLE_MODULE, 1);
} else {
int i;
res->token = 0;
if (image->assembly->image->modules) {
for (i = 0; i < image->assembly->image->module_count; i++) {
if (image->assembly->image->modules [i] == image)
res->token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1);
}
g_assert (res->token);
}
}
CACHE_OBJECT (MonoReflectionModule *, image, res, NULL);
}
MonoReflectionModule*
mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index)
{
static MonoClass *module_type;
MonoReflectionModule *res;
MonoTableInfo *table;
guint32 cols [MONO_FILE_SIZE];
const char *name;
guint32 i, name_idx;
const char *val;
if (!module_type) {
MonoClass *class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoModule");
if (class == NULL)
class = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Module");
g_assert (class);
module_type = class;
}
res = (MonoReflectionModule *)mono_object_new (domain, module_type);
table = &image->tables [MONO_TABLE_FILE];
g_assert (table_index < table->rows);
mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE);
res->image = NULL;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
/* Check whenever the row has a corresponding row in the moduleref table */
table = &image->tables [MONO_TABLE_MODULEREF];
for (i = 0; i < table->rows; ++i) {
name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME);
val = mono_metadata_string_heap (image, name_idx);
if (strcmp (val, name) == 0)
res->image = image->modules [i];
}
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, name));
res->is_resource = cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA;
res->token = mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1);
return res;
}
static gboolean
mymono_metadata_type_equal (MonoType *t1, MonoType *t2)
{
if ((t1->type != t2->type) ||
(t1->byref != t2->byref))
return FALSE;
switch (t1->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_STRING:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
return TRUE;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
return t1->data.klass == t2->data.klass;
case MONO_TYPE_PTR:
return mymono_metadata_type_equal (t1->data.type, t2->data.type);
case MONO_TYPE_ARRAY:
if (t1->data.array->rank != t2->data.array->rank)
return FALSE;
return t1->data.array->eklass == t2->data.array->eklass;
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *i1 = t1->data.generic_class->context.class_inst;
MonoGenericInst *i2 = t2->data.generic_class->context.class_inst;
if (i1->type_argc != i2->type_argc)
return FALSE;
if (!mono_metadata_type_equal (&t1->data.generic_class->container_class->byval_arg,
&t2->data.generic_class->container_class->byval_arg))
return FALSE;
/* FIXME: we should probably just compare the instance pointers directly. */
for (i = 0; i < i1->type_argc; ++i) {
if (!mono_metadata_type_equal (i1->type_argv [i], i2->type_argv [i]))
return FALSE;
}
return TRUE;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return t1->data.generic_param == t2->data.generic_param;
default:
g_error ("implement type compare for %0x!", t1->type);
return FALSE;
}
return FALSE;
}
static guint
mymono_metadata_type_hash (MonoType *t1)
{
guint hash;
hash = t1->type;
hash |= t1->byref << 6; /* do not collide with t1->type values */
switch (t1->type) {
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
/* check if the distribution is good enough */
return ((hash << 5) - hash) ^ mono_aligned_addr_hash (t1->data.klass);
case MONO_TYPE_PTR:
return ((hash << 5) - hash) ^ mymono_metadata_type_hash (t1->data.type);
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *inst = t1->data.generic_class->context.class_inst;
hash += g_str_hash (t1->data.generic_class->container_class->name);
hash *= 13;
for (i = 0; i < inst->type_argc; ++i) {
hash += mymono_metadata_type_hash (inst->type_argv [i]);
hash *= 13;
}
return hash;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return ((hash << 5) - hash) ^ GPOINTER_TO_UINT (t1->data.generic_param);
}
return hash;
}
static gboolean
verify_safe_for_managed_space (MonoType *type)
{
switch (type->type) {
#ifdef DEBUG_HARDER
case MONO_TYPE_ARRAY:
return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
case MONO_TYPE_PTR:
return verify_safe_for_managed_space (type->data.type);
case MONO_TYPE_SZARRAY:
return verify_safe_for_managed_space (&type->data.klass->byval_arg);
case MONO_TYPE_GENERICINST: {
MonoGenericInst *inst = type->data.generic_class->inst;
int i;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!verify_safe_for_managed_space (inst->type_argv [i]))
return FALSE;
break;
}
#endif
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return TRUE;
}
return TRUE;
}
static MonoType*
mono_type_normalize (MonoType *type)
{
int i;
MonoGenericClass *gclass;
MonoGenericInst *ginst;
MonoClass *gtd;
MonoGenericContainer *gcontainer;
MonoType **argv = NULL;
gboolean is_denorm_gtd = TRUE, requires_rebind = FALSE;
if (type->type != MONO_TYPE_GENERICINST)
return type;
gclass = type->data.generic_class;
ginst = gclass->context.class_inst;
if (!ginst->is_open)
return type;
gtd = gclass->container_class;
gcontainer = gtd->generic_container;
argv = g_newa (MonoType*, ginst->type_argc);
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *t = ginst->type_argv [i], *norm;
if (t->type != MONO_TYPE_VAR || t->data.generic_param->num != i || t->data.generic_param->owner != gcontainer)
is_denorm_gtd = FALSE;
norm = mono_type_normalize (t);
argv [i] = norm;
if (norm != t)
requires_rebind = TRUE;
}
if (is_denorm_gtd)
return type->byref == gtd->byval_arg.byref ? >d->byval_arg : >d->this_arg;
if (requires_rebind) {
MonoClass *klass = mono_class_bind_generic_parameters (gtd, ginst->type_argc, argv, gclass->is_dynamic);
return type->byref == klass->byval_arg.byref ? &klass->byval_arg : &klass->this_arg;
}
return type;
}
/*
* mono_type_get_object:
* @domain: an app domain
* @type: a type
*
* Return an System.MonoType object representing the type @type.
*/
MonoReflectionType*
mono_type_get_object (MonoDomain *domain, MonoType *type)
{
MonoType *norm_type;
MonoReflectionType *res;
MonoClass *klass = mono_class_from_mono_type (type);
/*we must avoid using @type as it might have come
* from a mono_metadata_type_dup and the caller
* expects that is can be freed.
* Using the right type from
*/
type = klass->byval_arg.byref == type->byref ? &klass->byval_arg : &klass->this_arg;
/* void is very common */
if (type->type == MONO_TYPE_VOID && domain->typeof_void)
return (MonoReflectionType*)domain->typeof_void;
/*
* If the vtable of the given class was already created, we can use
* the MonoType from there and avoid all locking and hash table lookups.
*
* We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects
* that the resulting object is different.
*/
if (type == &klass->byval_arg && !klass->image->dynamic) {
MonoVTable *vtable = mono_class_try_get_vtable (domain, klass);
if (vtable && vtable->type)
return vtable->type;
}
mono_loader_lock (); /*FIXME mono_class_init and mono_class_vtable acquire it*/
mono_domain_lock (domain);
if (!domain->type_hash)
domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mymono_metadata_type_hash,
(GCompareFunc)mymono_metadata_type_equal, MONO_HASH_VALUE_GC);
if ((res = mono_g_hash_table_lookup (domain->type_hash, type))) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/*Types must be normalized so a generic instance of the GTD get's the same inner type.
* For example in: Foo<A,B>; Bar<A> : Foo<A, Bar<A>>
* The second Bar will be encoded a generic instance of Bar with <A> as parameter.
* On all other places, Bar<A> will be encoded as the GTD itself. This is an implementation
* artifact of how generics are encoded and should be transparent to managed code so we
* need to weed out this diference when retrieving managed System.Type objects.
*/
norm_type = mono_type_normalize (type);
if (norm_type != type) {
res = mono_type_get_object (domain, norm_type);
mono_g_hash_table_insert (domain->type_hash, type, res);
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/* This MonoGenericClass hack is no longer necessary. Let's leave it here until we finish with the 2-stage type-builder setup.*/
if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder)
g_assert (0);
if (!verify_safe_for_managed_space (type)) {
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_raise_exception (mono_get_exception_invalid_operation ("This type cannot be propagated to managed space"));
}
if (mono_class_get_ref_info (klass) && !klass->wastypebuilder) {
gboolean is_type_done = TRUE;
/* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
* We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
* We can't simply close the types as this will interfere with other parts of the generics machinery.
*/
if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
if (gparam->owner && gparam->owner->is_method) {
MonoMethod *method = gparam->owner->owner.method;
if (method && mono_class_get_generic_type_definition (method->klass)->wastypebuilder)
is_type_done = FALSE;
} else if (gparam->owner && !gparam->owner->is_method) {
MonoClass *klass = gparam->owner->owner.klass;
if (klass && mono_class_get_generic_type_definition (klass)->wastypebuilder)
is_type_done = FALSE;
}
}
/* g_assert_not_reached (); */
/* should this be considered an error condition? */
if (is_type_done && !type->byref) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return mono_class_get_ref_info (klass);
}
}
#ifdef HAVE_SGEN_GC
res = (MonoReflectionType *)mono_gc_alloc_pinned_obj (mono_class_vtable (domain, mono_defaults.monotype_class), mono_class_instance_size (mono_defaults.monotype_class));
#else
res = (MonoReflectionType *)mono_object_new (domain, mono_defaults.monotype_class);
#endif
res->type = type;
mono_g_hash_table_insert (domain->type_hash, type, res);
if (type->type == MONO_TYPE_VOID)
domain->typeof_void = (MonoObject*)res;
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/*
* mono_method_get_object:
* @domain: an app domain
* @method: a method
* @refclass: the reflected type (can be NULL)
*
* Return an System.Reflection.MonoMethod object representing the method @method.
*/
MonoReflectionMethod*
mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
/*
* We use the same C representation for methods and constructors, but the type
* name in C# is different.
*/
static MonoClass *System_Reflection_MonoMethod = NULL;
static MonoClass *System_Reflection_MonoCMethod = NULL;
static MonoClass *System_Reflection_MonoGenericMethod = NULL;
static MonoClass *System_Reflection_MonoGenericCMethod = NULL;
MonoClass *klass;
MonoReflectionMethod *ret;
if (method->is_inflated) {
MonoReflectionGenericMethod *gret;
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if ((*method->name == '.') && (!strcmp (method->name, ".ctor") || !strcmp (method->name, ".cctor"))) {
if (!System_Reflection_MonoGenericCMethod)
System_Reflection_MonoGenericCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericCMethod");
klass = System_Reflection_MonoGenericCMethod;
} else {
if (!System_Reflection_MonoGenericMethod)
System_Reflection_MonoGenericMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericMethod");
klass = System_Reflection_MonoGenericMethod;
}
gret = (MonoReflectionGenericMethod*)mono_object_new (domain, klass);
gret->method.method = method;
MONO_OBJECT_SETREF (gret, method.name, mono_string_new (domain, method->name));
MONO_OBJECT_SETREF (gret, method.reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, (MonoReflectionMethod*)gret, refclass);
}
if (!refclass)
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) {
if (!System_Reflection_MonoCMethod)
System_Reflection_MonoCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoCMethod");
klass = System_Reflection_MonoCMethod;
}
else {
if (!System_Reflection_MonoMethod)
System_Reflection_MonoMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoMethod");
klass = System_Reflection_MonoMethod;
}
ret = (MonoReflectionMethod*)mono_object_new (domain, klass);
ret->method = method;
MONO_OBJECT_SETREF (ret, reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, ret, refclass);
}
/*
* mono_method_clear_object:
*
* Clear the cached reflection objects for the dynamic method METHOD.
*/
void
mono_method_clear_object (MonoDomain *domain, MonoMethod *method)
{
MonoClass *klass;
g_assert (method->dynamic);
klass = method->klass;
while (klass) {
clear_cached_object (domain, method, klass);
klass = klass->parent;
}
/* Added by mono_param_get_objects () */
clear_cached_object (domain, &(method->signature), NULL);
klass = method->klass;
while (klass) {
clear_cached_object (domain, &(method->signature), klass);
klass = klass->parent;
}
}
/*
* mono_field_get_object:
* @domain: an app domain
* @klass: a type
* @field: a field
*
* Return an System.Reflection.MonoField object representing the field @field
* in class @klass.
*/
MonoReflectionField*
mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field)
{
MonoReflectionField *res;
static MonoClass *monofield_klass;
CHECK_OBJECT (MonoReflectionField *, field, klass);
if (!monofield_klass)
monofield_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoField");
res = (MonoReflectionField *)mono_object_new (domain, monofield_klass);
res->klass = klass;
res->field = field;
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, mono_field_get_name (field)));
if (is_field_on_inst (field)) {
res->attrs = get_field_on_inst_generic_type (field)->attrs;
MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type));
} else {
if (field->type)
MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type));
res->attrs = mono_field_get_flags (field);
}
CACHE_OBJECT (MonoReflectionField *, field, res, klass);
}
/*
* mono_property_get_object:
* @domain: an app domain
* @klass: a type
* @property: a property
*
* Return an System.Reflection.MonoProperty object representing the property @property
* in class @klass.
*/
MonoReflectionProperty*
mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property)
{
MonoReflectionProperty *res;
static MonoClass *monoproperty_klass;
CHECK_OBJECT (MonoReflectionProperty *, property, klass);
if (!monoproperty_klass)
monoproperty_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoProperty");
res = (MonoReflectionProperty *)mono_object_new (domain, monoproperty_klass);
res->klass = klass;
res->property = property;
CACHE_OBJECT (MonoReflectionProperty *, property, res, klass);
}
/*
* mono_event_get_object:
* @domain: an app domain
* @klass: a type
* @event: a event
*
* Return an System.Reflection.MonoEvent object representing the event @event
* in class @klass.
*/
MonoReflectionEvent*
mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event)
{
MonoReflectionEvent *res;
MonoReflectionMonoEvent *mono_event;
static MonoClass *monoevent_klass;
CHECK_OBJECT (MonoReflectionEvent *, event, klass);
if (!monoevent_klass)
monoevent_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoEvent");
mono_event = (MonoReflectionMonoEvent *)mono_object_new (domain, monoevent_klass);
mono_event->klass = klass;
mono_event->event = event;
res = (MonoReflectionEvent*)mono_event;
CACHE_OBJECT (MonoReflectionEvent *, event, res, klass);
}
/**
* mono_get_reflection_missing_object:
* @domain: Domain where the object lives
*
* Returns the System.Reflection.Missing.Value singleton object
* (of type System.Reflection.Missing).
*
* Used as the value for ParameterInfo.DefaultValue when Optional
* is present
*/
static MonoObject *
mono_get_reflection_missing_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *missing_value_field = NULL;
if (!missing_value_field) {
MonoClass *missing_klass;
missing_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Missing");
mono_class_init (missing_klass);
missing_value_field = mono_class_get_field_from_name (missing_klass, "Value");
g_assert (missing_value_field);
}
obj = mono_field_get_value_object (domain, missing_value_field, NULL);
g_assert (obj);
return obj;
}
static MonoObject*
get_dbnull (MonoDomain *domain, MonoObject **dbnull)
{
if (!*dbnull)
*dbnull = mono_get_dbnull_object (domain);
return *dbnull;
}
static MonoObject*
get_reflection_missing (MonoDomain *domain, MonoObject **reflection_missing)
{
if (!*reflection_missing)
*reflection_missing = mono_get_reflection_missing_object (domain);
return *reflection_missing;
}
/*
* mono_param_get_objects:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.ParameterInfo array object representing the parameters
* in the method @method.
*/
MonoArray*
mono_param_get_objects_internal (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
static MonoClass *System_Reflection_ParameterInfo;
static MonoClass *System_Reflection_ParameterInfo_array;
MonoArray *res = NULL;
MonoReflectionMethod *member = NULL;
MonoReflectionParameter *param = NULL;
char **names, **blobs = NULL;
guint32 *types = NULL;
MonoType *type = NULL;
MonoObject *dbnull = NULL;
MonoObject *missing = NULL;
MonoMarshalSpec **mspecs;
MonoMethodSignature *sig;
MonoVTable *pinfo_vtable;
int i;
if (!System_Reflection_ParameterInfo_array) {
MonoClass *klass;
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ParameterInfo");
mono_memory_barrier ();
System_Reflection_ParameterInfo = klass;
klass = mono_array_class_get (klass, 1);
mono_memory_barrier ();
System_Reflection_ParameterInfo_array = klass;
}
if (!mono_method_signature (method)->param_count)
return mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), 0);
/* Note: the cache is based on the address of the signature into the method
* since we already cache MethodInfos with the method as keys.
*/
CHECK_OBJECT (MonoArray*, &(method->signature), refclass);
sig = mono_method_signature (method);
member = mono_method_get_object (domain, method, refclass);
names = g_new (char *, sig->param_count);
mono_method_get_param_names (method, (const char **) names);
mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
mono_method_get_marshal_info (method, mspecs);
res = mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), sig->param_count);
pinfo_vtable = mono_class_vtable (domain, System_Reflection_ParameterInfo);
for (i = 0; i < sig->param_count; ++i) {
param = (MonoReflectionParameter *)mono_object_new_specific (pinfo_vtable);
MONO_OBJECT_SETREF (param, ClassImpl, mono_type_get_object (domain, sig->params [i]));
MONO_OBJECT_SETREF (param, MemberImpl, (MonoObject*)member);
MONO_OBJECT_SETREF (param, NameImpl, mono_string_new (domain, names [i]));
param->PositionImpl = i;
param->AttrsImpl = sig->params [i]->attrs;
if (!(param->AttrsImpl & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
} else {
if (!blobs) {
blobs = g_new0 (char *, sig->param_count);
types = g_new0 (guint32, sig->param_count);
get_default_param_value_blobs (method, blobs, types);
}
/* Build MonoType for the type from the Constant Table */
if (!type)
type = g_new0 (MonoType, 1);
type->type = types [i];
type->data.klass = NULL;
if (types [i] == MONO_TYPE_CLASS)
type->data.klass = mono_defaults.object_class;
else if ((sig->params [i]->type == MONO_TYPE_VALUETYPE) && sig->params [i]->data.klass->enumtype) {
/* For enums, types [i] contains the base type */
type->type = MONO_TYPE_VALUETYPE;
type->data.klass = mono_class_from_mono_type (sig->params [i]);
} else
type->data.klass = mono_class_from_mono_type (type);
MONO_OBJECT_SETREF (param, DefaultValueImpl, mono_get_object_from_blob (domain, type, blobs [i]));
/* Type in the Constant table is MONO_TYPE_CLASS for nulls */
if (types [i] != MONO_TYPE_CLASS && !param->DefaultValueImpl) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
}
}
if (mspecs [i + 1])
MONO_OBJECT_SETREF (param, MarshalAsImpl, (MonoObject*)mono_reflection_marshal_from_marshal_spec (domain, method->klass, mspecs [i + 1]));
mono_array_setref (res, i, param);
}
g_free (names);
g_free (blobs);
g_free (types);
g_free (type);
for (i = mono_method_signature (method)->param_count; i >= 0; i--)
if (mspecs [i])
mono_metadata_free_marshal_spec (mspecs [i]);
g_free (mspecs);
CACHE_OBJECT (MonoArray *, &(method->signature), res, refclass);
}
MonoArray*
mono_param_get_objects (MonoDomain *domain, MonoMethod *method)
{
return mono_param_get_objects_internal (domain, method, NULL);
}
/*
* mono_method_body_get_object:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.MethodBody object representing the method @method.
*/
MonoReflectionMethodBody*
mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
{
static MonoClass *System_Reflection_MethodBody = NULL;
static MonoClass *System_Reflection_LocalVariableInfo = NULL;
static MonoClass *System_Reflection_ExceptionHandlingClause = NULL;
MonoReflectionMethodBody *ret;
MonoMethodHeader *header;
MonoImage *image;
guint32 method_rva, local_var_sig_token;
char *ptr;
unsigned char format, flags;
int i;
if (!System_Reflection_MethodBody)
System_Reflection_MethodBody = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MethodBody");
if (!System_Reflection_LocalVariableInfo)
System_Reflection_LocalVariableInfo = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "LocalVariableInfo");
if (!System_Reflection_ExceptionHandlingClause)
System_Reflection_ExceptionHandlingClause = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ExceptionHandlingClause");
CHECK_OBJECT (MonoReflectionMethodBody *, method, NULL);
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME))
return NULL;
image = method->klass->image;
header = mono_method_get_header (method);
if (!image->dynamic) {
/* Obtain local vars signature token */
method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA);
ptr = mono_image_rva_map (image, method_rva);
flags = *(const unsigned char *) ptr;
format = flags & METHOD_HEADER_FORMAT_MASK;
switch (format){
case METHOD_HEADER_TINY_FORMAT:
local_var_sig_token = 0;
break;
case METHOD_HEADER_FAT_FORMAT:
ptr += 2;
ptr += 2;
ptr += 4;
local_var_sig_token = read32 (ptr);
break;
default:
g_assert_not_reached ();
}
} else
local_var_sig_token = 0; //FIXME
ret = (MonoReflectionMethodBody*)mono_object_new (domain, System_Reflection_MethodBody);
ret->init_locals = header->init_locals;
ret->max_stack = header->max_stack;
ret->local_var_sig_token = local_var_sig_token;
MONO_OBJECT_SETREF (ret, il, mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size));
memcpy (mono_array_addr (ret->il, guint8, 0), header->code, header->code_size);
/* Locals */
MONO_OBJECT_SETREF (ret, locals, mono_array_new_cached (domain, System_Reflection_LocalVariableInfo, header->num_locals));
for (i = 0; i < header->num_locals; ++i) {
MonoReflectionLocalVariableInfo *info = (MonoReflectionLocalVariableInfo*)mono_object_new (domain, System_Reflection_LocalVariableInfo);
MONO_OBJECT_SETREF (info, local_type, mono_type_get_object (domain, header->locals [i]));
info->is_pinned = header->locals [i]->pinned;
info->local_index = i;
mono_array_setref (ret->locals, i, info);
}
/* Exceptions */
MONO_OBJECT_SETREF (ret, clauses, mono_array_new_cached (domain, System_Reflection_ExceptionHandlingClause, header->num_clauses));
for (i = 0; i < header->num_clauses; ++i) {
MonoReflectionExceptionHandlingClause *info = (MonoReflectionExceptionHandlingClause*)mono_object_new (domain, System_Reflection_ExceptionHandlingClause);
MonoExceptionClause *clause = &header->clauses [i];
info->flags = clause->flags;
info->try_offset = clause->try_offset;
info->try_length = clause->try_len;
info->handler_offset = clause->handler_offset;
info->handler_length = clause->handler_len;
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
info->filter_offset = clause->data.filter_offset;
else if (clause->data.catch_class)
MONO_OBJECT_SETREF (info, catch_type, mono_type_get_object (mono_domain_get (), &clause->data.catch_class->byval_arg));
mono_array_setref (ret->clauses, i, info);
}
mono_metadata_free_mh (header);
CACHE_OBJECT (MonoReflectionMethodBody *, method, ret, NULL);
return ret;
}
/**
* mono_get_dbnull_object:
* @domain: Domain where the object lives
*
* Returns the System.DBNull.Value singleton object
*
* Used as the value for ParameterInfo.DefaultValue
*/
MonoObject *
mono_get_dbnull_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *dbnull_value_field = NULL;
if (!dbnull_value_field) {
MonoClass *dbnull_klass;
dbnull_klass = mono_class_from_name (mono_defaults.corlib, "System", "DBNull");
mono_class_init (dbnull_klass);
dbnull_value_field = mono_class_get_field_from_name (dbnull_klass, "Value");
g_assert (dbnull_value_field);
}
obj = mono_field_get_value_object (domain, dbnull_value_field, NULL);
g_assert (obj);
return obj;
}
static void
get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types)
{
guint32 param_index, i, lastp, crow = 0;
guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE];
gint32 idx;
MonoClass *klass = method->klass;
MonoImage *image = klass->image;
MonoMethodSignature *methodsig = mono_method_signature (method);
MonoTableInfo *constt;
MonoTableInfo *methodt;
MonoTableInfo *paramt;
if (!methodsig->param_count)
return;
mono_class_init (klass);
if (klass->image->dynamic) {
MonoReflectionMethodAux *aux;
if (method->is_inflated)
method = ((MonoMethodInflated*)method)->declaring;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (aux && aux->param_defaults) {
memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*));
memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32));
}
return;
}
methodt = &klass->image->tables [MONO_TABLE_METHOD];
paramt = &klass->image->tables [MONO_TABLE_PARAM];
constt = &image->tables [MONO_TABLE_CONSTANT];
idx = mono_method_get_index (method) - 1;
g_assert (idx != -1);
param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
if (idx + 1 < methodt->rows)
lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
else
lastp = paramt->rows + 1;
for (i = param_index; i < lastp; ++i) {
guint32 paramseq;
mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE);
paramseq = param_cols [MONO_PARAM_SEQUENCE];
if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT))
continue;
crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1);
if (!crow) {
continue;
}
mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE);
blobs [paramseq - 1] = (gpointer) mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]);
types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE];
}
return;
}
MonoObject *
mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob)
{
void *retval;
MonoClass *klass;
MonoObject *object;
MonoType *basetype = type;
if (!blob)
return NULL;
klass = mono_class_from_mono_type (type);
if (klass->valuetype) {
object = mono_object_new (domain, klass);
retval = ((gchar *) object + sizeof (MonoObject));
if (klass->enumtype)
basetype = mono_class_enum_basetype (klass);
} else {
retval = &object;
}
if (!mono_get_constant_value_from_blob (domain, basetype->type, blob, retval))
return object;
else
return NULL;
}
static int
assembly_name_to_aname (MonoAssemblyName *assembly, char *p) {
int found_sep;
char *s;
memset (assembly, 0, sizeof (MonoAssemblyName));
assembly->name = p;
assembly->culture = "";
memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@'))
p++;
found_sep = 0;
while (g_ascii_isspace (*p) || *p == ',') {
*p++ = 0;
found_sep = 1;
continue;
}
/* failed */
if (!found_sep)
return 1;
while (*p) {
if (*p == 'V' && g_ascii_strncasecmp (p, "Version=", 8) == 0) {
p += 8;
assembly->major = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->minor = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->build = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->revision = strtoul (p, &s, 10);
if (s == p)
return 1;
p = s;
} else if (*p == 'C' && g_ascii_strncasecmp (p, "Culture=", 8) == 0) {
p += 8;
if (g_ascii_strncasecmp (p, "neutral", 7) == 0) {
assembly->culture = "";
p += 7;
} else {
assembly->culture = p;
while (*p && *p != ',') {
p++;
}
}
} else if (*p == 'P' && g_ascii_strncasecmp (p, "PublicKeyToken=", 15) == 0) {
p += 15;
if (strncmp (p, "null", 4) == 0) {
p += 4;
} else {
int len;
gchar *start = p;
while (*p && *p != ',') {
p++;
}
len = (p - start + 1);
if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH)
len = MONO_PUBLIC_KEY_TOKEN_LENGTH;
g_strlcpy ((char*)assembly->public_key_token, start, len);
}
} else {
while (*p && *p != ',')
p++;
}
found_sep = 0;
while (g_ascii_isspace (*p) || *p == ',') {
*p++ = 0;
found_sep = 1;
continue;
}
/* failed */
if (!found_sep)
return 1;
}
return 0;
}
/*
* mono_reflection_parse_type:
* @name: type name
*
* Parse a type name as accepted by the GetType () method and output the info
* extracted in the info structure.
* the name param will be mangled, so, make a copy before passing it to this function.
* The fields in info will be valid until the memory pointed to by name is valid.
*
* See also mono_type_get_name () below.
*
* Returns: 0 on parse error.
*/
static int
_mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
MonoTypeNameParse *info)
{
char *start, *p, *w, *temp, *last_point, *startn;
int in_modifiers = 0;
int isbyref = 0, rank, arity = 0, i;
start = p = w = name;
//FIXME could we just zero the whole struct? memset (&info, 0, sizeof (MonoTypeNameParse))
memset (&info->assembly, 0, sizeof (MonoAssemblyName));
info->name = info->name_space = NULL;
info->nested = NULL;
info->modifiers = NULL;
info->type_arguments = NULL;
/* last_point separates the namespace from the name */
last_point = NULL;
/* Skips spaces */
while (*p == ' ') p++, start++, w++, name++;
while (*p) {
switch (*p) {
case '+':
*p = 0; /* NULL terminate the name */
startn = p + 1;
info->nested = g_list_append (info->nested, startn);
/* we have parsed the nesting namespace + name */
if (info->name)
break;
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
break;
case '.':
last_point = p;
break;
case '\\':
++p;
break;
case '&':
case '*':
case '[':
case ',':
case ']':
in_modifiers = 1;
break;
case '`':
++p;
i = strtol (p, &temp, 10);
arity += i;
if (p == temp)
return 0;
p = temp-1;
break;
default:
break;
}
if (in_modifiers)
break;
// *w++ = *p++;
p++;
}
if (!info->name) {
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
}
while (*p) {
switch (*p) {
case '&':
if (isbyref) /* only one level allowed by the spec */
return 0;
isbyref = 1;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0));
*p++ = 0;
break;
case '*':
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1));
*p++ = 0;
break;
case '[':
if (arity != 0) {
*p++ = 0;
info->type_arguments = g_ptr_array_new ();
for (i = 0; i < arity; i++) {
MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1);
gboolean fqname = FALSE;
g_ptr_array_add (info->type_arguments, subinfo);
if (*p == '[') {
p++;
fqname = TRUE;
}
if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo))
return 0;
/*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/
if (fqname && (*p != ']')) {
char *aname;
if (*p != ',')
return 0;
*p++ = 0;
aname = p;
while (*p && (*p != ']'))
p++;
if (*p != ']')
return 0;
*p++ = 0;
while (*aname) {
if (g_ascii_isspace (*aname)) {
++aname;
continue;
}
break;
}
if (!*aname ||
!assembly_name_to_aname (&subinfo->assembly, aname))
return 0;
} else if (fqname && (*p == ']')) {
*p++ = 0;
}
if (i + 1 < arity) {
if (*p != ',')
return 0;
} else {
if (*p != ']')
return 0;
}
*p++ = 0;
}
arity = 0;
break;
}
rank = 1;
*p++ = 0;
while (*p) {
if (*p == ']')
break;
if (*p == ',')
rank++;
else if (*p == '*') /* '*' means unknown lower bound */
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2));
else
return 0;
++p;
}
if (*p++ != ']')
return 0;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank));
break;
case ']':
if (is_recursed)
goto end;
return 0;
case ',':
if (is_recursed)
goto end;
*p++ = 0;
while (*p) {
if (g_ascii_isspace (*p)) {
++p;
continue;
}
break;
}
if (!*p)
return 0; /* missing assembly name */
if (!assembly_name_to_aname (&info->assembly, p))
return 0;
break;
default:
return 0;
}
if (info->assembly.name)
break;
}
// *w = 0; /* terminate class name */
end:
if (!info->name || !*info->name)
return 0;
if (endptr)
*endptr = p;
/* add other consistency checks */
return 1;
}
int
mono_reflection_parse_type (char *name, MonoTypeNameParse *info)
{
return _mono_reflection_parse_type (name, NULL, FALSE, info);
}
static MonoType*
_mono_reflection_get_type_from_info (MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase)
{
gboolean type_resolve = FALSE;
MonoType *type;
MonoImage *rootimage = image;
if (info->assembly.name) {
MonoAssembly *assembly = mono_assembly_loaded (&info->assembly);
if (!assembly && image && image->assembly && mono_assembly_names_equal (&info->assembly, &image->assembly->aname))
/*
* This could happen in the AOT compiler case when the search hook is not
* installed.
*/
assembly = image->assembly;
if (!assembly) {
/* then we must load the assembly ourselve - see #60439 */
assembly = mono_assembly_load (&info->assembly, NULL, NULL);
if (!assembly)
return NULL;
}
image = assembly->image;
} else if (!image) {
image = mono_defaults.corlib;
}
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
if (type == NULL && !info->assembly.name && image != mono_defaults.corlib) {
image = mono_defaults.corlib;
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
}
return type;
}
static MonoType*
mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoClass *klass;
GList *mod;
int modval;
gboolean bounded = FALSE;
if (!image)
image = mono_defaults.corlib;
if (ignorecase)
klass = mono_class_from_name_case (image, info->name_space, info->name);
else
klass = mono_class_from_name (image, info->name_space, info->name);
if (!klass)
return NULL;
for (mod = info->nested; mod; mod = mod->next) {
gpointer iter = NULL;
MonoClass *parent;
parent = klass;
mono_class_init (parent);
while ((klass = mono_class_get_nested_types (parent, &iter))) {
if (ignorecase) {
if (mono_utf8_strcasecmp (klass->name, mod->data) == 0)
break;
} else {
if (strcmp (klass->name, mod->data) == 0)
break;
}
}
if (!klass)
break;
}
if (!klass)
return NULL;
if (info->type_arguments) {
MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len);
MonoReflectionType *the_type;
MonoType *instance;
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
type_args [i] = _mono_reflection_get_type_from_info (subinfo, rootimage, ignorecase);
if (!type_args [i]) {
g_free (type_args);
return NULL;
}
}
the_type = mono_type_get_object (mono_domain_get (), &klass->byval_arg);
instance = mono_reflection_bind_generic_parameters (
the_type, info->type_arguments->len, type_args);
g_free (type_args);
if (!instance)
return NULL;
klass = mono_class_from_mono_type (instance);
}
for (mod = info->modifiers; mod; mod = mod->next) {
modval = GPOINTER_TO_UINT (mod->data);
if (!modval) { /* byref: must be last modifier */
return &klass->this_arg;
} else if (modval == -1) {
klass = mono_ptr_class_get (&klass->byval_arg);
} else if (modval == -2) {
bounded = TRUE;
} else { /* array rank */
klass = mono_bounded_array_class_get (klass, modval, bounded);
}
}
return &klass->byval_arg;
}
/*
* mono_reflection_get_type:
* @image: a metadata context
* @info: type description structure
* @ignorecase: flag for case-insensitive string compares
* @type_resolve: whenever type resolve was already tried
*
* Build a MonoType from the type description in @info.
*
*/
MonoType*
mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) {
return mono_reflection_get_type_with_rootimage(image, image, info, ignorecase, type_resolve);
}
static MonoType*
mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoReflectionAssemblyBuilder *abuilder;
MonoType *type;
int i;
g_assert (assembly->dynamic);
abuilder = (MonoReflectionAssemblyBuilder*)mono_assembly_get_object (((MonoDynamicAssembly*)assembly)->domain, assembly);
/* Enumerate all modules */
type = NULL;
if (abuilder->modules) {
for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
type = mono_reflection_get_type_internal (rootimage, &mb->dynamic_image->image, info, ignorecase);
if (type)
break;
}
}
if (!type && abuilder->loaded_modules) {
for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
type = mono_reflection_get_type_internal (rootimage, mod->image, info, ignorecase);
if (type)
break;
}
}
return type;
}
MonoType*
mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve)
{
MonoType *type;
MonoReflectionAssembly *assembly;
GString *fullName;
GList *mod;
if (image && image->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase);
if (type)
return type;
if (!mono_domain_has_type_resolve (mono_domain_get ()))
return NULL;
if (type_resolve) {
if (*type_resolve)
return NULL;
else
*type_resolve = TRUE;
}
/* Reconstruct the type name */
fullName = g_string_new ("");
if (info->name_space && (info->name_space [0] != '\0'))
g_string_printf (fullName, "%s.%s", info->name_space, info->name);
else
g_string_printf (fullName, "%s", info->name);
for (mod = info->nested; mod; mod = mod->next)
g_string_append_printf (fullName, "+%s", (char*)mod->data);
assembly = mono_domain_try_type_resolve ( mono_domain_get (), fullName->str, NULL);
if (assembly) {
if (assembly->assembly->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image,
info, ignorecase);
}
g_string_free (fullName, TRUE);
return type;
}
void
mono_reflection_free_type_info (MonoTypeNameParse *info)
{
g_list_free (info->modifiers);
g_list_free (info->nested);
if (info->type_arguments) {
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
mono_reflection_free_type_info (subinfo);
/*We free the subinfo since it is allocated by _mono_reflection_parse_type*/
g_free (subinfo);
}
g_ptr_array_free (info->type_arguments, TRUE);
}
}
/*
* mono_reflection_type_from_name:
* @name: type name.
* @image: a metadata context (can be NULL).
*
* Retrieves a MonoType from its @name. If the name is not fully qualified,
* it defaults to get the type from @image or, if @image is NULL or loading
* from it fails, uses corlib.
*
*/
MonoType*
mono_reflection_type_from_name (char *name, MonoImage *image)
{
MonoType *type = NULL;
MonoTypeNameParse info;
char *tmp;
/* Make a copy since parse_type modifies its argument */
tmp = g_strdup (name);
/*g_print ("requested type %s\n", str);*/
if (mono_reflection_parse_type (tmp, &info)) {
type = _mono_reflection_get_type_from_info (&info, image, FALSE);
}
g_free (tmp);
mono_reflection_free_type_info (&info);
return type;
}
/*
* mono_reflection_get_token:
*
* Return the metadata token of OBJ which should be an object
* representing a metadata element.
*/
guint32
mono_reflection_get_token (MonoObject *obj)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
/* Call mono_image_create_token so the object gets added to the tokens hash table */
token = mono_image_create_token (((MonoReflectionTypeBuilder*)fb->typeb)->module->dynamic_image, obj, FALSE, TRUE);
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
token = mc->type_token;
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
MonoMethodInflated *inflated = (MonoMethodInflated *) m->method;
return inflated->declaring->token;
} else {
token = m->method->token;
}
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField*)obj;
if (is_field_on_inst (f->field)) {
MonoDynamicGenericClass *dgclass = (MonoDynamicGenericClass*)f->field->parent->generic_class;
int field_index = f->field - dgclass->fields;
MonoObject *obj;
g_assert (field_index >= 0 && field_index < dgclass->count_fields);
obj = dgclass->field_objects [field_index];
return mono_reflection_get_token (obj);
}
token = mono_class_get_field_token (f->field);
} else if (strcmp (klass->name, "MonoProperty") == 0) {
MonoReflectionProperty *p = (MonoReflectionProperty*)obj;
token = mono_class_get_property_token (p->property);
} else if (strcmp (klass->name, "MonoEvent") == 0) {
MonoReflectionMonoEvent *p = (MonoReflectionMonoEvent*)obj;
token = mono_class_get_event_token (p->event);
} else if (strcmp (klass->name, "ParameterInfo") == 0) {
MonoReflectionParameter *p = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (p->MemberImpl);
g_assert (mono_class_is_reflection_method_or_constructor (member_class));
token = mono_method_get_param_token (((MonoReflectionMethod*)p->MemberImpl)->method, p->PositionImpl);
} else if (strcmp (klass->name, "Module") == 0 || strcmp (klass->name, "MonoModule") == 0) {
MonoReflectionModule *m = (MonoReflectionModule*)obj;
token = m->token;
} else if (strcmp (klass->name, "Assembly") == 0 || strcmp (klass->name, "MonoAssembly") == 0) {
token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1);
} else {
gchar *msg = g_strdup_printf ("MetadataToken is not supported for type '%s.%s'", klass->name_space, klass->name);
MonoException *ex = mono_get_exception_not_implemented (msg);
g_free (msg);
mono_raise_exception (ex);
}
return token;
}
static void*
load_cattr_value (MonoImage *image, MonoType *t, const char *p, const char **end)
{
int slen, type = t->type;
MonoClass *tklass = t->data.klass;
handle_enum:
switch (type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN: {
MonoBoolean *bval = g_malloc (sizeof (MonoBoolean));
*bval = *p;
*end = p + 1;
return bval;
}
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2: {
guint16 *val = g_malloc (sizeof (guint16));
*val = read16 (p);
*end = p + 2;
return val;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_U:
case MONO_TYPE_I:
#endif
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4: {
guint32 *val = g_malloc (sizeof (guint32));
*val = read32 (p);
*end = p + 4;
return val;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_U: /* error out instead? this should probably not happen */
case MONO_TYPE_I:
#endif
case MONO_TYPE_U8:
case MONO_TYPE_I8: {
guint64 *val = g_malloc (sizeof (guint64));
*val = read64 (p);
*end = p + 8;
return val;
}
case MONO_TYPE_R8: {
double *val = g_malloc (sizeof (double));
readr8 (p, val);
*end = p + 8;
return val;
}
case MONO_TYPE_VALUETYPE:
if (t->data.klass->enumtype) {
type = mono_class_enum_basetype (t->data.klass)->type;
goto handle_enum;
} else {
MonoClass *k = t->data.klass;
if (mono_is_corlib_image (k->image) && strcmp (k->name_space, "System") == 0 && strcmp (k->name, "DateTime") == 0){
guint64 *val = g_malloc (sizeof (guint64));
*val = read64 (p);
*end = p + 8;
return val;
}
}
g_error ("generic valutype %s not handled in custom attr value decoding", t->data.klass->name);
break;
case MONO_TYPE_STRING:
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
slen = mono_metadata_decode_value (p, &p);
*end = p + slen;
return mono_string_new_len (mono_domain_get (), p, slen);
case MONO_TYPE_CLASS: {
char *n;
MonoType *t;
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
handle_type:
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_warning ("Cannot load type '%s'", n);
g_free (n);
*end = p + slen;
if (t)
return mono_type_get_object (mono_domain_get (), t);
else
return NULL;
}
case MONO_TYPE_OBJECT: {
char subt = *p++;
MonoObject *obj;
MonoClass *subc = NULL;
void *val;
if (subt == 0x50) {
goto handle_type;
} else if (subt == 0x0E) {
type = MONO_TYPE_STRING;
goto handle_enum;
} else if (subt == 0x1D) {
MonoType simple_type = {{0}};
int etype = *p;
p ++;
if (etype == 0x51)
/* See Partition II, Appendix B3 */
etype = MONO_TYPE_OBJECT;
type = MONO_TYPE_SZARRAY;
simple_type.type = etype;
tklass = mono_class_from_mono_type (&simple_type);
goto handle_enum;
} else if (subt == 0x55) {
char *n;
MonoType *t;
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_error ("Cannot load type '%s'", n);
g_free (n);
p += slen;
subc = mono_class_from_mono_type (t);
} else if (subt >= MONO_TYPE_BOOLEAN && subt <= MONO_TYPE_R8) {
MonoType simple_type = {{0}};
simple_type.type = subt;
subc = mono_class_from_mono_type (&simple_type);
} else {
g_error ("Unknown type 0x%02x for object type encoding in custom attr", subt);
}
val = load_cattr_value (image, &subc->byval_arg, p, end);
obj = mono_object_new (mono_domain_get (), subc);
g_assert (!subc->has_references);
memcpy ((char*)obj + sizeof (MonoObject), val, mono_class_value_size (subc, NULL));
g_free (val);
return obj;
}
case MONO_TYPE_SZARRAY: {
MonoArray *arr;
guint32 i, alen, basetype;
alen = read32 (p);
p += 4;
if (alen == 0xffffffff) {
*end = p;
return NULL;
}
arr = mono_array_new (mono_domain_get(), tklass, alen);
basetype = tklass->byval_arg.type;
if (basetype == MONO_TYPE_VALUETYPE && tklass->enumtype)
basetype = mono_class_enum_basetype (tklass)->type;
switch (basetype)
{
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
for (i = 0; i < alen; i++) {
MonoBoolean val = *p++;
mono_array_set (arr, MonoBoolean, i, val);
}
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
for (i = 0; i < alen; i++) {
guint16 val = read16 (p);
mono_array_set (arr, guint16, i, val);
p += 2;
}
break;
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
for (i = 0; i < alen; i++) {
guint32 val = read32 (p);
mono_array_set (arr, guint32, i, val);
p += 4;
}
break;
case MONO_TYPE_R8:
for (i = 0; i < alen; i++) {
double val;
readr8 (p, &val);
mono_array_set (arr, double, i, val);
p += 8;
}
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
for (i = 0; i < alen; i++) {
guint64 val = read64 (p);
mono_array_set (arr, guint64, i, val);
p += 8;
}
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_STRING:
for (i = 0; i < alen; i++) {
MonoObject *item = load_cattr_value (image, &tklass->byval_arg, p, &p);
mono_array_setref (arr, i, item);
}
break;
default:
g_error ("Type 0x%02x not handled in custom attr array decoding", basetype);
}
*end=p;
return arr;
}
default:
g_error ("Type 0x%02x not handled in custom attr value decoding", type);
}
return NULL;
}
static MonoObject*
create_cattr_typed_arg (MonoType *t, MonoObject *val)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *params [2], *unboxed;
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeTypedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = mono_type_get_object (mono_domain_get (), t);
params [1] = val;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static MonoObject*
create_cattr_named_arg (void *minfo, MonoObject *typedarg)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *unboxed, *params [2];
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeNamedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = minfo;
params [1] = typedarg;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static gboolean
type_is_reference (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_R4:
case MONO_TYPE_VALUETYPE:
return FALSE;
default:
return TRUE;
}
}
static void
free_param_data (MonoMethodSignature *sig, void **params) {
int i;
for (i = 0; i < sig->param_count; ++i) {
if (!type_is_reference (sig->params [i]))
g_free (params [i]);
}
}
/*
* Find the field index in the metadata FieldDef table.
*/
static guint32
find_field_index (MonoClass *klass, MonoClassField *field) {
int i;
for (i = 0; i < klass->field.count; ++i) {
if (field == &klass->fields [i])
return klass->field.first + 1 + i;
}
return 0;
}
/*
* Find the property index in the metadata Property table.
*/
static guint32
find_property_index (MonoClass *klass, MonoProperty *property) {
int i;
for (i = 0; i < klass->ext->property.count; ++i) {
if (property == &klass->ext->properties [i])
return klass->ext->property.first + 1 + i;
}
return 0;
}
/*
* Find the event index in the metadata Event table.
*/
static guint32
find_event_index (MonoClass *klass, MonoEvent *event) {
int i;
for (i = 0; i < klass->ext->event.count; ++i) {
if (event == &klass->ext->events [i])
return klass->ext->event.first + 1 + i;
}
return 0;
}
static MonoObject*
create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len)
{
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
MonoObject *attr;
void *params_buf [32];
void **params;
MonoMethodSignature *sig;
mono_class_init (method->klass);
if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
return NULL;
if (len == 0) {
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, NULL, NULL);
return attr;
}
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return NULL;
/*g_print ("got attr %s\n", method->klass->name);*/
sig = mono_method_signature (method);
if (sig->param_count < 32)
params = params_buf;
else
/* Allocate using GC so it gets GC tracking */
params = mono_gc_alloc_fixed (sig->param_count * sizeof (void*), NULL);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
params [i] = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
}
named = p;
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, params, NULL);
free_param_data (method->signature, params);
num_named = read16 (named);
named += 2;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoClassField *field = mono_class_get_field_from_name (mono_object_class (attr), name);
void *val = load_cattr_value (image, field->type, named, &named);
mono_field_set_value (attr, field, val);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoProperty *prop;
void *pparams [1];
MonoType *prop_type;
prop = mono_class_get_property_from_name (mono_object_class (attr), name);
/* can we have more that 1 arg in a custom attr named property? */
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
pparams [0] = load_cattr_value (image, prop_type, named, &named);
mono_property_set_value (prop, attr, pparams, NULL);
if (!type_is_reference (prop_type))
g_free (pparams [0]);
}
g_free (name);
}
if (params != params_buf)
mono_gc_free_fixed (params);
return attr;
}
/*
* mono_reflection_create_custom_attr_data_args:
*
* Create an array of typed and named arguments from the cattr blob given by DATA.
* TYPED_ARGS and NAMED_ARGS will contain the objects representing the arguments,
* NAMED_ARG_INFO will contain information about the named arguments.
*/
void
mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoArray **typed_args, MonoArray **named_args, CattrNamedArg **named_arg_info)
{
MonoArray *typedargs, *namedargs;
MonoClass *attrklass;
MonoDomain *domain;
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
if (!mono_verifier_verify_cattr_content (image, method, data, len, NULL))
return;
mono_class_init (method->klass);
*typed_args = NULL;
*named_args = NULL;
*named_arg_info = NULL;
domain = mono_domain_get ();
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return;
typedargs = mono_array_new (domain, mono_get_object_class (), mono_method_signature (method)->param_count);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj;
void *val;
val = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
obj = type_is_reference (mono_method_signature (method)->params [i]) ?
val : mono_value_box (domain, mono_class_from_mono_type (mono_method_signature (method)->params [i]), val);
mono_array_setref (typedargs, i, obj);
if (!type_is_reference (mono_method_signature (method)->params [i]))
g_free (val);
}
named = p;
num_named = read16 (named);
namedargs = mono_array_new (domain, mono_get_object_class (), num_named);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoObject *obj;
MonoClassField *field = mono_class_get_field_from_name (attrklass, name);
void *val;
arginfo [j].type = field->type;
arginfo [j].field = field;
val = load_cattr_value (image, field->type, named, &named);
obj = type_is_reference (field->type) ? val : mono_value_box (domain, mono_class_from_mono_type (field->type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoObject *obj;
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name (attrklass, name);
void *val;
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
val = load_cattr_value (image, prop_type, named, &named);
obj = type_is_reference (prop_type) ? val : mono_value_box (domain, mono_class_from_mono_type (prop_type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (prop_type))
g_free (val);
}
g_free (name);
}
*typed_args = typedargs;
*named_args = namedargs;
}
void
mono_reflection_resolve_custom_attribute_data (MonoReflectionMethod *ref_method, MonoReflectionAssembly *assembly, gpointer data, guint32 len, MonoArray **ctor_args, MonoArray **named_args)
{
MonoDomain *domain;
MonoArray *typedargs, *namedargs;
MonoImage *image;
MonoMethod *method;
CattrNamedArg *arginfo;
int i;
*ctor_args = NULL;
*named_args = NULL;
if (len == 0)
return;
image = assembly->assembly->image;
method = ref_method->method;
domain = mono_object_domain (ref_method);
if (!mono_class_init (method->klass))
mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
mono_reflection_create_custom_attr_data_args (image, method, data, len, &typedargs, &namedargs, &arginfo);
if (mono_loader_get_last_error ())
mono_raise_exception (mono_loader_error_prepare_exception (mono_loader_get_last_error ()));
if (!typedargs || !namedargs)
return;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj = mono_array_get (typedargs, MonoObject*, i);
MonoObject *typedarg;
typedarg = create_cattr_typed_arg (mono_method_signature (method)->params [i], obj);
mono_array_setref (typedargs, i, typedarg);
}
for (i = 0; i < mono_array_length (namedargs); ++i) {
MonoObject *obj = mono_array_get (namedargs, MonoObject*, i);
MonoObject *typedarg, *namedarg, *minfo;
if (arginfo [i].prop)
minfo = (MonoObject*)mono_property_get_object (domain, NULL, arginfo [i].prop);
else
minfo = (MonoObject*)mono_field_get_object (domain, NULL, arginfo [i].field);
typedarg = create_cattr_typed_arg (arginfo [i].type, obj);
namedarg = create_cattr_named_arg (minfo, typedarg);
mono_array_setref (namedargs, i, namedarg);
}
*ctor_args = typedargs;
*named_args = namedargs;
}
static MonoObject*
create_custom_attr_data (MonoImage *image, MonoCustomAttrEntry *cattr)
{
static MonoMethod *ctor;
MonoDomain *domain;
MonoObject *attr;
void *params [4];
g_assert (image->assembly);
if (!ctor)
ctor = mono_class_get_method_from_name (mono_defaults.customattribute_data_class, ".ctor", 4);
domain = mono_domain_get ();
attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
params [0] = mono_method_get_object (domain, cattr->ctor, NULL);
params [1] = mono_assembly_get_object (domain, image->assembly);
params [2] = (gpointer)&cattr->data;
params [3] = &cattr->data_size;
mono_runtime_invoke (ctor, attr, params, NULL);
return attr;
}
MonoArray*
mono_custom_attrs_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
if (!cinfo->attrs [i].ctor)
/* The cattr type is not finished yet */
/* We should include the type name but cinfo doesn't contain it */
mono_raise_exception (mono_get_exception_type_load (NULL, NULL));
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, i, attr);
}
return result;
}
static MonoArray*
mono_custom_attrs_construct_by_type (MonoCustomAttrInfo *cinfo, MonoClass *attr_klass)
{
MonoArray *result;
MonoObject *attr;
int i, n;
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass))
n ++;
}
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, n);
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass)) {
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, n, attr);
n ++;
}
}
return result;
}
static MonoArray*
mono_custom_attrs_data_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
attr = create_custom_attr_data (cinfo->image, &cinfo->attrs [i]);
mono_array_setref (result, i, attr);
}
return result;
}
/**
* mono_custom_attrs_from_index:
*
* Returns: NULL if no attributes are found or if a loading error occurs.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
{
guint32 mtoken, i, len;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
MonoCustomAttrInfo *ainfo;
GList *tmp, *list = NULL;
const char *data;
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return NULL;
i --;
while (i < ca->rows) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx)
break;
list = g_list_prepend (list, GUINT_TO_POINTER (i));
++i;
}
len = g_list_length (list);
if (!len)
return NULL;
ainfo = g_malloc0 (MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * len);
ainfo->num_attrs = len;
ainfo->image = image;
for (i = 0, tmp = list; i < len; ++i, tmp = tmp->next) {
mono_metadata_decode_row (ca, GPOINTER_TO_UINT (tmp->data), cols, MONO_CUSTOM_ATTR_SIZE);
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_error ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
break;
}
ainfo->attrs [i].ctor = mono_get_method (image, mtoken, NULL);
if (!ainfo->attrs [i].ctor) {
g_warning ("Can't find custom attr constructor image: %s mtoken: 0x%08x", image->name, mtoken);
g_list_free (list);
g_free (ainfo);
return NULL;
}
if (!mono_verifier_verify_cattr_blob (image, cols [MONO_CUSTOM_ATTR_VALUE], NULL)) {
/*FIXME raising an exception here doesn't make any sense*/
g_warning ("Invalid custom attribute blob on image %s for index %x", image->name, idx);
g_list_free (list);
g_free (ainfo);
return NULL;
}
data = mono_metadata_blob_heap (image, cols [MONO_CUSTOM_ATTR_VALUE]);
ainfo->attrs [i].data_size = mono_metadata_decode_value (data, &data);
ainfo->attrs [i].data = (guchar*)data;
}
g_list_free (list);
return ainfo;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_method (MonoMethod *method)
{
guint32 idx;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->dynamic || method->klass->image->dynamic)
return lookup_custom_attr (method->klass->image, method);
if (!method->token)
/* Synthetic methods */
return NULL;
idx = mono_method_get_index (method);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_METHODDEF;
return mono_custom_attrs_from_index (method->klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_class (MonoClass *klass)
{
guint32 idx;
if (klass->generic_class)
klass = klass->generic_class->container_class;
if (klass->image->dynamic)
return lookup_custom_attr (klass->image, klass);
if (klass->byval_arg.type == MONO_TYPE_VAR || klass->byval_arg.type == MONO_TYPE_MVAR) {
idx = mono_metadata_token_index (klass->sizes.generic_param_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_GENERICPAR;
} else {
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_TYPEDEF;
}
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly (MonoAssembly *assembly)
{
guint32 idx;
if (assembly->image->dynamic)
return lookup_custom_attr (assembly->image, assembly);
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
return mono_custom_attrs_from_index (assembly->image, idx);
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_module (MonoImage *image)
{
guint32 idx;
if (image->dynamic)
return lookup_custom_attr (image, image);
idx = 1; /* there is only one module */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_MODULE;
return mono_custom_attrs_from_index (image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_property (MonoClass *klass, MonoProperty *property)
{
guint32 idx;
if (klass->image->dynamic) {
property = mono_metadata_get_corresponding_property_from_generic_type_definition (property);
return lookup_custom_attr (klass->image, property);
}
idx = find_property_index (klass, property);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PROPERTY;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_event (MonoClass *klass, MonoEvent *event)
{
guint32 idx;
if (klass->image->dynamic) {
event = mono_metadata_get_corresponding_event_from_generic_type_definition (event);
return lookup_custom_attr (klass->image, event);
}
idx = find_event_index (klass, event);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_EVENT;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_field (MonoClass *klass, MonoClassField *field)
{
guint32 idx;
if (klass->image->dynamic) {
field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
return lookup_custom_attr (klass->image, field);
}
idx = find_field_index (klass, field);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_FIELDDEF;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_param (MonoMethod *method, guint32 param)
{
MonoTableInfo *ca;
guint32 i, idx, method_index;
guint32 param_list, param_last, param_pos, found;
MonoImage *image;
MonoReflectionMethodAux *aux;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->klass->image->dynamic) {
MonoCustomAttrInfo *res, *ainfo;
int size;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (!aux || !aux->param_cattr)
return NULL;
/* Need to copy since it will be freed later */
ainfo = aux->param_cattr [param];
if (!ainfo)
return NULL;
size = MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * ainfo->num_attrs;
res = g_malloc0 (size);
memcpy (res, ainfo, size);
return res;
}
image = method->klass->image;
method_index = mono_method_get_index (method);
if (!method_index)
return NULL;
ca = &image->tables [MONO_TABLE_METHOD];
param_list = mono_metadata_decode_row_col (ca, method_index - 1, MONO_METHOD_PARAMLIST);
if (method_index == ca->rows) {
ca = &image->tables [MONO_TABLE_PARAM];
param_last = ca->rows + 1;
} else {
param_last = mono_metadata_decode_row_col (ca, method_index, MONO_METHOD_PARAMLIST);
ca = &image->tables [MONO_TABLE_PARAM];
}
found = FALSE;
for (i = param_list; i < param_last; ++i) {
param_pos = mono_metadata_decode_row_col (ca, i - 1, MONO_PARAM_SEQUENCE);
if (param_pos == param) {
found = TRUE;
break;
}
}
if (!found)
return NULL;
idx = i;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PARAMDEF;
return mono_custom_attrs_from_index (image, idx);
}
gboolean
mono_custom_attrs_has_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i;
MonoClass *klass;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass) || (MONO_CLASS_IS_INTERFACE (attr_klass) && mono_class_is_assignable_from (attr_klass, klass)))
return TRUE;
}
return FALSE;
}
MonoObject*
mono_custom_attrs_get_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i, attr_index;
MonoClass *klass;
MonoArray *attrs;
attr_index = -1;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass)) {
attr_index = i;
break;
}
}
if (attr_index == -1)
return NULL;
attrs = mono_custom_attrs_construct (ainfo);
if (attrs)
return mono_array_get (attrs, MonoObject*, attr_index);
else
return NULL;
}
/*
* mono_reflection_get_custom_attrs_info:
* @obj: a reflection object handle
*
* Return the custom attribute info for attributes defined for the
* reflection handle @obj. The objects.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info (MonoObject *obj)
{
MonoClass *klass;
MonoCustomAttrInfo *cinfo = NULL;
klass = obj->vtable->klass;
if (klass == mono_defaults.monotype_class) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
klass = mono_class_from_mono_type (type);
/*We cannot mono_class_init the class from which we'll load the custom attributes since this must work with broken types.*/
cinfo = mono_custom_attrs_from_class (klass);
} else if (strcmp ("Assembly", klass->name) == 0 || strcmp ("MonoAssembly", klass->name) == 0) {
MonoReflectionAssembly *rassembly = (MonoReflectionAssembly*)obj;
cinfo = mono_custom_attrs_from_assembly (rassembly->assembly);
} else if (strcmp ("Module", klass->name) == 0 || strcmp ("MonoModule", klass->name) == 0) {
MonoReflectionModule *module = (MonoReflectionModule*)obj;
cinfo = mono_custom_attrs_from_module (module->image);
} else if (strcmp ("MonoProperty", klass->name) == 0) {
MonoReflectionProperty *rprop = (MonoReflectionProperty*)obj;
cinfo = mono_custom_attrs_from_property (rprop->property->parent, rprop->property);
} else if (strcmp ("MonoEvent", klass->name) == 0) {
MonoReflectionMonoEvent *revent = (MonoReflectionMonoEvent*)obj;
cinfo = mono_custom_attrs_from_event (revent->event->parent, revent->event);
} else if (strcmp ("MonoField", klass->name) == 0) {
MonoReflectionField *rfield = (MonoReflectionField*)obj;
cinfo = mono_custom_attrs_from_field (rfield->field->parent, rfield->field);
} else if ((strcmp ("MonoMethod", klass->name) == 0) || (strcmp ("MonoCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if ((strcmp ("MonoGenericMethod", klass->name) == 0) || (strcmp ("MonoGenericCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if (strcmp ("ParameterInfo", klass->name) == 0) {
MonoReflectionParameter *param = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (param->MemberImpl);
if (mono_class_is_reflection_method_or_constructor (member_class)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
cinfo = mono_custom_attrs_from_param (rmethod->method, param->PositionImpl + 1);
} else if (is_sr_mono_property (member_class)) {
MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
MonoMethod *method;
if (!(method = prop->property->get))
method = prop->property->set;
g_assert (method);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
}
#ifndef DISABLE_REFLECTION_EMIT
else if (is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
MonoMethod *method = mono_reflection_method_on_tb_inst_get_handle ((MonoReflectionMethodOnTypeBuilderInst*)param->MemberImpl);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
} else if (is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)param->MemberImpl;
MonoMethod *method = NULL;
if (is_sre_ctor_builder (mono_object_class (c->cb)))
method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
else if (is_sr_mono_cmethod (mono_object_class (c->cb)))
method = ((MonoReflectionMethod *)c->cb)->method;
else
g_error ("mono_reflection_get_custom_attrs_info:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (member_class));
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
}
#endif
else {
char *type_name = mono_type_get_full_name (member_class);
char *msg = g_strdup_printf ("Custom attributes on a ParamInfo with member %s are not supported", type_name);
MonoException *ex = mono_get_exception_not_supported (msg);
g_free (type_name);
g_free (msg);
mono_raise_exception (ex);
}
} else if (strcmp ("AssemblyBuilder", klass->name) == 0) {
MonoReflectionAssemblyBuilder *assemblyb = (MonoReflectionAssemblyBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, assemblyb->assembly.assembly->image, assemblyb->cattrs);
} else if (strcmp ("TypeBuilder", klass->name) == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &tb->module->dynamic_image->image, tb->cattrs);
} else if (strcmp ("ModuleBuilder", klass->name) == 0) {
MonoReflectionModuleBuilder *mb = (MonoReflectionModuleBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &mb->dynamic_image->image, mb->cattrs);
} else if (strcmp ("ConstructorBuilder", klass->name) == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, cb->mhandle->klass->image, cb->cattrs);
} else if (strcmp ("MethodBuilder", klass->name) == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, mb->mhandle->klass->image, mb->cattrs);
} else if (strcmp ("FieldBuilder", klass->name) == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &((MonoReflectionTypeBuilder*)fb->typeb)->module->dynamic_image->image, fb->cattrs);
} else if (strcmp ("MonoGenericClass", klass->name) == 0) {
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)obj;
cinfo = mono_reflection_get_custom_attrs_info ((MonoObject*)gclass->generic_type);
} else { /* handle other types here... */
g_error ("get custom attrs not yet supported for %s", klass->name);
}
return cinfo;
}
/*
* mono_reflection_get_custom_attrs_by_type:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. If @attr_klass is non-NULL, only custom attributes
* of that type are returned. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs_by_type (MonoObject *obj, MonoClass *attr_klass)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
if (attr_klass)
result = mono_custom_attrs_construct_by_type (cinfo, attr_klass);
else
result = mono_custom_attrs_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
if (mono_loader_get_last_error ())
return NULL;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, 0);
}
return result;
}
/*
* mono_reflection_get_custom_attrs:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs (MonoObject *obj)
{
return mono_reflection_get_custom_attrs_by_type (obj, NULL);
}
/*
* mono_reflection_get_custom_attrs_data:
* @obj: a reflection obj handle
*
* Returns an array of System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArray*
mono_reflection_get_custom_attrs_data (MonoObject *obj)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
result = mono_custom_attrs_data_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, 0);
return result;
}
static MonoReflectionType*
mono_reflection_type_get_underlying_system_type (MonoReflectionType* t)
{
static MonoMethod *method_get_underlying_system_type = NULL;
MonoMethod *usertype_method;
if (!method_get_underlying_system_type)
method_get_underlying_system_type = mono_class_get_method_from_name (mono_defaults.systemtype_class, "get_UnderlyingSystemType", 0);
usertype_method = mono_object_get_virtual_method ((MonoObject *) t, method_get_underlying_system_type);
return (MonoReflectionType *) mono_runtime_invoke (usertype_method, t, NULL, NULL);
}
static gboolean
is_corlib_type (MonoClass *class)
{
return class->image == mono_defaults.corlib;
}
#define check_corlib_type_cached(_class, _namespace, _name) do { \
static MonoClass *cached_class; \
if (cached_class) \
return cached_class == _class; \
if (is_corlib_type (_class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
cached_class = _class; \
return TRUE; \
} \
return FALSE; \
} while (0) \
#ifndef DISABLE_REFLECTION_EMIT
static gboolean
is_sre_array (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ArrayType");
}
static gboolean
is_sre_byref (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ByRefType");
}
static gboolean
is_sre_pointer (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "PointerType");
}
static gboolean
is_sre_generic_instance (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericClass");
}
static gboolean
is_sre_type_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "TypeBuilder");
}
static gboolean
is_sre_method_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodBuilder");
}
static gboolean
is_sre_ctor_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorBuilder");
}
static gboolean
is_sre_field_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "FieldBuilder");
}
static gboolean
is_sre_method_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodOnTypeBuilderInst");
}
static gboolean
is_sre_ctor_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorOnTypeBuilderInst");
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
MonoClass *class;
if (!ref)
return NULL;
if (ref->type)
return ref->type;
if (is_usertype (ref)) {
ref = mono_reflection_type_get_underlying_system_type (ref);
if (ref == NULL || is_usertype (ref))
return NULL;
if (ref->type)
return ref->type;
}
class = mono_object_class (ref);
if (is_sre_array (class)) {
MonoType *res;
MonoReflectionArrayType *sre_array = (MonoReflectionArrayType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_array->element_type);
g_assert (base);
if (sre_array->rank == 0) //single dimentional array
res = &mono_array_class_get (mono_class_from_mono_type (base), 1)->byval_arg;
else
res = &mono_bounded_array_class_get (mono_class_from_mono_type (base), sre_array->rank, TRUE)->byval_arg;
sre_array->type.type = res;
return res;
} else if (is_sre_byref (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_byref = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_byref->element_type);
g_assert (base);
res = &mono_class_from_mono_type (base)->this_arg;
sre_byref->type.type = res;
return res;
} else if (is_sre_pointer (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_pointer = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_pointer->element_type);
g_assert (base);
res = &mono_ptr_class_get (base)->byval_arg;
sre_pointer->type.type = res;
return res;
} else if (is_sre_generic_instance (class)) {
MonoType *res, **types;
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)ref;
int i, count;
count = mono_array_length (gclass->type_arguments);
types = g_new0 (MonoType*, count);
for (i = 0; i < count; ++i) {
MonoReflectionType *t = mono_array_get (gclass->type_arguments, gpointer, i);
types [i] = mono_reflection_type_get_handle (t);
if (!types[i]) {
g_free (types);
return NULL;
}
}
res = mono_reflection_bind_generic_parameters (gclass->generic_type, count, types);
g_free (types);
g_assert (res);
gclass->type.type = res;
return res;
}
g_error ("Cannot handle corlib user type %s", mono_type_full_name (&mono_object_class(ref)->byval_arg));
return NULL;
}
void
mono_reflection_create_unmanaged_type (MonoReflectionType *type)
{
mono_reflection_type_get_handle (type);
}
void
mono_reflection_register_with_runtime (MonoReflectionType *type)
{
MonoType *res = mono_reflection_type_get_handle (type);
MonoDomain *domain = mono_object_domain ((MonoObject*)type);
MonoClass *class;
if (!res)
mono_raise_exception (mono_get_exception_argument (NULL, "Invalid generic instantiation, one or more arguments are not proper user types"));
class = mono_class_from_mono_type (res);
mono_loader_lock (); /*same locking as mono_type_get_object*/
mono_domain_lock (domain);
if (!class->image->dynamic) {
mono_class_setup_supertypes (class);
} else {
if (!domain->type_hash)
domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mymono_metadata_type_hash,
(GCompareFunc)mymono_metadata_type_equal, MONO_HASH_VALUE_GC);
mono_g_hash_table_insert (domain->type_hash, res, type);
}
mono_domain_unlock (domain);
mono_loader_unlock ();
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
parameters_to_signature (MonoImage *image, MonoArray *parameters) {
MonoMethodSignature *sig;
int count, i;
count = parameters? mono_array_length (parameters): 0;
sig = image_g_malloc0 (image, MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * count);
sig->param_count = count;
sig->sentinelpos = -1; /* FIXME */
for (i = 0; i < count; ++i)
sig->params [i] = mono_type_array_get_and_resolve (parameters, i);
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
ctor_builder_to_signature (MonoImage *image, MonoReflectionCtorBuilder *ctor) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, ctor->parameters);
sig->hasthis = ctor->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = &mono_defaults.void_class->byval_arg;
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
method_builder_to_signature (MonoImage *image, MonoReflectionMethodBuilder *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle ((MonoReflectionType*)method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = method->generic_params ? mono_array_length (method->generic_params) : 0;
return sig;
}
static MonoMethodSignature*
dynamic_method_to_signature (MonoReflectionDynamicMethod *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (NULL, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle (method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = 0;
return sig;
}
static void
get_prop_name_and_type (MonoObject *prop, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (prop);
if (strcmp (klass->name, "PropertyBuilder") == 0) {
MonoReflectionPropertyBuilder *pb = (MonoReflectionPropertyBuilder *)prop;
*name = mono_string_to_utf8 (pb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)pb->type);
} else {
MonoReflectionProperty *p = (MonoReflectionProperty *)prop;
*name = g_strdup (p->property->name);
if (p->property->get)
*type = mono_method_signature (p->property->get)->ret;
else
*type = mono_method_signature (p->property->set)->params [mono_method_signature (p->property->set)->param_count - 1];
}
}
static void
get_field_name_and_type (MonoObject *field, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (field);
if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)field;
*name = mono_string_to_utf8 (fb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
} else {
MonoReflectionField *f = (MonoReflectionField *)field;
*name = g_strdup (mono_field_get_name (f->field));
*type = f->field->type;
}
}
#else /* DISABLE_REFLECTION_EMIT */
void
mono_reflection_register_with_runtime (MonoReflectionType *type)
{
/* This is empty */
}
static gboolean
is_sre_type_builder (MonoClass *class)
{
return FALSE;
}
static gboolean
is_sre_generic_instance (MonoClass *class)
{
return FALSE;
}
#endif /* !DISABLE_REFLECTION_EMIT */
static gboolean
is_sr_mono_field (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoField");
}
static gboolean
is_sr_mono_property (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoProperty");
}
static gboolean
is_sr_mono_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoMethod");
}
static gboolean
is_sr_mono_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoCMethod");
}
static gboolean
is_sr_mono_generic_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericMethod");
}
static gboolean
is_sr_mono_generic_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericCMethod");
}
gboolean
mono_class_is_reflection_method_or_constructor (MonoClass *class)
{
return is_sr_mono_method (class) || is_sr_mono_cmethod (class) || is_sr_mono_generic_method (class) || is_sr_mono_generic_cmethod (class);
}
static gboolean
is_usertype (MonoReflectionType *ref)
{
MonoClass *class = mono_object_class (ref);
return class->image != mono_defaults.corlib || strcmp ("TypeDelegator", class->name) == 0;
}
static MonoReflectionType*
mono_reflection_type_resolve_user_types (MonoReflectionType *type)
{
if (!type || type->type)
return type;
if (is_usertype (type)) {
type = mono_reflection_type_get_underlying_system_type (type);
if (is_usertype (type))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported22"));
}
return type;
}
/*
* Encode a value in a custom attribute stream of bytes.
* The value to encode is either supplied as an object in argument val
* (valuetypes are boxed), or as a pointer to the data in the
* argument argval.
* @type represents the type of the value
* @buffer is the start of the buffer
* @p the current position in the buffer
* @buflen contains the size of the buffer and is used to return the new buffer size
* if this needs to be realloced.
* @retbuffer and @retp return the start and the position of the buffer
*/
static void
encode_cattr_value (MonoAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, MonoObject *arg, char *argval)
{
MonoTypeEnum simple_type;
if ((p-buffer) + 10 >= *buflen) {
char *newbuf;
*buflen *= 2;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
if (!argval)
argval = ((char*)arg + sizeof (MonoObject));
simple_type = type->type;
handle_enum:
switch (simple_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
*p++ = *argval;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
swap_with_size (p, argval, 2, 1);
p += 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
swap_with_size (p, argval, 4, 1);
p += 4;
break;
case MONO_TYPE_R8:
#if defined(ARM_FPU_FPA) && G_BYTE_ORDER == G_LITTLE_ENDIAN
p [0] = argval [4];
p [1] = argval [5];
p [2] = argval [6];
p [3] = argval [7];
p [4] = argval [0];
p [5] = argval [1];
p [6] = argval [2];
p [7] = argval [3];
#else
swap_with_size (p, argval, 8, 1);
#endif
p += 8;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
swap_with_size (p, argval, 8, 1);
p += 8;
break;
case MONO_TYPE_VALUETYPE:
if (type->data.klass->enumtype) {
simple_type = mono_class_enum_basetype (type->data.klass)->type;
goto handle_enum;
} else {
g_warning ("generic valutype %s not handled in custom attr value decoding", type->data.klass->name);
}
break;
case MONO_TYPE_STRING: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
str = mono_string_to_utf8 ((MonoString*)arg);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_CLASS: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
handle_type:
str = type_get_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)arg), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_SZARRAY: {
int len, i;
MonoClass *eclass, *arg_eclass;
if (!arg) {
*p++ = 0xff; *p++ = 0xff; *p++ = 0xff; *p++ = 0xff;
break;
}
len = mono_array_length ((MonoArray*)arg);
*p++ = len & 0xff;
*p++ = (len >> 8) & 0xff;
*p++ = (len >> 16) & 0xff;
*p++ = (len >> 24) & 0xff;
*retp = p;
*retbuffer = buffer;
eclass = type->data.klass;
arg_eclass = mono_object_class (arg)->element_class;
if (!eclass) {
/* Happens when we are called from the MONO_TYPE_OBJECT case below */
eclass = mono_defaults.object_class;
}
if (eclass == mono_defaults.object_class && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (arg_eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &arg_eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else if (eclass->valuetype && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else {
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, mono_array_get ((MonoArray*)arg, MonoObject*, i), NULL);
}
}
break;
}
case MONO_TYPE_OBJECT: {
MonoClass *klass;
char *str;
guint32 slen;
/*
* The parameter type is 'object' but the type of the actual
* argument is not. So we have to add type information to the blob
* too. This is completely undocumented in the spec.
*/
if (arg == NULL) {
*p++ = MONO_TYPE_STRING; // It's same hack as MS uses
*p++ = 0xFF;
break;
}
klass = mono_object_class (arg);
if (mono_object_isinst (arg, mono_defaults.systemtype_class)) {
*p++ = 0x50;
goto handle_type;
} else if (klass->enumtype) {
*p++ = 0x55;
} else if (klass == mono_defaults.string_class) {
simple_type = MONO_TYPE_STRING;
*p++ = 0x0E;
goto handle_enum;
} else if (klass->rank == 1) {
*p++ = 0x1D;
if (klass->element_class->byval_arg.type == MONO_TYPE_OBJECT)
/* See Partition II, Appendix B3 */
*p++ = 0x51;
else
*p++ = klass->element_class->byval_arg.type;
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &klass->byval_arg, arg, NULL);
break;
} else if (klass->byval_arg.type >= MONO_TYPE_BOOLEAN && klass->byval_arg.type <= MONO_TYPE_R8) {
*p++ = simple_type = klass->byval_arg.type;
goto handle_enum;
} else {
g_error ("unhandled type in custom attr");
}
str = type_get_qualified_name (mono_class_get_type(klass), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
simple_type = mono_class_enum_basetype (klass)->type;
goto handle_enum;
}
default:
g_error ("type 0x%02x not yet supported in custom attr encoder", simple_type);
}
*retp = p;
*retbuffer = buffer;
}
static void
encode_field_or_prop_type (MonoType *type, char *p, char **retp)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
int slen = strlen (str);
*p++ = 0x55;
/*
* This seems to be optional...
* *p++ = 0x80;
*/
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
} else if (type->type == MONO_TYPE_OBJECT) {
*p++ = 0x51;
} else if (type->type == MONO_TYPE_CLASS) {
/* it should be a type: encode_cattr_value () has the check */
*p++ = 0x50;
} else {
mono_metadata_encode_value (type->type, p, &p);
if (type->type == MONO_TYPE_SZARRAY)
/* See the examples in Partition VI, Annex B */
encode_field_or_prop_type (&type->data.klass->byval_arg, p, &p);
}
*retp = p;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
encode_named_val (MonoReflectionAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, char *name, MonoObject *value)
{
int len;
/* Preallocate a large enough buffer */
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
len = strlen (str);
g_free (str);
} else if (type->type == MONO_TYPE_SZARRAY && type->data.klass->enumtype) {
char *str = type_get_qualified_name (&type->data.klass->byval_arg, NULL);
len = strlen (str);
g_free (str);
} else {
len = 0;
}
len += strlen (name);
if ((p-buffer) + 20 + len >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += len;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
encode_field_or_prop_type (type, p, &p);
len = strlen (name);
mono_metadata_encode_value (len, p, &p);
memcpy (p, name, len);
p += len;
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, buflen, type, value, NULL);
*retp = p;
*retbuffer = buffer;
}
/*
* mono_reflection_get_custom_attrs_blob:
* @ctor: custom attribute constructor
* @ctorArgs: arguments o the constructor
* @properties:
* @propValues:
* @fields:
* @fieldValues:
*
* Creates the blob of data that needs to be saved in the metadata and that represents
* the custom attributed described by @ctor, @ctorArgs etc.
* Returns: a Byte array representing the blob of data.
*/
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
MonoArray *result;
MonoMethodSignature *sig;
MonoObject *arg;
char *buffer, *p;
guint32 buflen, i;
MONO_ARCH_SAVE_REGS;
if (strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
/* sig is freed later so allocate it in the heap */
sig = ctor_builder_to_signature (NULL, (MonoReflectionCtorBuilder*)ctor);
} else {
sig = mono_method_signature (((MonoReflectionMethod*)ctor)->method);
}
g_assert (mono_array_length (ctorArgs) == sig->param_count);
buflen = 256;
p = buffer = g_malloc (buflen);
/* write the prolog */
*p++ = 1;
*p++ = 0;
for (i = 0; i < sig->param_count; ++i) {
arg = mono_array_get (ctorArgs, MonoObject*, i);
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, &buflen, sig->params [i], arg, NULL);
}
i = 0;
if (properties)
i += mono_array_length (properties);
if (fields)
i += mono_array_length (fields);
*p++ = i & 0xff;
*p++ = (i >> 8) & 0xff;
if (properties) {
MonoObject *prop;
for (i = 0; i < mono_array_length (properties); ++i) {
MonoType *ptype;
char *pname;
prop = mono_array_get (properties, gpointer, i);
get_prop_name_and_type (prop, &pname, &ptype);
*p++ = 0x54; /* PROPERTY signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ptype, pname, (MonoObject*)mono_array_get (propValues, gpointer, i));
g_free (pname);
}
}
if (fields) {
MonoObject *field;
for (i = 0; i < mono_array_length (fields); ++i) {
MonoType *ftype;
char *fname;
field = mono_array_get (fields, gpointer, i);
get_field_name_and_type (field, &fname, &ftype);
*p++ = 0x53; /* FIELD signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ftype, fname, (MonoObject*)mono_array_get (fieldValues, gpointer, i));
g_free (fname);
}
}
g_assert (p - buffer <= buflen);
buflen = p - buffer;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
p = mono_array_addr (result, char, 0);
memcpy (p, buffer, buflen);
g_free (buffer);
if (strcmp (ctor->vtable->klass->name, "MonoCMethod"))
g_free (sig);
return result;
}
/*
* mono_reflection_setup_internal_class:
* @tb: a TypeBuilder object
*
* Creates a MonoClass that represents the TypeBuilder.
* This is a trick that lets us simplify a lot of reflection code
* (and will allow us to support Build and Run assemblies easier).
*/
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass, *parent;
MONO_ARCH_SAVE_REGS;
RESOLVE_TYPE (tb->parent);
mono_loader_lock ();
if (tb->parent) {
/* check so we can compile corlib correctly */
if (strcmp (mono_object_class (tb->parent)->name, "TypeBuilder") == 0) {
/* mono_class_setup_mono_type () guaranteess type->data.klass is valid */
parent = mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent)->data.klass;
} else {
parent = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
}
} else {
parent = NULL;
}
/* the type has already being created: it means we just have to change the parent */
if (tb->type.type) {
klass = mono_class_from_mono_type (tb->type.type);
klass->parent = NULL;
/* fool mono_class_setup_parent */
klass->supertypes = NULL;
mono_class_setup_parent (klass, parent);
mono_class_setup_mono_type (klass);
mono_loader_unlock ();
return;
}
klass = mono_image_alloc0 (&tb->module->dynamic_image->image, sizeof (MonoClass));
klass->image = &tb->module->dynamic_image->image;
klass->inited = 1; /* we lie to the runtime */
klass->name = mono_string_to_utf8_image (klass->image, tb->name, &error);
if (!mono_error_ok (&error))
goto failure;
klass->name_space = mono_string_to_utf8_image (klass->image, tb->nspace, &error);
if (!mono_error_ok (&error))
goto failure;
klass->type_token = MONO_TOKEN_TYPE_DEF | tb->table_idx;
klass->flags = tb->attrs;
mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
klass->element_class = klass;
if (mono_class_get_ref_info (klass) == NULL) {
mono_class_set_ref_info (klass, tb);
/* Put into cache so mono_class_get () will find it.
Skip nested types as those should not be available on the global scope. */
if (!tb->nesting_type) {
mono_image_add_to_name_cache (klass->image, klass->name_space, klass->name, tb->table_idx);
} else {
klass->image->reflection_info_unregister_classes =
g_slist_prepend (klass->image->reflection_info_unregister_classes, klass);
}
} else {
g_assert (mono_class_get_ref_info (klass) == tb);
}
mono_g_hash_table_insert (tb->module->dynamic_image->tokens,
GUINT_TO_POINTER (MONO_TOKEN_TYPE_DEF | tb->table_idx), tb);
if (parent != NULL) {
mono_class_setup_parent (klass, parent);
} else if (strcmp (klass->name, "Object") == 0 && strcmp (klass->name_space, "System") == 0) {
const char *old_n = klass->name;
/* trick to get relative numbering right when compiling corlib */
klass->name = "BuildingObject";
mono_class_setup_parent (klass, mono_defaults.object_class);
klass->name = old_n;
}
if ((!strcmp (klass->name, "ValueType") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Object") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Enum") && !strcmp (klass->name_space, "System"))) {
klass->instance_size = sizeof (MonoObject);
klass->size_inited = 1;
mono_class_setup_vtable_general (klass, NULL, 0);
}
mono_class_setup_mono_type (klass);
mono_class_setup_supertypes (klass);
/*
* FIXME: handle interfaces.
*/
tb->type.type = &klass->byval_arg;
if (tb->nesting_type) {
g_assert (tb->nesting_type->type);
klass->nested_in = mono_class_from_mono_type (mono_reflection_type_get_handle (tb->nesting_type));
}
/*g_print ("setup %s as %s (%p)\n", klass->name, ((MonoObject*)tb)->vtable->klass->name, tb);*/
mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
mono_loader_unlock ();
return;
failure:
mono_loader_unlock ();
mono_error_raise_exception (&error);
}
/*
* mono_reflection_setup_generic_class:
* @tb: a TypeBuilder object
*
* Setup the generic class before adding the first generic parameter.
*/
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
}
/*
* mono_reflection_create_generic_class:
* @tb: a TypeBuilder object
*
* Creates the generic class after all generic parameters have been added.
*/
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
int count, i;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
count = tb->generic_params ? mono_array_length (tb->generic_params) : 0;
if (klass->generic_container || (count == 0))
return;
g_assert (tb->generic_container && (tb->generic_container->owner.klass == klass));
klass->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
klass->generic_container->owner.klass = klass;
klass->generic_container->type_argc = count;
klass->generic_container->type_params = mono_image_alloc0 (klass->image, sizeof (MonoGenericParamFull) * count);
klass->is_generic = 1;
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam = mono_array_get (tb->generic_params, gpointer, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gparam)->data.generic_param;
klass->generic_container->type_params [i] = *param;
/*Make sure we are a diferent type instance */
klass->generic_container->type_params [i].param.owner = klass->generic_container;
klass->generic_container->type_params [i].info.pklass = NULL;
klass->generic_container->type_params [i].info.flags = gparam->attrs;
g_assert (klass->generic_container->type_params [i].param.owner);
}
klass->generic_container->context.class_inst = mono_get_shared_generic_inst (klass->generic_container);
}
/*
* mono_reflection_create_internal_class:
* @tb: a TypeBuilder object
*
* Actually create the MonoClass that is associated with the TypeBuilder.
*/
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
mono_loader_lock ();
if (klass->enumtype && mono_class_enum_basetype (klass) == NULL) {
MonoReflectionFieldBuilder *fb;
MonoClass *ec;
MonoType *enum_basetype;
g_assert (tb->fields != NULL);
g_assert (mono_array_length (tb->fields) >= 1);
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, 0);
if (!mono_type_is_valid_enum_basetype (mono_reflection_type_get_handle ((MonoReflectionType*)fb->type))) {
mono_loader_unlock ();
return;
}
enum_basetype = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
klass->element_class = mono_class_from_mono_type (enum_basetype);
if (!klass->element_class)
klass->element_class = mono_class_from_mono_type (enum_basetype);
/*
* get the element_class from the current corlib.
*/
ec = default_class_from_mono_type (enum_basetype);
klass->instance_size = ec->instance_size;
klass->size_inited = 1;
/*
* this is almost safe to do with enums and it's needed to be able
* to create objects of the enum type (for use in SetConstant).
*/
/* FIXME: Does this mean enums can't have method overrides ? */
mono_class_setup_vtable_general (klass, NULL, 0);
}
mono_loader_unlock ();
}
static MonoMarshalSpec*
mono_marshal_spec_from_builder (MonoImage *image, MonoAssembly *assembly,
MonoReflectionMarshal *minfo)
{
MonoMarshalSpec *res;
res = image_g_new0 (image, MonoMarshalSpec, 1);
res->native = minfo->type;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
res->data.array_data.elem_type = minfo->eltype;
if (minfo->has_size) {
res->data.array_data.param_num = minfo->param_num;
res->data.array_data.num_elem = minfo->count;
res->data.array_data.elem_mult = minfo->param_num == -1 ? 0 : 1;
}
else {
res->data.array_data.param_num = -1;
res->data.array_data.num_elem = -1;
res->data.array_data.elem_mult = -1;
}
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
res->data.array_data.num_elem = minfo->count;
break;
case MONO_NATIVE_CUSTOM:
if (minfo->marshaltyperef)
res->data.custom_data.custom_name =
type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
if (minfo->mcookie)
res->data.custom_data.cookie = mono_string_to_utf8 (minfo->mcookie);
break;
default:
break;
}
return res;
}
#endif /* !DISABLE_REFLECTION_EMIT */
MonoReflectionMarshal*
mono_reflection_marshal_from_marshal_spec (MonoDomain *domain, MonoClass *klass,
MonoMarshalSpec *spec)
{
static MonoClass *System_Reflection_Emit_UnmanagedMarshalClass;
MonoReflectionMarshal *minfo;
MonoType *mtype;
if (!System_Reflection_Emit_UnmanagedMarshalClass) {
System_Reflection_Emit_UnmanagedMarshalClass = mono_class_from_name (
mono_defaults.corlib, "System.Reflection.Emit", "UnmanagedMarshal");
g_assert (System_Reflection_Emit_UnmanagedMarshalClass);
}
minfo = (MonoReflectionMarshal*)mono_object_new (domain, System_Reflection_Emit_UnmanagedMarshalClass);
minfo->type = spec->native;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
minfo->eltype = spec->data.array_data.elem_type;
minfo->count = spec->data.array_data.num_elem;
minfo->param_num = spec->data.array_data.param_num;
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
minfo->count = spec->data.array_data.num_elem;
break;
case MONO_NATIVE_CUSTOM:
if (spec->data.custom_data.custom_name) {
mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, klass->image);
if (mtype)
MONO_OBJECT_SETREF (minfo, marshaltyperef, mono_type_get_object (domain, mtype));
MONO_OBJECT_SETREF (minfo, marshaltype, mono_string_new (domain, spec->data.custom_data.custom_name));
}
if (spec->data.custom_data.cookie)
MONO_OBJECT_SETREF (minfo, mcookie, mono_string_new (domain, spec->data.custom_data.cookie));
break;
default:
break;
}
return minfo;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod*
reflection_methodbuilder_to_mono_method (MonoClass *klass,
ReflectionMethodBuilder *rmb,
MonoMethodSignature *sig)
{
MonoError error;
MonoMethod *m;
MonoMethodWrapper *wrapperm;
MonoMarshalSpec **specs;
MonoReflectionMethodAux *method_aux;
MonoImage *image;
gboolean dynamic;
int i;
mono_error_init (&error);
/*
* Methods created using a MethodBuilder should have their memory allocated
* inside the image mempool, while dynamic methods should have their memory
* malloc'd.
*/
dynamic = rmb->refs != NULL;
image = dynamic ? NULL : klass->image;
if (!dynamic)
g_assert (!klass->generic_class);
mono_loader_lock ();
if ((rmb->attrs & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(rmb->iattrs & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
m = (MonoMethod *)image_g_new0 (image, MonoMethodPInvoke, 1);
else
m = (MonoMethod *)image_g_new0 (image, MonoMethodWrapper, 1);
wrapperm = (MonoMethodWrapper*)m;
m->dynamic = dynamic;
m->slot = -1;
m->flags = rmb->attrs;
m->iflags = rmb->iattrs;
m->name = mono_string_to_utf8_image (image, rmb->name, &error);
g_assert (mono_error_ok (&error));
m->klass = klass;
m->signature = sig;
m->sre_method = TRUE;
m->skip_visibility = rmb->skip_visibility;
if (rmb->table_idx)
m->token = MONO_TOKEN_METHOD_DEF | (*rmb->table_idx);
if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (klass == mono_defaults.string_class && !strcmp (m->name, ".ctor"))
m->string_ctor = 1;
m->signature->pinvoke = 1;
} else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
m->signature->pinvoke = 1;
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->dllentry = rmb->dllentry ? mono_string_to_utf8_image (image, rmb->dllentry, &error) : image_strdup (image, m->name);
g_assert (mono_error_ok (&error));
method_aux->dll = mono_string_to_utf8_image (image, rmb->dll, &error);
g_assert (mono_error_ok (&error));
((MonoMethodPInvoke*)m)->piflags = (rmb->native_cc << 8) | (rmb->charset ? (rmb->charset - 1) * 2 : 0) | rmb->extra_flags;
if (klass->image->dynamic)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
} else if (!(m->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
!(m->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
MonoMethodHeader *header;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_clauses = 0;
guint8 *code;
if (rmb->ilgen) {
code = mono_array_addr (rmb->ilgen->code, guint8, 0);
code_size = rmb->ilgen->code_len;
max_stack = rmb->ilgen->max_stack;
num_locals = rmb->ilgen->locals ? mono_array_length (rmb->ilgen->locals) : 0;
if (rmb->ilgen->ex_handlers)
num_clauses = method_count_clauses (rmb->ilgen);
} else {
if (rmb->code) {
code = mono_array_addr (rmb->code, guint8, 0);
code_size = mono_array_length (rmb->code);
/* we probably need to run a verifier on the code... */
max_stack = 8;
}
else {
code = NULL;
code_size = 0;
max_stack = 8;
}
}
header = image_g_malloc0 (image, MONO_SIZEOF_METHOD_HEADER + num_locals * sizeof (MonoType*));
header->code_size = code_size;
header->code = image_g_malloc (image, code_size);
memcpy ((char*)header->code, code, code_size);
header->max_stack = max_stack;
header->init_locals = rmb->init_locals;
header->num_locals = num_locals;
for (i = 0; i < num_locals; ++i) {
MonoReflectionLocalBuilder *lb =
mono_array_get (rmb->ilgen->locals, MonoReflectionLocalBuilder*, i);
header->locals [i] = image_g_new0 (image, MonoType, 1);
memcpy (header->locals [i], mono_reflection_type_get_handle ((MonoReflectionType*)lb->type), MONO_SIZEOF_TYPE);
}
header->num_clauses = num_clauses;
if (num_clauses) {
header->clauses = method_encode_clauses (image, (MonoDynamicImage*)klass->image,
rmb->ilgen, num_clauses);
}
wrapperm->header = header;
}
if (rmb->generic_params) {
int count = mono_array_length (rmb->generic_params);
MonoGenericContainer *container = rmb->generic_container;
g_assert (container);
container->type_argc = count;
container->type_params = image_g_new0 (image, MonoGenericParamFull, count);
container->owner.method = m;
m->is_generic = TRUE;
mono_method_set_generic_container (m, container);
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gp =
mono_array_get (rmb->generic_params, MonoReflectionGenericParam*, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gp)->data.generic_param;
container->type_params [i] = *param;
}
/*
* The method signature might have pointers to generic parameters that belong to other methods.
* This is a valid SRE case, but the resulting method signature must be encoded using the proper
* generic parameters.
*/
for (i = 0; i < m->signature->param_count; ++i) {
MonoType *t = m->signature->params [i];
if (t->type == MONO_TYPE_MVAR) {
MonoGenericParam *gparam = t->data.generic_param;
if (gparam->num < count) {
m->signature->params [i] = mono_metadata_type_dup (image, m->signature->params [i]);
m->signature->params [i]->data.generic_param = mono_generic_container_get_param (container, gparam->num);
}
}
}
if (klass->generic_container) {
container->parent = klass->generic_container;
container->context.class_inst = klass->generic_container->context.class_inst;
}
container->context.method_inst = mono_get_shared_generic_inst (container);
}
if (rmb->refs) {
MonoMethodWrapper *mw = (MonoMethodWrapper*)m;
int i;
void **data;
m->wrapper_type = MONO_WRAPPER_DYNAMIC_METHOD;
mw->method_data = data = image_g_new (image, gpointer, rmb->nrefs + 1);
data [0] = GUINT_TO_POINTER (rmb->nrefs);
for (i = 0; i < rmb->nrefs; ++i)
data [i + 1] = rmb->refs [i];
}
method_aux = NULL;
/* Parameter info */
if (rmb->pinfo) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_names = image_g_new0 (image, char *, mono_method_signature (m)->param_count + 1);
for (i = 0; i <= m->signature->param_count; ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if ((i > 0) && (pb->attrs)) {
/* Make a copy since it might point to a shared type structure */
m->signature->params [i - 1] = mono_metadata_type_dup (klass->image, m->signature->params [i - 1]);
m->signature->params [i - 1]->attrs = pb->attrs;
}
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
MonoDynamicImage *assembly;
guint32 idx, def_type, len;
char *p;
const char *p2;
if (!method_aux->param_defaults) {
method_aux->param_defaults = image_g_new0 (image, guint8*, m->signature->param_count + 1);
method_aux->param_default_types = image_g_new0 (image, guint32, m->signature->param_count + 1);
}
assembly = (MonoDynamicImage*)klass->image;
idx = encode_constant (assembly, pb->def_value, &def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
method_aux->param_defaults [i] = image_g_malloc (image, len);
method_aux->param_default_types [i] = def_type;
memcpy ((gpointer)method_aux->param_defaults [i], p, len);
}
if (pb->name) {
method_aux->param_names [i] = mono_string_to_utf8_image (image, pb->name, &error);
g_assert (mono_error_ok (&error));
}
if (pb->cattrs) {
if (!method_aux->param_cattr)
method_aux->param_cattr = image_g_new0 (image, MonoCustomAttrInfo*, m->signature->param_count + 1);
method_aux->param_cattr [i] = mono_custom_attrs_from_builders (image, klass->image, pb->cattrs);
}
}
}
}
/* Parameter marshalling */
specs = NULL;
if (rmb->pinfo)
for (i = 0; i < mono_array_length (rmb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if (pb->marshal_info) {
if (specs == NULL)
specs = image_g_new0 (image, MonoMarshalSpec*, sig->param_count + 1);
specs [pb->position] =
mono_marshal_spec_from_builder (image, klass->image->assembly, pb->marshal_info);
}
}
}
if (specs != NULL) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_marshall = specs;
}
if (klass->image->dynamic && method_aux)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
}
static MonoMethod*
ctorbuilder_to_mono_method (MonoClass *klass, MonoReflectionCtorBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = ctor_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoMethod*
methodbuilder_to_mono_method (MonoClass *klass, MonoReflectionMethodBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = method_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_method_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoClassField*
fieldbuilder_to_mono_class_field (MonoClass *klass, MonoReflectionFieldBuilder* fb)
{
MonoClassField *field;
MonoType *custom;
field = g_new0 (MonoClassField, 1);
field->name = mono_string_to_utf8 (fb->name);
if (fb->attrs || fb->modreq || fb->modopt) {
field->type = mono_metadata_type_dup (NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
g_assert (klass->image->dynamic);
custom = add_custom_modifiers ((MonoDynamicImage*)klass->image, field->type, fb->modreq, fb->modopt);
g_free (field->type);
field->type = custom;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
// FIXME: Can't store fb->def_value/RVA, is it needed for field_on_insts ?
return field;
}
#endif
MonoType*
mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc, MonoType **types)
{
MonoClass *klass;
MonoReflectionTypeBuilder *tb = NULL;
gboolean is_dynamic = FALSE;
MonoDomain *domain;
MonoClass *geninst;
mono_loader_lock ();
domain = mono_object_domain (type);
if (is_sre_type_builder (mono_object_class (type))) {
tb = (MonoReflectionTypeBuilder *) type;
is_dynamic = TRUE;
} else if (is_sre_generic_instance (mono_object_class (type))) {
MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type;
MonoReflectionType *gtd = rgi->generic_type;
if (is_sre_type_builder (mono_object_class (gtd))) {
tb = (MonoReflectionTypeBuilder *)gtd;
is_dynamic = TRUE;
}
}
/* FIXME: fix the CreateGenericParameters protocol to avoid the two stage setup of TypeBuilders */
if (tb && tb->generic_container)
mono_reflection_create_generic_class (tb);
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
if (!klass->generic_container) {
mono_loader_unlock ();
return NULL;
}
if (klass->wastypebuilder) {
tb = (MonoReflectionTypeBuilder *) mono_class_get_ref_info (klass);
is_dynamic = TRUE;
}
mono_loader_unlock ();
geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic);
return &geninst->byval_arg;
}
MonoClass*
mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic)
{
MonoGenericClass *gclass;
MonoGenericInst *inst;
g_assert (klass->generic_container);
inst = mono_metadata_get_generic_inst (type_argc, types);
gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic);
return mono_generic_class_get_class (gclass);
}
MonoReflectionMethod*
mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types)
{
MonoClass *klass;
MonoMethod *method, *inflated;
MonoMethodInflated *imethod;
MonoGenericContext tmp_context;
MonoGenericInst *ginst;
MonoType **type_argv;
int count, i;
MONO_ARCH_SAVE_REGS;
/*FIXME but this no longer should happen*/
if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionMethodBuilder *mb = NULL;
MonoReflectionTypeBuilder *tb;
MonoClass *klass;
mb = (MonoReflectionMethodBuilder *) rmethod;
tb = (MonoReflectionTypeBuilder *) mb->type;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
method = methodbuilder_to_mono_method (klass, mb);
#else
g_assert_not_reached ();
method = NULL;
#endif
} else {
method = rmethod->method;
}
klass = method->klass;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_method_signature (method)->generic_param_count;
if (count != mono_array_length (types))
return NULL;
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (types, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
imethod = (MonoMethodInflated *) inflated;
/*FIXME but I think this is no longer necessary*/
if (method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
/*
* This table maps metadata structures representing inflated methods/fields
* to the reflection objects representing their generic definitions.
*/
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
mono_loader_unlock ();
}
if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
mono_raise_exception (mono_get_exception_argument ("typeArguments", "Invalid generic arguments"));
return mono_method_get_object (mono_object_domain (rmethod), inflated, NULL);
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod *
inflate_mono_method (MonoClass *klass, MonoMethod *method, MonoObject *obj)
{
MonoMethodInflated *imethod;
MonoGenericContext *context;
int i;
/*
* With generic code sharing the klass might not be inflated.
* This can happen because classes inflated with their own
* type arguments are "normalized" to the uninflated class.
*/
if (!klass->generic_class)
return method;
context = mono_class_get_context (klass);
if (klass->method.count && klass->methods) {
/* Find the already created inflated method */
for (i = 0; i < klass->method.count; ++i) {
g_assert (klass->methods [i]->is_inflated);
if (((MonoMethodInflated*)klass->methods [i])->declaring == method)
break;
}
g_assert (i < klass->method.count);
imethod = (MonoMethodInflated*)klass->methods [i];
} else {
imethod = (MonoMethodInflated *) mono_class_inflate_generic_method_full (method, klass, context);
}
if (method->is_generic && method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, obj);
mono_loader_unlock ();
}
return (MonoMethod *) imethod;
}
static MonoMethod *
inflate_method (MonoReflectionType *type, MonoObject *obj)
{
MonoMethod *method;
MonoClass *gklass;
MonoClass *type_class = mono_object_class (type);
if (is_sre_generic_instance (type_class)) {
MonoReflectionGenericClass *mgc = (MonoReflectionGenericClass*)type;
gklass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mgc->generic_type));
} else if (is_sre_type_builder (type_class)) {
gklass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
} else if (type->type) {
gklass = mono_class_from_mono_type (type->type);
gklass = mono_class_get_generic_type_definition (gklass);
} else {
g_error ("Can't handle type %s", mono_type_get_full_name (mono_object_class (type)));
}
if (!strcmp (obj->vtable->klass->name, "MethodBuilder"))
if (((MonoReflectionMethodBuilder*)obj)->mhandle)
method = ((MonoReflectionMethodBuilder*)obj)->mhandle;
else
method = methodbuilder_to_mono_method (gklass, (MonoReflectionMethodBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "ConstructorBuilder"))
method = ctorbuilder_to_mono_method (gklass, (MonoReflectionCtorBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoMethod") || !strcmp (obj->vtable->klass->name, "MonoCMethod"))
method = ((MonoReflectionMethod *) obj)->method;
else {
method = NULL; /* prevent compiler warning */
g_error ("can't handle type %s", obj->vtable->klass->name);
}
return inflate_mono_method (mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)type)), method, obj);
}
/*TODO avoid saving custom attrs for generic classes as it's enough to have them on the generic type definition.*/
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoClass *klass, *gklass;
MonoType *gtype;
int i;
MONO_ARCH_SAVE_REGS;
gtype = mono_reflection_type_get_handle ((MonoReflectionType*)type);
klass = mono_class_from_mono_type (gtype);
g_assert (gtype->type == MONO_TYPE_GENERICINST);
gclass = gtype->data.generic_class;
if (!gclass->is_dynamic)
return;
dgclass = (MonoDynamicGenericClass *) gclass;
if (dgclass->initialized)
return;
gklass = gclass->container_class;
mono_class_init (gklass);
dgclass->count_methods = methods ? mono_array_length (methods) : 0;
dgclass->count_ctors = ctors ? mono_array_length (ctors) : 0;
dgclass->count_fields = fields ? mono_array_length (fields) : 0;
dgclass->methods = g_new0 (MonoMethod *, dgclass->count_methods);
dgclass->ctors = g_new0 (MonoMethod *, dgclass->count_ctors);
dgclass->fields = g_new0 (MonoClassField, dgclass->count_fields);
dgclass->field_objects = g_new0 (MonoObject*, dgclass->count_fields);
dgclass->field_generic_types = g_new0 (MonoType*, dgclass->count_fields);
for (i = 0; i < dgclass->count_methods; i++) {
MonoObject *obj = mono_array_get (methods, gpointer, i);
dgclass->methods [i] = inflate_method ((MonoReflectionType*)type, obj);
}
for (i = 0; i < dgclass->count_ctors; i++) {
MonoObject *obj = mono_array_get (ctors, gpointer, i);
dgclass->ctors [i] = inflate_method ((MonoReflectionType*)type, obj);
}
for (i = 0; i < dgclass->count_fields; i++) {
MonoObject *obj = mono_array_get (fields, gpointer, i);
MonoClassField *field, *inflated_field = NULL;
if (!strcmp (obj->vtable->klass->name, "FieldBuilder"))
inflated_field = field = fieldbuilder_to_mono_class_field (klass, (MonoReflectionFieldBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoField"))
field = ((MonoReflectionField *) obj)->field;
else {
field = NULL; /* prevent compiler warning */
g_assert_not_reached ();
}
dgclass->fields [i] = *field;
dgclass->fields [i].parent = klass;
dgclass->fields [i].type = mono_class_inflate_generic_type (
field->type, mono_generic_class_get_context ((MonoGenericClass *) dgclass));
dgclass->field_generic_types [i] = field->type;
MOVING_GC_REGISTER (&dgclass->field_objects [i]);
dgclass->field_objects [i] = obj;
if (inflated_field) {
g_free (inflated_field);
} else {
dgclass->fields [i].name = g_strdup (dgclass->fields [i].name);
}
}
dgclass->initialized = TRUE;
}
static void
fix_partial_generic_class (MonoClass *klass)
{
MonoClass *gklass = klass->generic_class->container_class;
MonoDynamicGenericClass *dgclass;
int i;
if (klass->wastypebuilder)
return;
dgclass = (MonoDynamicGenericClass *) klass->generic_class;
if (klass->parent != gklass->parent) {
MonoError error;
MonoType *parent_type = mono_class_inflate_generic_type_checked (&gklass->parent->byval_arg, &klass->generic_class->context, &error);
if (mono_error_ok (&error)) {
MonoClass *parent = mono_class_from_mono_type (parent_type);
mono_metadata_free_type (parent_type);
if (parent != klass->parent) {
/*fool mono_class_setup_parent*/
klass->supertypes = NULL;
mono_class_setup_parent (klass, parent);
}
} else {
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
mono_error_cleanup (&error);
if (gklass->wastypebuilder)
klass->wastypebuilder = TRUE;
return;
}
}
if (!dgclass->initialized)
return;
if (klass->method.count != gklass->method.count) {
klass->method.count = gklass->method.count;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * (klass->method.count + 1));
for (i = 0; i < klass->method.count; i++) {
klass->methods [i] = mono_class_inflate_generic_method_full (
gklass->methods [i], klass, mono_class_get_context (klass));
}
}
if (klass->interface_count && klass->interface_count != gklass->interface_count) {
klass->interface_count = gklass->interface_count;
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * gklass->interface_count);
klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
for (i = 0; i < gklass->interface_count; ++i) {
MonoType *iface_type = mono_class_inflate_generic_type (&gklass->interfaces [i]->byval_arg, mono_class_get_context (klass));
klass->interfaces [i] = mono_class_from_mono_type (iface_type);
mono_metadata_free_type (iface_type);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
}
if (klass->field.count != gklass->field.count) {
klass->field.count = gklass->field.count;
klass->fields = image_g_new0 (klass->image, MonoClassField, klass->field.count);
for (i = 0; i < klass->field.count; i++) {
klass->fields [i] = gklass->fields [i];
klass->fields [i].parent = klass;
klass->fields [i].type = mono_class_inflate_generic_type (gklass->fields [i].type, mono_class_get_context (klass));
}
}
/*We can only finish with this klass once it's parent has as well*/
if (gklass->wastypebuilder)
klass->wastypebuilder = TRUE;
return;
}
static void
ensure_generic_class_runtime_vtable (MonoClass *klass)
{
MonoClass *gklass = klass->generic_class->container_class;
ensure_runtime_vtable (gklass);
fix_partial_generic_class (klass);
}
static void
ensure_runtime_vtable (MonoClass *klass)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
int i, num, j;
if (!klass->image->dynamic || (!tb && !klass->generic_class) || klass->wastypebuilder)
return;
if (klass->parent)
ensure_runtime_vtable (klass->parent);
if (tb) {
num = tb->ctors? mono_array_length (tb->ctors): 0;
num += tb->num_methods;
klass->method.count = num;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * num);
num = tb->ctors? mono_array_length (tb->ctors): 0;
for (i = 0; i < num; ++i)
klass->methods [i] = ctorbuilder_to_mono_method (klass, mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i));
num = tb->num_methods;
j = i;
for (i = 0; i < num; ++i)
klass->methods [j++] = methodbuilder_to_mono_method (klass, mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i));
if (tb->interfaces) {
klass->interface_count = mono_array_length (tb->interfaces);
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * klass->interface_count);
for (i = 0; i < klass->interface_count; ++i) {
MonoType *iface = mono_type_array_get_and_resolve (tb->interfaces, i);
klass->interfaces [i] = mono_class_from_mono_type (iface);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
}
} else if (klass->generic_class){
ensure_generic_class_runtime_vtable (klass);
}
if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
for (i = 0; i < klass->method.count; ++i)
klass->methods [i]->slot = i;
klass->interfaces_packed = NULL; /*make setup_interface_offsets happy*/
mono_class_setup_interface_offsets (klass);
mono_class_setup_interface_id (klass);
}
/*
* The generic vtable is needed even if image->run is not set since some
* runtime code like ves_icall_Type_GetMethodsByName depends on
* method->slot being defined.
*/
/*
* tb->methods could not be freed since it is used for determining
* overrides during dynamic vtable construction.
*/
}
static MonoMethod*
mono_reflection_method_get_handle (MonoObject *method)
{
MonoClass *class = mono_object_class (method);
if (is_sr_mono_method (class) || is_sr_mono_generic_method (class)) {
MonoReflectionMethod *sr_method = (MonoReflectionMethod*)method;
return sr_method->method;
}
if (is_sre_method_builder (class)) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)method;
return mb->mhandle;
}
if (is_sre_method_on_tb_inst (class)) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)method;
MonoMethod *result;
/*FIXME move this to a proper method and unify with resolve_object*/
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
} else {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *mono_method;
if (is_sre_method_builder (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
else if (is_sr_mono_method (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethod *)m->mb)->method;
else
g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
result = inflate_mono_method (inflated_klass, mono_method, (MonoObject*)m->mb);
}
return result;
}
g_error ("Can't handle methods of type %s:%s", class->name_space, class->name);
return NULL;
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
MonoReflectionTypeBuilder *tb;
int i, onum;
*overrides = NULL;
*num_overrides = 0;
g_assert (klass->image->dynamic);
if (!mono_class_get_ref_info (klass))
return;
g_assert (strcmp (((MonoObject*)mono_class_get_ref_info (klass))->vtable->klass->name, "TypeBuilder") == 0);
tb = (MonoReflectionTypeBuilder*)mono_class_get_ref_info (klass);
onum = 0;
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method)
onum ++;
}
}
if (onum) {
*overrides = g_new0 (MonoMethod*, onum * 2);
onum = 0;
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method) {
(*overrides) [onum * 2] = mono_reflection_method_get_handle ((MonoObject *)mb->override_method);
(*overrides) [onum * 2 + 1] = mb->mhandle;
g_assert (mb->mhandle);
onum ++;
}
}
}
*num_overrides = onum;
}
static void
typebuilder_setup_fields (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionFieldBuilder *fb;
MonoClassField *field;
MonoImage *image = klass->image;
const char *p, *p2;
int i;
guint32 len, idx, real_size = 0;
klass->field.count = tb->num_fields;
klass->field.first = 0;
mono_error_init (error);
if (tb->class_size) {
g_assert ((tb->packing_size & 0xfffffff0) == 0);
klass->packing_size = tb->packing_size;
real_size = klass->instance_size + tb->class_size;
}
if (!klass->field.count) {
klass->instance_size = MAX (klass->instance_size, real_size);
return;
}
klass->fields = image_g_new0 (image, MonoClassField, klass->field.count);
mono_class_alloc_ext (klass);
klass->ext->field_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->field.count);
/*
This is, guess what, a hack.
The issue is that the runtime doesn't know how to setup the fields of a typebuider and crash.
On the static path no field class is resolved, only types are built. This is the right thing to do
but we suck.
Setting size_inited is harmless because we're doing the same job as mono_class_setup_fields anyway.
*/
klass->size_inited = 1;
for (i = 0; i < klass->field.count; ++i) {
fb = mono_array_get (tb->fields, gpointer, i);
field = &klass->fields [i];
field->name = mono_string_to_utf8_image (image, fb->name, error);
if (!mono_error_ok (error))
return;
if (fb->attrs) {
field->type = mono_metadata_type_dup (klass->image, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if ((fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) && fb->rva_data)
klass->ext->field_def_values [i].data = mono_array_addr (fb->rva_data, char, 0);
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
fb->handle = field;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
if (klass->enumtype && !(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
klass->cast_class = klass->element_class = mono_class_from_mono_type (field->type);
}
if (fb->def_value) {
MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
field->type->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
idx = encode_constant (assembly, fb->def_value, &klass->ext->field_def_values [i].def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
klass->ext->field_def_values [i].data = mono_image_alloc (image, len);
memcpy ((gpointer)klass->ext->field_def_values [i].data, p, len);
}
}
klass->instance_size = MAX (klass->instance_size, real_size);
mono_class_layout_fields (klass);
}
static void
typebuilder_setup_properties (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionPropertyBuilder *pb;
MonoImage *image = klass->image;
MonoProperty *properties;
int i;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->property.count = tb->properties ? mono_array_length (tb->properties) : 0;
klass->ext->property.first = 0;
properties = image_g_new0 (image, MonoProperty, klass->ext->property.count);
klass->ext->properties = properties;
for (i = 0; i < klass->ext->property.count; ++i) {
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
properties [i].parent = klass;
properties [i].attrs = pb->attrs;
properties [i].name = mono_string_to_utf8_image (image, pb->name, error);
if (!mono_error_ok (error))
return;
if (pb->get_method)
properties [i].get = pb->get_method->mhandle;
if (pb->set_method)
properties [i].set = pb->set_method->mhandle;
mono_save_custom_attrs (klass->image, &properties [i], pb->cattrs);
if (pb->def_value) {
guint32 len, idx;
const char *p, *p2;
MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
if (!klass->ext->prop_def_values)
klass->ext->prop_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->ext->property.count);
properties [i].attrs |= PROPERTY_ATTRIBUTE_HAS_DEFAULT;
idx = encode_constant (assembly, pb->def_value, &klass->ext->prop_def_values [i].def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
klass->ext->prop_def_values [i].data = mono_image_alloc (image, len);
memcpy ((gpointer)klass->ext->prop_def_values [i].data, p, len);
}
}
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
MonoEvent *event = g_new0 (MonoEvent, 1);
MonoClass *klass;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
event->parent = klass;
event->attrs = eb->attrs;
event->name = mono_string_to_utf8 (eb->name);
if (eb->add_method)
event->add = eb->add_method->mhandle;
if (eb->remove_method)
event->remove = eb->remove_method->mhandle;
if (eb->raise_method)
event->raise = eb->raise_method->mhandle;
#ifndef MONO_SMALL_CONFIG
if (eb->other_methods) {
int j;
event->other = g_new0 (MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
event->other [j] = mb->mhandle;
}
}
#endif
return mono_event_get_object (mono_object_domain (tb), klass, event);
}
static void
typebuilder_setup_events (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
MonoReflectionEventBuilder *eb;
MonoImage *image = klass->image;
MonoEvent *events;
int i;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->event.count = tb->events ? mono_array_length (tb->events) : 0;
klass->ext->event.first = 0;
events = image_g_new0 (image, MonoEvent, klass->ext->event.count);
klass->ext->events = events;
for (i = 0; i < klass->ext->event.count; ++i) {
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
events [i].parent = klass;
events [i].attrs = eb->attrs;
events [i].name = mono_string_to_utf8_image (image, eb->name, error);
if (!mono_error_ok (error))
return;
if (eb->add_method)
events [i].add = eb->add_method->mhandle;
if (eb->remove_method)
events [i].remove = eb->remove_method->mhandle;
if (eb->raise_method)
events [i].raise = eb->raise_method->mhandle;
#ifndef MONO_SMALL_CONFIG
if (eb->other_methods) {
int j;
events [i].other = image_g_new0 (image, MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
events [i].other [j] = mb->mhandle;
}
}
#endif
mono_save_custom_attrs (klass->image, &events [i], eb->cattrs);
}
}
static gboolean
remove_instantiations_of_and_ensure_contents (gpointer key,
gpointer value,
gpointer user_data)
{
MonoType *type = (MonoType*)key;
MonoClass *klass = (MonoClass*)user_data;
if ((type->type == MONO_TYPE_GENERICINST) && (type->data.generic_class->container_class == klass)) {
fix_partial_generic_class (mono_class_from_mono_type (type)); //Ensure it's safe to use it.
return TRUE;
} else
return FALSE;
}
static void
check_array_for_usertypes (MonoArray *arr)
{
int i;
if (!arr)
return;
for (i = 0; i < mono_array_length (arr); ++i)
RESOLVE_ARRAY_TYPE_ELEMENT (arr, i);
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass;
MonoDomain* domain;
MonoReflectionType* res;
int i, j;
MONO_ARCH_SAVE_REGS;
domain = mono_object_domain (tb);
klass = mono_class_from_mono_type (tb->type.type);
/*
* Check for user defined Type subclasses.
*/
RESOLVE_TYPE (tb->parent);
check_array_for_usertypes (tb->interfaces);
if (tb->fields) {
for (i = 0; i < mono_array_length (tb->fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (tb->fields, gpointer, i);
if (fb) {
RESOLVE_TYPE (fb->type);
check_array_for_usertypes (fb->modreq);
check_array_for_usertypes (fb->modopt);
if (fb->marshal_info && fb->marshal_info->marshaltyperef)
RESOLVE_TYPE (fb->marshal_info->marshaltyperef);
}
}
}
if (tb->methods) {
for (i = 0; i < mono_array_length (tb->methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (tb->methods, gpointer, i);
if (mb) {
RESOLVE_TYPE (mb->rtype);
check_array_for_usertypes (mb->return_modreq);
check_array_for_usertypes (mb->return_modopt);
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder *mb = mono_array_get (tb->ctors, gpointer, i);
if (mb) {
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
mono_save_custom_attrs (klass->image, klass, tb->cattrs);
/*
* we need to lock the domain because the lock will be taken inside
* So, we need to keep the locking order correct.
*/
mono_loader_lock ();
mono_domain_lock (domain);
if (klass->wastypebuilder) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
/*
* Fields to set in klass:
* the various flags: delegate/unicode/contextbound etc.
*/
klass->flags = tb->attrs;
klass->has_cctor = 1;
klass->has_finalize = 1;
/* fool mono_class_setup_parent */
klass->supertypes = NULL;
mono_class_setup_parent (klass, klass->parent);
mono_class_setup_mono_type (klass);
#if 0
if (!((MonoDynamicImage*)klass->image)->run) {
if (klass->generic_container) {
/* FIXME: The code below can't handle generic classes */
klass->wastypebuilder = TRUE;
mono_loader_unlock ();
mono_domain_unlock (domain);
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
}
#endif
/* enums are done right away */
if (!klass->enumtype)
ensure_runtime_vtable (klass);
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtb = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
mono_class_alloc_ext (klass);
klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)subtb)));
}
}
klass->nested_classes_inited = TRUE;
/* fields and object layout */
if (klass->parent) {
if (!klass->parent->size_inited)
mono_class_init (klass->parent);
klass->instance_size = klass->parent->instance_size;
klass->sizes.class_size = 0;
klass->min_align = klass->parent->min_align;
/* if the type has no fields we won't call the field_setup
* routine which sets up klass->has_references.
*/
klass->has_references |= klass->parent->has_references;
} else {
klass->instance_size = sizeof (MonoObject);
klass->min_align = 1;
}
/* FIXME: handle packing_size and instance_size */
typebuilder_setup_fields (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_properties (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_events (klass, &error);
if (!mono_error_ok (&error))
goto failure;
klass->wastypebuilder = TRUE;
/*
* If we are a generic TypeBuilder, there might be instantiations in the type cache
* which have type System.Reflection.MonoGenericClass, but after the type is created,
* we want to return normal System.MonoType objects, so clear these out from the cache.
*
* Together with this we must ensure the contents of all instances to match the created type.
*/
if (domain->type_hash && klass->generic_container)
mono_g_hash_table_foreach_remove (domain->type_hash, remove_instantiations_of_and_ensure_contents, klass);
mono_domain_unlock (domain);
mono_loader_unlock ();
if (klass->enumtype && !mono_class_is_valid_enum (klass)) {
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
mono_raise_exception (mono_get_exception_type_load (tb->name, NULL));
}
res = mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
g_assert (res != (MonoReflectionType*)tb);
return res;
failure:
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
klass->wastypebuilder = TRUE;
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_error_raise_exception (&error);
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
MonoGenericParamFull *param;
MonoImage *image;
MonoClass *pklass;
MONO_ARCH_SAVE_REGS;
param = g_new0 (MonoGenericParamFull, 1);
if (gparam->mbuilder) {
if (!gparam->mbuilder->generic_container) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)gparam->mbuilder->type;
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
gparam->mbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->mbuilder->generic_container->is_method = TRUE;
/*
* Cannot set owner.method, since the MonoMethod is not created yet.
* Set the image field instead, so type_in_image () works.
*/
gparam->mbuilder->generic_container->image = klass->image;
}
param->param.owner = gparam->mbuilder->generic_container;
} else if (gparam->tbuilder) {
if (!gparam->tbuilder->generic_container) {
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)gparam->tbuilder));
gparam->tbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->tbuilder->generic_container->owner.klass = klass;
}
param->param.owner = gparam->tbuilder->generic_container;
}
param->info.name = mono_string_to_utf8 (gparam->name);
param->param.num = gparam->index;
image = &gparam->tbuilder->module->dynamic_image->image;
pklass = mono_class_from_generic_parameter ((MonoGenericParam *) param, image, gparam->mbuilder != NULL);
gparam->type.type = &pklass->byval_arg;
mono_class_set_ref_info (pklass, gparam);
mono_image_lock (image);
image->reflection_info_unregister_classes = g_slist_prepend (image->reflection_info_unregister_classes, pklass);
mono_image_unlock (image);
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
MonoReflectionModuleBuilder *module = sig->module;
MonoDynamicImage *assembly = module != NULL ? module->dynamic_image : NULL;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, na);
if (assembly != NULL){
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
MonoDynamicImage *assembly = sig->module->dynamic_image;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
MonoClass *klass;
GSList *l;
int i;
sig = dynamic_method_to_signature (mb);
reflection_methodbuilder_from_dynamic_method (&rmb, mb);
/*
* Resolve references.
*/
/*
* Every second entry in the refs array is reserved for storing handle_class,
* which is needed by the ldtoken implementation in the JIT.
*/
rmb.nrefs = mb->nrefs;
rmb.refs = g_new0 (gpointer, mb->nrefs + 1);
for (i = 0; i < mb->nrefs; i += 2) {
MonoClass *handle_class;
gpointer ref;
MonoObject *obj = mono_array_get (mb->refs, MonoObject*, i);
if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/*
* The referenced DynamicMethod should already be created by the managed
* code, except in the case of circular references. In that case, we store
* method in the refs array, and fix it up later when the referenced
* DynamicMethod is created.
*/
if (method->mhandle) {
ref = method->mhandle;
} else {
/* FIXME: GC object stored in unmanaged memory */
ref = method;
/* FIXME: GC object stored in unmanaged memory */
method->referenced_by = g_slist_append (method->referenced_by, mb);
}
handle_class = mono_defaults.methodhandle_class;
} else {
MonoException *ex = NULL;
ref = resolve_object (mb->module->image, obj, &handle_class, NULL);
if (!ref)
ex = mono_get_exception_type_load (NULL, NULL);
else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
ex = mono_security_core_clr_ensure_dynamic_method_resolved_object (ref, handle_class);
if (ex) {
g_free (rmb.refs);
mono_raise_exception (ex);
return;
}
}
rmb.refs [i] = ref; /* FIXME: GC object stored in unmanaged memory (change also resolve_object() signature) */
rmb.refs [i + 1] = handle_class;
}
klass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class;
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
/* Fix up refs entries pointing at us */
for (l = mb->referenced_by; l; l = l->next) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)l->data;
MonoMethodWrapper *wrapper = (MonoMethodWrapper*)method->mhandle;
gpointer *data;
g_assert (method->mhandle);
data = (gpointer*)wrapper->method_data;
for (i = 0; i < GPOINTER_TO_UINT (data [0]); i += 2) {
if ((data [i + 1] == mb) && (data [i + 1 + 1] == mono_defaults.methodhandle_class))
data [i + 1] = mb->mhandle;
}
}
g_slist_free (mb->referenced_by);
g_free (rmb.refs);
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
#endif /* DISABLE_REFLECTION_EMIT */
void
mono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb)
{
g_assert (mb);
if (mb->mhandle)
mono_runtime_free_method (
mono_object_get_domain ((MonoObject*)mb), mb->mhandle);
}
/**
*
* mono_reflection_is_valid_dynamic_token:
*
* Returns TRUE if token is valid.
*
*/
gboolean
mono_reflection_is_valid_dynamic_token (MonoDynamicImage *image, guint32 token)
{
return mono_g_hash_table_lookup (image->tokens, GUINT_TO_POINTER (token)) != NULL;
}
MonoMethodSignature *
mono_reflection_lookup_signature (MonoImage *image, MonoMethod *method, guint32 token)
{
MonoMethodSignature *sig;
g_assert (image->dynamic);
sig = g_hash_table_lookup (((MonoDynamicImage*)image)->vararg_aux_hash, GUINT_TO_POINTER (token));
if (sig)
return sig;
return mono_method_signature (method);
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mono_reflection_lookup_dynamic_token:
*
* Finish the Builder object pointed to by TOKEN and return the corresponding
* runtime structure. If HANDLE_CLASS is not NULL, it is set to the class required by
* mono_ldtoken. If valid_token is TRUE, assert if it is not found in the token->object
* mapping table.
*
* LOCKING: Take the loader lock
*/
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
MonoDynamicImage *assembly = (MonoDynamicImage*)image;
MonoObject *obj;
MonoClass *klass;
mono_loader_lock ();
obj = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
mono_loader_unlock ();
if (!obj) {
if (valid_token)
g_error ("Could not find required dynamic token 0x%08x", token);
else
return NULL;
}
if (!handle_class)
handle_class = &klass;
return resolve_object (image, obj, handle_class, context);
}
/*
* ensure_complete_type:
*
* Ensure that KLASS is completed if it is a dynamic type, or references
* dynamic types.
*/
static void
ensure_complete_type (MonoClass *klass)
{
if (klass->image->dynamic && !klass->wastypebuilder && mono_class_get_ref_info (klass)) {
MonoReflectionTypeBuilder *tb = mono_class_get_ref_info (klass);
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
// Asserting here could break a lot of code
//g_assert (klass->wastypebuilder);
}
if (klass->generic_class) {
MonoGenericInst *inst = klass->generic_class->context.class_inst;
int i;
for (i = 0; i < inst->type_argc; ++i) {
ensure_complete_type (mono_class_from_mono_type (inst->type_argv [i]));
}
}
}
static gpointer
resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context)
{
gpointer result = NULL;
if (strcmp (obj->vtable->klass->name, "String") == 0) {
result = mono_string_intern ((MonoString*)obj);
*handle_class = mono_defaults.string_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
MonoClass *mc = mono_class_from_mono_type (type);
if (!mono_class_init (mc))
mono_raise_exception (mono_class_get_exception_for_failure (mc));
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
} else {
result = mono_class_from_mono_type (type);
}
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericMethod") == 0) {
result = ((MonoReflectionMethod*)obj)->method;
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
result = mb->mhandle;
if (!result) {
/* Type is not yet created */
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
/*
* Hopefully this has been filled in by calling CreateType() on the
* TypeBuilder.
*/
/*
* TODO: This won't work if the application finishes another
* TypeBuilder instance instead of this one.
*/
result = mb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
result = cb->mhandle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)cb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = cb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoField") == 0) {
MonoClassField *field = ((MonoReflectionField*)obj)->field;
ensure_complete_type (field->parent);
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (&field->parent->byval_arg, context);
MonoClass *class = mono_class_from_mono_type (inflated);
MonoClassField *inflated_field;
gpointer iter = NULL;
mono_metadata_free_type (inflated);
while ((inflated_field = mono_class_get_fields (class, &iter))) {
if (!strcmp (field->name, inflated_field->name))
break;
}
g_assert (inflated_field && !strcmp (field->name, inflated_field->name));
result = inflated_field;
} else {
result = field;
}
*handle_class = mono_defaults.fieldhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
result = fb->handle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)fb->typeb;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = fb->handle;
}
if (fb->handle && fb->handle->parent->generic_container) {
MonoClass *klass = fb->handle->parent;
MonoType *type = mono_class_inflate_generic_type (&klass->byval_arg, context);
MonoClass *inflated = mono_class_from_mono_type (type);
result = mono_class_get_field_from_name (inflated, mono_field_get_name (fb->handle));
g_assert (result);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
MonoClass *klass;
klass = type->data.klass;
if (klass->wastypebuilder) {
/* Already created */
result = klass;
}
else {
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = type->data.klass;
g_assert (result);
}
*handle_class = mono_defaults.typehandle_class;
} else if (strcmp (obj->vtable->klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *helper = (MonoReflectionSigHelper*)obj;
MonoMethodSignature *sig;
int nargs, i;
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
sig = mono_metadata_signature_alloc (image, nargs);
sig->explicit_this = helper->call_conv & 64 ? 1 : 0;
sig->hasthis = helper->call_conv & 32 ? 1 : 0;
if (helper->unmanaged_call_conv) { /* unmanaged */
sig->call_convention = helper->unmanaged_call_conv - 1;
sig->pinvoke = TRUE;
} else if (helper->call_conv & 0x02) {
sig->call_convention = MONO_CALL_VARARG;
} else {
sig->call_convention = MONO_CALL_DEFAULT;
}
sig->param_count = nargs;
/* TODO: Copy type ? */
sig->ret = helper->return_type->type;
for (i = 0; i < nargs; ++i)
sig->params [i] = mono_type_array_get_and_resolve (helper->arguments, i);
result = sig;
*handle_class = NULL;
} else if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/* Already created by the managed code */
g_assert (method->mhandle);
result = method->mhandle;
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
MonoClass *inflated;
MonoType *type;
MonoClassField *field;
if (is_sre_field_builder (mono_object_class (f->fb)))
field = ((MonoReflectionFieldBuilder*)f->fb)->handle;
else if (is_sr_mono_field (mono_object_class (f->fb)))
field = ((MonoReflectionField*)f->fb)->field;
else
g_error ("resolve_object:: can't handle a FTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (f->fb)));
type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)f->inst), context);
inflated = mono_class_from_mono_type (type);
result = field = mono_class_get_field_from_name (inflated, mono_field_get_name (field));
ensure_complete_type (field->parent);
g_assert (result);
mono_metadata_free_type (type);
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)c->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *method;
if (is_sre_ctor_builder (mono_object_class (c->cb)))
method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
else if (is_sr_mono_cmethod (mono_object_class (c->cb)))
method = ((MonoReflectionMethod *)c->cb)->method;
else
g_error ("resolve_object:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (c->cb)));
result = inflate_mono_method (inflated_klass, method, (MonoObject*)c->cb);
*handle_class = mono_defaults.methodhandle_class;
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
if (context)
result = mono_class_inflate_generic_method (result, context);
} else {
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)m->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *method;
if (is_sre_method_builder (mono_object_class (m->mb)))
method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
else if (is_sr_mono_method (mono_object_class (m->mb)))
method = ((MonoReflectionMethod *)m->mb)->method;
else
g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
result = inflate_mono_method (inflated_klass, method, (MonoObject*)m->mb);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod*)obj;
MonoType *mtype;
MonoClass *klass;
MonoMethod *method;
gpointer iter;
char *name;
mtype = mono_reflection_type_get_handle (m->parent);
klass = mono_class_from_mono_type (mtype);
/* Find the method */
name = mono_string_to_utf8 (m->name);
iter = NULL;
while ((method = mono_class_get_methods (klass, &iter))) {
if (!strcmp (method->name, name))
break;
}
g_free (name);
// FIXME:
g_assert (method);
// FIXME: Check parameters/return value etc. match
result = method;
*handle_class = mono_defaults.methodhandle_class;
} else if (is_sre_array (mono_object_get_class(obj)) ||
is_sre_byref (mono_object_get_class(obj)) ||
is_sre_pointer (mono_object_get_class(obj))) {
MonoReflectionType *ref_type = (MonoReflectionType *)obj;
MonoType *type = mono_reflection_type_get_handle (ref_type);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
} else {
g_print ("%s\n", obj->vtable->klass->name);
g_assert_not_reached ();
}
return result;
}
#else /* DISABLE_REFLECTION_EMIT */
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit, so System.Reflection.Emit is not supported.");
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
g_assert_not_reached ();
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
g_assert_not_reached ();
}
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
g_assert_not_reached ();
return NULL;
}
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_methodspec, gboolean register_token)
{
g_assert_not_reached ();
return 0;
}
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
}
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
g_assert_not_reached ();
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
*overrides = NULL;
*num_overrides = 0;
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
g_assert_not_reached ();
return NULL;
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
g_assert_not_reached ();
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
}
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
return NULL;
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
if (!ref)
return NULL;
return ref->type;
}
#endif /* DISABLE_REFLECTION_EMIT */
/* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */
const static guint32 declsec_flags_map[] = {
0x00000000, /* empty */
MONO_DECLSEC_FLAG_REQUEST, /* SECURITY_ACTION_REQUEST (x01) */
MONO_DECLSEC_FLAG_DEMAND, /* SECURITY_ACTION_DEMAND (x02) */
MONO_DECLSEC_FLAG_ASSERT, /* SECURITY_ACTION_ASSERT (x03) */
MONO_DECLSEC_FLAG_DENY, /* SECURITY_ACTION_DENY (x04) */
MONO_DECLSEC_FLAG_PERMITONLY, /* SECURITY_ACTION_PERMITONLY (x05) */
MONO_DECLSEC_FLAG_LINKDEMAND, /* SECURITY_ACTION_LINKDEMAND (x06) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND, /* SECURITY_ACTION_INHERITANCEDEMAND (x07) */
MONO_DECLSEC_FLAG_REQUEST_MINIMUM, /* SECURITY_ACTION_REQUEST_MINIMUM (x08) */
MONO_DECLSEC_FLAG_REQUEST_OPTIONAL, /* SECURITY_ACTION_REQUEST_OPTIONAL (x09) */
MONO_DECLSEC_FLAG_REQUEST_REFUSE, /* SECURITY_ACTION_REQUEST_REFUSE (x0A) */
MONO_DECLSEC_FLAG_PREJIT_GRANT, /* SECURITY_ACTION_PREJIT_GRANT (x0B) */
MONO_DECLSEC_FLAG_PREJIT_DENY, /* SECURITY_ACTION_PREJIT_DENY (x0C) */
MONO_DECLSEC_FLAG_NONCAS_DEMAND, /* SECURITY_ACTION_NONCAS_DEMAND (x0D) */
MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND, /* SECURITY_ACTION_NONCAS_LINKDEMAND (x0E) */
MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND, /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND (x0F) */
MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE, /* SECURITY_ACTION_LINKDEMAND_CHOICE (x10) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE, /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE (x11) */
MONO_DECLSEC_FLAG_DEMAND_CHOICE, /* SECURITY_ACTION_DEMAND_CHOICE (x12) */
};
/*
* Returns flags that includes all available security action associated to the handle.
* @token: metadata token (either for a class or a method)
* @image: image where resides the metadata.
*/
static guint32
mono_declsec_get_flags (MonoImage *image, guint32 token)
{
int index = mono_metadata_declsec_from_index (image, token);
MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY];
guint32 result = 0;
guint32 action;
int i;
/* HasSecurity can be present for other, not specially encoded, attributes,
e.g. SuppressUnmanagedCodeSecurityAttribute */
if (index < 0)
return 0;
for (i = index; i < t->rows; i++) {
guint32 cols [MONO_DECL_SECURITY_SIZE];
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
break;
action = cols [MONO_DECL_SECURITY_ACTION];
if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) {
result |= declsec_flags_map [action];
} else {
g_assert_not_reached ();
}
}
return result;
}
/*
* Get the security actions (in the form of flags) associated with the specified method.
*
* @method: The method for which we want the declarative security flags.
* Return the declarative security flags for the method (only).
*
* Note: To keep MonoMethod size down we do not cache the declarative security flags
* (except for the stack modifiers which are kept in the MonoJitInfo structure)
*/
guint32
mono_declsec_flags_from_method (MonoMethod *method)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
/* FIXME: No cache (for the moment) */
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return mono_declsec_get_flags (method->klass->image, idx);
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified class.
*
* @klass: The class for which we want the declarative security flags.
* Return the declarative security flags for the class.
*
* Note: We cache the flags inside the MonoClass structure as this will get
* called very often (at least for each method).
*/
guint32
mono_declsec_flags_from_class (MonoClass *klass)
{
if (klass->flags & TYPE_ATTRIBUTE_HAS_SECURITY) {
if (!klass->ext || !klass->ext->declsec_flags) {
guint32 idx;
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
mono_loader_lock ();
mono_class_alloc_ext (klass);
mono_loader_unlock ();
/* we cache the flags on classes */
klass->ext->declsec_flags = mono_declsec_get_flags (klass->image, idx);
}
return klass->ext->declsec_flags;
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified assembly.
*
* @assembly: The assembly for which we want the declarative security flags.
* Return the declarative security flags for the assembly.
*/
guint32
mono_declsec_flags_from_assembly (MonoAssembly *assembly)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return mono_declsec_get_flags (assembly->image, idx);
}
/*
* Fill actions for the specific index (which may either be an encoded class token or
* an encoded method token) from the metadata image.
* Returns TRUE if some actions requiring code generation are present, FALSE otherwise.
*/
static MonoBoolean
fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
MonoBoolean result = FALSE;
MonoTableInfo *t;
guint32 cols [MONO_DECL_SECURITY_SIZE];
int index = mono_metadata_declsec_from_index (image, token);
int i;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
return result;
/* if present only replace (class) permissions with method permissions */
/* if empty accept either class or method permissions */
if (cols [MONO_DECL_SECURITY_ACTION] == id_std) {
if (!actions->demand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demand.blob = (char*) (blob + 2);
actions->demand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) {
if (!actions->noncasdemand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->noncasdemand.blob = (char*) (blob + 2);
actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) {
if (!actions->demandchoice.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demandchoice.blob = (char*) (blob + 2);
actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
}
}
return result;
}
static MonoBoolean
mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return fill_actions_from_index (klass->image, idx, demands, id_std, id_noncas, id_choice);
}
static MonoBoolean
mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return fill_actions_from_index (method->klass->image, idx, demands, id_std, id_noncas, id_choice);
}
/*
* Collect all actions (that requires to generate code in mini) assigned for
* the specified method.
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands)
{
guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND |
MONO_DECLSEC_FLAG_DEMAND_CHOICE;
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result = mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & mask) {
if (!result) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
}
result |= mono_declsec_get_class_demands_params (method->klass, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* The boolean return value is used as a shortcut in case nothing needs to
be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */
return result;
}
/*
* Collect all Link actions: LinkDemand, NonCasLinkDemand and LinkDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* results are independant - zeroize both */
memset (cmethod, 0, sizeof (MonoDeclSecurityActions));
memset (klass, 0, sizeof (MonoDeclSecurityActions));
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
result = mono_declsec_get_method_demands_params (method, cmethod,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) {
mono_class_init (method->klass);
result |= mono_declsec_get_class_demands_params (method->klass, klass,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* @klass The inherited class - this is the class that provides the security check (attributes)
* @demans
* return TRUE if inheritance demands (any kind) are present, FALSE otherwise.
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (klass);
if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) {
mono_class_init (klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result |= mono_declsec_get_class_demands_params (klass, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands)
{
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
return mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return FALSE;
}
static MonoBoolean
get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 cols [MONO_DECL_SECURITY_SIZE];
MonoTableInfo *t;
int i;
int index = mono_metadata_declsec_from_index (image, token);
if (index == -1)
return FALSE;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
/* shortcut - index are ordered */
if (token != cols [MONO_DECL_SECURITY_PARENT])
return FALSE;
if (cols [MONO_DECL_SECURITY_ACTION] == action) {
const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
entry->blob = (char*) (metadata + 2);
entry->size = mono_metadata_decode_blob_size (metadata, &metadata);
return TRUE;
}
}
return FALSE;
}
MonoBoolean
mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return get_declsec_action (method->klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry)
{
/* use cache */
guint32 flags = mono_declsec_flags_from_class (klass);
if (declsec_flags_map [action] & flags) {
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return get_declsec_action (klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return get_declsec_action (assembly->image, idx, action, entry);
}
gboolean
mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass)
{
MonoObject *res, *exc;
void *params [1];
static MonoClass *System_Reflection_Emit_TypeBuilder = NULL;
static MonoMethod *method = NULL;
if (!System_Reflection_Emit_TypeBuilder) {
System_Reflection_Emit_TypeBuilder = mono_class_from_name (mono_defaults.corlib, "System.Reflection.Emit", "TypeBuilder");
g_assert (System_Reflection_Emit_TypeBuilder);
}
if (method == NULL) {
method = mono_class_get_method_from_name (System_Reflection_Emit_TypeBuilder, "IsAssignableTo", 1);
g_assert (method);
}
/*
* The result of mono_type_get_object () might be a System.MonoType but we
* need a TypeBuilder so use mono_class_get_ref_info (klass).
*/
g_assert (mono_class_get_ref_info (klass));
g_assert (!strcmp (((MonoObject*)(mono_class_get_ref_info (klass)))->vtable->klass->name, "TypeBuilder"));
params [0] = mono_type_get_object (mono_domain_get (), &oklass->byval_arg);
res = mono_runtime_invoke (method, (MonoObject*)(mono_class_get_ref_info (klass)), params, &exc);
if (exc)
return FALSE;
else
return *(MonoBoolean*)mono_object_unbox (res);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4717_0 |
crossvul-cpp_data_bad_5418_2 | /*
* Copyright (c) 2001-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
/*
* Image Information Program
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <assert.h>
#include <stdint.h>
#include <jasper/jasper.h>
/******************************************************************************\
*
\******************************************************************************/
typedef enum {
OPT_HELP,
OPT_VERSION,
OPT_VERBOSE,
OPT_INFILE,
OPT_DEBUG,
OPT_MAXMEM
} optid_t;
/******************************************************************************\
*
\******************************************************************************/
static void usage(void);
static void cmdinfo(void);
/******************************************************************************\
*
\******************************************************************************/
static jas_opt_t opts[] = {
{OPT_HELP, "help", 0},
{OPT_VERSION, "version", 0},
{OPT_VERBOSE, "verbose", 0},
{OPT_INFILE, "f", JAS_OPT_HASARG},
{OPT_DEBUG, "debug-level", JAS_OPT_HASARG},
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
{OPT_MAXMEM, "memory-limit", JAS_OPT_HASARG},
#endif
{-1, 0, 0}
};
static char *cmdname = 0;
/******************************************************************************\
* Main program.
\******************************************************************************/
int main(int argc, char **argv)
{
int fmtid;
int id;
char *infile;
jas_stream_t *instream;
jas_image_t *image;
int width;
int height;
int depth;
int numcmpts;
int verbose;
char *fmtname;
int debug;
size_t max_mem;
if (jas_init()) {
abort();
}
cmdname = argv[0];
infile = 0;
verbose = 0;
debug = 0;
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
max_mem = JAS_DEFAULT_MAX_MEM_USAGE;
#endif
/* Parse the command line options. */
while ((id = jas_getopt(argc, argv, opts)) >= 0) {
switch (id) {
case OPT_VERBOSE:
verbose = 1;
break;
case OPT_VERSION:
printf("%s\n", JAS_VERSION);
exit(EXIT_SUCCESS);
break;
case OPT_DEBUG:
debug = atoi(jas_optarg);
break;
case OPT_INFILE:
infile = jas_optarg;
break;
case OPT_MAXMEM:
max_mem = strtoull(jas_optarg, 0, 10);
break;
case OPT_HELP:
default:
usage();
break;
}
}
jas_setdbglevel(debug);
#if defined(JAS_DEFAULT_MAX_MEM_USAGE)
jas_set_max_mem_usage(max_mem);
#endif
/* Open the image file. */
if (infile) {
/* The image is to be read from a file. */
if (!(instream = jas_stream_fopen(infile, "rb"))) {
fprintf(stderr, "cannot open input image file %s\n", infile);
exit(EXIT_FAILURE);
}
} else {
/* The image is to be read from standard input. */
if (!(instream = jas_stream_fdopen(0, "rb"))) {
fprintf(stderr, "cannot open standard input\n");
exit(EXIT_FAILURE);
}
}
if ((fmtid = jas_image_getfmt(instream)) < 0) {
fprintf(stderr, "unknown image format\n");
}
/* Decode the image. */
if (!(image = jas_image_decode(instream, fmtid, 0))) {
jas_stream_close(instream);
fprintf(stderr, "cannot load image\n");
return EXIT_FAILURE;
}
/* Close the image file. */
jas_stream_close(instream);
if (!(numcmpts = jas_image_numcmpts(image))) {
fprintf(stderr, "warning: image has no components\n");
}
if (numcmpts) {
width = jas_image_cmptwidth(image, 0);
height = jas_image_cmptheight(image, 0);
depth = jas_image_cmptprec(image, 0);
} else {
width = 0;
height = 0;
depth = 0;
}
if (!(fmtname = jas_image_fmttostr(fmtid))) {
abort();
}
printf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));
jas_image_destroy(image);
jas_image_clearfmts();
return EXIT_SUCCESS;
}
/******************************************************************************\
*
\******************************************************************************/
static void cmdinfo()
{
fprintf(stderr, "Image Information Utility (Version %s).\n",
JAS_VERSION);
fprintf(stderr,
"Copyright (c) 2001 Michael David Adams.\n"
"All rights reserved.\n"
);
}
static void usage()
{
cmdinfo();
fprintf(stderr, "usage:\n");
fprintf(stderr,"%s ", cmdname);
fprintf(stderr, "[-f image_file]\n");
exit(EXIT_FAILURE);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5418_2 |
crossvul-cpp_data_good_5845_16 | /*********************************************************************
*
* Filename: af_irda.c
* Version: 0.9
* Description: IrDA sockets implementation
* Status: Stable
* Author: Dag Brattli <dagb@cs.uit.no>
* Created at: Sun May 31 10:12:43 1998
* Modified at: Sat Dec 25 21:10:23 1999
* Modified by: Dag Brattli <dag@brattli.net>
* Sources: af_netroom.c, af_ax25.c, af_rose.c, af_x25.c etc.
*
* Copyright (c) 1999 Dag Brattli <dagb@cs.uit.no>
* Copyright (c) 1999-2003 Jean Tourrilhes <jt@hpl.hp.com>
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Linux-IrDA now supports four different types of IrDA sockets:
*
* o SOCK_STREAM: TinyTP connections with SAR disabled. The
* max SDU size is 0 for conn. of this type
* o SOCK_SEQPACKET: TinyTP connections with SAR enabled. TTP may
* fragment the messages, but will preserve
* the message boundaries
* o SOCK_DGRAM: IRDAPROTO_UNITDATA: TinyTP connections with Unitdata
* (unreliable) transfers
* IRDAPROTO_ULTRA: Connectionless and unreliable data
*
********************************************************************/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/net.h>
#include <linux/irda.h>
#include <linux/poll.h>
#include <asm/ioctls.h> /* TIOCOUTQ, TIOCINQ */
#include <asm/uaccess.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/irda/af_irda.h>
static int irda_create(struct net *net, struct socket *sock, int protocol, int kern);
static const struct proto_ops irda_stream_ops;
static const struct proto_ops irda_seqpacket_ops;
static const struct proto_ops irda_dgram_ops;
#ifdef CONFIG_IRDA_ULTRA
static const struct proto_ops irda_ultra_ops;
#define ULTRA_MAX_DATA 382
#endif /* CONFIG_IRDA_ULTRA */
#define IRDA_MAX_HEADER (TTP_MAX_HEADER)
/*
* Function irda_data_indication (instance, sap, skb)
*
* Received some data from TinyTP. Just queue it on the receive queue
*
*/
static int irda_data_indication(void *instance, void *sap, struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
int err;
IRDA_DEBUG(3, "%s()\n", __func__);
self = instance;
sk = instance;
err = sock_queue_rcv_skb(sk, skb);
if (err) {
IRDA_DEBUG(1, "%s(), error: no more mem!\n", __func__);
self->rx_flow = FLOW_STOP;
/* When we return error, TTP will need to requeue the skb */
return err;
}
return 0;
}
/*
* Function irda_disconnect_indication (instance, sap, reason, skb)
*
* Connection has been closed. Check reason to find out why
*
*/
static void irda_disconnect_indication(void *instance, void *sap,
LM_REASON reason, struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
self = instance;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
/* Don't care about it, but let's not leak it */
if(skb)
dev_kfree_skb(skb);
sk = instance;
if (sk == NULL) {
IRDA_DEBUG(0, "%s(%p) : BUG : sk is NULL\n",
__func__, self);
return;
}
/* Prevent race conditions with irda_release() and irda_shutdown() */
bh_lock_sock(sk);
if (!sock_flag(sk, SOCK_DEAD) && sk->sk_state != TCP_CLOSE) {
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
/* Close our TSAP.
* If we leave it open, IrLMP put it back into the list of
* unconnected LSAPs. The problem is that any incoming request
* can then be matched to this socket (and it will be, because
* it is at the head of the list). This would prevent any
* listening socket waiting on the same TSAP to get those
* requests. Some apps forget to close sockets, or hang to it
* a bit too long, so we may stay in this dead state long
* enough to be noticed...
* Note : all socket function do check sk->sk_state, so we are
* safe...
* Jean II
*/
if (self->tsap) {
irttp_close_tsap(self->tsap);
self->tsap = NULL;
}
}
bh_unlock_sock(sk);
/* Note : once we are there, there is not much you want to do
* with the socket anymore, apart from closing it.
* For example, bind() and connect() won't reset sk->sk_err,
* sk->sk_shutdown and sk->sk_flags to valid values...
* Jean II
*/
}
/*
* Function irda_connect_confirm (instance, sap, qos, max_sdu_size, skb)
*
* Connections has been confirmed by the remote device
*
*/
static void irda_connect_confirm(void *instance, void *sap,
struct qos_info *qos,
__u32 max_sdu_size, __u8 max_header_size,
struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
self = instance;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
sk = instance;
if (sk == NULL) {
dev_kfree_skb(skb);
return;
}
dev_kfree_skb(skb);
// Should be ??? skb_queue_tail(&sk->sk_receive_queue, skb);
/* How much header space do we need to reserve */
self->max_header_size = max_header_size;
/* IrTTP max SDU size in transmit direction */
self->max_sdu_size_tx = max_sdu_size;
/* Find out what the largest chunk of data that we can transmit is */
switch (sk->sk_type) {
case SOCK_STREAM:
if (max_sdu_size != 0) {
IRDA_ERROR("%s: max_sdu_size must be 0\n",
__func__);
return;
}
self->max_data_size = irttp_get_max_seg_size(self->tsap);
break;
case SOCK_SEQPACKET:
if (max_sdu_size == 0) {
IRDA_ERROR("%s: max_sdu_size cannot be 0\n",
__func__);
return;
}
self->max_data_size = max_sdu_size;
break;
default:
self->max_data_size = irttp_get_max_seg_size(self->tsap);
}
IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__,
self->max_data_size);
memcpy(&self->qos_tx, qos, sizeof(struct qos_info));
/* We are now connected! */
sk->sk_state = TCP_ESTABLISHED;
sk->sk_state_change(sk);
}
/*
* Function irda_connect_indication(instance, sap, qos, max_sdu_size, userdata)
*
* Incoming connection
*
*/
static void irda_connect_indication(void *instance, void *sap,
struct qos_info *qos, __u32 max_sdu_size,
__u8 max_header_size, struct sk_buff *skb)
{
struct irda_sock *self;
struct sock *sk;
self = instance;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
sk = instance;
if (sk == NULL) {
dev_kfree_skb(skb);
return;
}
/* How much header space do we need to reserve */
self->max_header_size = max_header_size;
/* IrTTP max SDU size in transmit direction */
self->max_sdu_size_tx = max_sdu_size;
/* Find out what the largest chunk of data that we can transmit is */
switch (sk->sk_type) {
case SOCK_STREAM:
if (max_sdu_size != 0) {
IRDA_ERROR("%s: max_sdu_size must be 0\n",
__func__);
kfree_skb(skb);
return;
}
self->max_data_size = irttp_get_max_seg_size(self->tsap);
break;
case SOCK_SEQPACKET:
if (max_sdu_size == 0) {
IRDA_ERROR("%s: max_sdu_size cannot be 0\n",
__func__);
kfree_skb(skb);
return;
}
self->max_data_size = max_sdu_size;
break;
default:
self->max_data_size = irttp_get_max_seg_size(self->tsap);
}
IRDA_DEBUG(2, "%s(), max_data_size=%d\n", __func__,
self->max_data_size);
memcpy(&self->qos_tx, qos, sizeof(struct qos_info));
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_state_change(sk);
}
/*
* Function irda_connect_response (handle)
*
* Accept incoming connection
*
*/
static void irda_connect_response(struct irda_sock *self)
{
struct sk_buff *skb;
IRDA_DEBUG(2, "%s()\n", __func__);
skb = alloc_skb(TTP_MAX_HEADER + TTP_SAR_HEADER, GFP_KERNEL);
if (skb == NULL) {
IRDA_DEBUG(0, "%s() Unable to allocate sk_buff!\n",
__func__);
return;
}
/* Reserve space for MUX_CONTROL and LAP header */
skb_reserve(skb, IRDA_MAX_HEADER);
irttp_connect_response(self->tsap, self->max_sdu_size_rx, skb);
}
/*
* Function irda_flow_indication (instance, sap, flow)
*
* Used by TinyTP to tell us if it can accept more data or not
*
*/
static void irda_flow_indication(void *instance, void *sap, LOCAL_FLOW flow)
{
struct irda_sock *self;
struct sock *sk;
IRDA_DEBUG(2, "%s()\n", __func__);
self = instance;
sk = instance;
BUG_ON(sk == NULL);
switch (flow) {
case FLOW_STOP:
IRDA_DEBUG(1, "%s(), IrTTP wants us to slow down\n",
__func__);
self->tx_flow = flow;
break;
case FLOW_START:
self->tx_flow = flow;
IRDA_DEBUG(1, "%s(), IrTTP wants us to start again\n",
__func__);
wake_up_interruptible(sk_sleep(sk));
break;
default:
IRDA_DEBUG(0, "%s(), Unknown flow command!\n", __func__);
/* Unknown flow command, better stop */
self->tx_flow = flow;
break;
}
}
/*
* Function irda_getvalue_confirm (obj_id, value, priv)
*
* Got answer from remote LM-IAS, just pass object to requester...
*
* Note : duplicate from above, but we need our own version that
* doesn't touch the dtsap_sel and save the full value structure...
*/
static void irda_getvalue_confirm(int result, __u16 obj_id,
struct ias_value *value, void *priv)
{
struct irda_sock *self;
self = priv;
if (!self) {
IRDA_WARNING("%s: lost myself!\n", __func__);
return;
}
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
/* We probably don't need to make any more queries */
iriap_close(self->iriap);
self->iriap = NULL;
/* Check if request succeeded */
if (result != IAS_SUCCESS) {
IRDA_DEBUG(1, "%s(), IAS query failed! (%d)\n", __func__,
result);
self->errno = result; /* We really need it later */
/* Wake up any processes waiting for result */
wake_up_interruptible(&self->query_wait);
return;
}
/* Pass the object to the caller (so the caller must delete it) */
self->ias_result = value;
self->errno = 0;
/* Wake up any processes waiting for result */
wake_up_interruptible(&self->query_wait);
}
/*
* Function irda_selective_discovery_indication (discovery)
*
* Got a selective discovery indication from IrLMP.
*
* IrLMP is telling us that this node is new and matching our hint bit
* filter. Wake up any process waiting for answer...
*/
static void irda_selective_discovery_indication(discinfo_t *discovery,
DISCOVERY_MODE mode,
void *priv)
{
struct irda_sock *self;
IRDA_DEBUG(2, "%s()\n", __func__);
self = priv;
if (!self) {
IRDA_WARNING("%s: lost myself!\n", __func__);
return;
}
/* Pass parameter to the caller */
self->cachedaddr = discovery->daddr;
/* Wake up process if its waiting for device to be discovered */
wake_up_interruptible(&self->query_wait);
}
/*
* Function irda_discovery_timeout (priv)
*
* Timeout in the selective discovery process
*
* We were waiting for a node to be discovered, but nothing has come up
* so far. Wake up the user and tell him that we failed...
*/
static void irda_discovery_timeout(u_long priv)
{
struct irda_sock *self;
IRDA_DEBUG(2, "%s()\n", __func__);
self = (struct irda_sock *) priv;
BUG_ON(self == NULL);
/* Nothing for the caller */
self->cachelog = NULL;
self->cachedaddr = 0;
self->errno = -ETIME;
/* Wake up process if its still waiting... */
wake_up_interruptible(&self->query_wait);
}
/*
* Function irda_open_tsap (self)
*
* Open local Transport Service Access Point (TSAP)
*
*/
static int irda_open_tsap(struct irda_sock *self, __u8 tsap_sel, char *name)
{
notify_t notify;
if (self->tsap) {
IRDA_DEBUG(0, "%s: busy!\n", __func__);
return -EBUSY;
}
/* Initialize callbacks to be used by the IrDA stack */
irda_notify_init(¬ify);
notify.connect_confirm = irda_connect_confirm;
notify.connect_indication = irda_connect_indication;
notify.disconnect_indication = irda_disconnect_indication;
notify.data_indication = irda_data_indication;
notify.udata_indication = irda_data_indication;
notify.flow_indication = irda_flow_indication;
notify.instance = self;
strncpy(notify.name, name, NOTIFY_MAX_NAME);
self->tsap = irttp_open_tsap(tsap_sel, DEFAULT_INITIAL_CREDIT,
¬ify);
if (self->tsap == NULL) {
IRDA_DEBUG(0, "%s(), Unable to allocate TSAP!\n",
__func__);
return -ENOMEM;
}
/* Remember which TSAP selector we actually got */
self->stsap_sel = self->tsap->stsap_sel;
return 0;
}
/*
* Function irda_open_lsap (self)
*
* Open local Link Service Access Point (LSAP). Used for opening Ultra
* sockets
*/
#ifdef CONFIG_IRDA_ULTRA
static int irda_open_lsap(struct irda_sock *self, int pid)
{
notify_t notify;
if (self->lsap) {
IRDA_WARNING("%s(), busy!\n", __func__);
return -EBUSY;
}
/* Initialize callbacks to be used by the IrDA stack */
irda_notify_init(¬ify);
notify.udata_indication = irda_data_indication;
notify.instance = self;
strncpy(notify.name, "Ultra", NOTIFY_MAX_NAME);
self->lsap = irlmp_open_lsap(LSAP_CONNLESS, ¬ify, pid);
if (self->lsap == NULL) {
IRDA_DEBUG( 0, "%s(), Unable to allocate LSAP!\n", __func__);
return -ENOMEM;
}
return 0;
}
#endif /* CONFIG_IRDA_ULTRA */
/*
* Function irda_find_lsap_sel (self, name)
*
* Try to lookup LSAP selector in remote LM-IAS
*
* Basically, we start a IAP query, and then go to sleep. When the query
* return, irda_getvalue_confirm will wake us up, and we can examine the
* result of the query...
* Note that in some case, the query fail even before we go to sleep,
* creating some races...
*/
static int irda_find_lsap_sel(struct irda_sock *self, char *name)
{
IRDA_DEBUG(2, "%s(%p, %s)\n", __func__, self, name);
if (self->iriap) {
IRDA_WARNING("%s(): busy with a previous query\n",
__func__);
return -EBUSY;
}
self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self,
irda_getvalue_confirm);
if(self->iriap == NULL)
return -ENOMEM;
/* Treat unexpected wakeup as disconnect */
self->errno = -EHOSTUNREACH;
/* Query remote LM-IAS */
iriap_getvaluebyclass_request(self->iriap, self->saddr, self->daddr,
name, "IrDA:TinyTP:LsapSel");
/* Wait for answer, if not yet finished (or failed) */
if (wait_event_interruptible(self->query_wait, (self->iriap==NULL)))
/* Treat signals as disconnect */
return -EHOSTUNREACH;
/* Check what happened */
if (self->errno)
{
/* Requested object/attribute doesn't exist */
if((self->errno == IAS_CLASS_UNKNOWN) ||
(self->errno == IAS_ATTRIB_UNKNOWN))
return -EADDRNOTAVAIL;
else
return -EHOSTUNREACH;
}
/* Get the remote TSAP selector */
switch (self->ias_result->type) {
case IAS_INTEGER:
IRDA_DEBUG(4, "%s() int=%d\n",
__func__, self->ias_result->t.integer);
if (self->ias_result->t.integer != -1)
self->dtsap_sel = self->ias_result->t.integer;
else
self->dtsap_sel = 0;
break;
default:
self->dtsap_sel = 0;
IRDA_DEBUG(0, "%s(), bad type!\n", __func__);
break;
}
if (self->ias_result)
irias_delete_value(self->ias_result);
if (self->dtsap_sel)
return 0;
return -EADDRNOTAVAIL;
}
/*
* Function irda_discover_daddr_and_lsap_sel (self, name)
*
* This try to find a device with the requested service.
*
* It basically look into the discovery log. For each address in the list,
* it queries the LM-IAS of the device to find if this device offer
* the requested service.
* If there is more than one node supporting the service, we complain
* to the user (it should move devices around).
* The, we set both the destination address and the lsap selector to point
* on the service on the unique device we have found.
*
* Note : this function fails if there is more than one device in range,
* because IrLMP doesn't disconnect the LAP when the last LSAP is closed.
* Moreover, we would need to wait the LAP disconnection...
*/
static int irda_discover_daddr_and_lsap_sel(struct irda_sock *self, char *name)
{
discinfo_t *discoveries; /* Copy of the discovery log */
int number; /* Number of nodes in the log */
int i;
int err = -ENETUNREACH;
__u32 daddr = DEV_ADDR_ANY; /* Address we found the service on */
__u8 dtsap_sel = 0x0; /* TSAP associated with it */
IRDA_DEBUG(2, "%s(), name=%s\n", __func__, name);
/* Ask lmp for the current discovery log
* Note : we have to use irlmp_get_discoveries(), as opposed
* to play with the cachelog directly, because while we are
* making our ias query, le log might change... */
discoveries = irlmp_get_discoveries(&number, self->mask.word,
self->nslots);
/* Check if the we got some results */
if (discoveries == NULL)
return -ENETUNREACH; /* No nodes discovered */
/*
* Now, check all discovered devices (if any), and connect
* client only about the services that the client is
* interested in...
*/
for(i = 0; i < number; i++) {
/* Try the address in the log */
self->daddr = discoveries[i].daddr;
self->saddr = 0x0;
IRDA_DEBUG(1, "%s(), trying daddr = %08x\n",
__func__, self->daddr);
/* Query remote LM-IAS for this service */
err = irda_find_lsap_sel(self, name);
switch (err) {
case 0:
/* We found the requested service */
if(daddr != DEV_ADDR_ANY) {
IRDA_DEBUG(1, "%s(), discovered service ''%s'' in two different devices !!!\n",
__func__, name);
self->daddr = DEV_ADDR_ANY;
kfree(discoveries);
return -ENOTUNIQ;
}
/* First time we found that one, save it ! */
daddr = self->daddr;
dtsap_sel = self->dtsap_sel;
break;
case -EADDRNOTAVAIL:
/* Requested service simply doesn't exist on this node */
break;
default:
/* Something bad did happen :-( */
IRDA_DEBUG(0, "%s(), unexpected IAS query failure\n", __func__);
self->daddr = DEV_ADDR_ANY;
kfree(discoveries);
return -EHOSTUNREACH;
break;
}
}
/* Cleanup our copy of the discovery log */
kfree(discoveries);
/* Check out what we found */
if(daddr == DEV_ADDR_ANY) {
IRDA_DEBUG(1, "%s(), cannot discover service ''%s'' in any device !!!\n",
__func__, name);
self->daddr = DEV_ADDR_ANY;
return -EADDRNOTAVAIL;
}
/* Revert back to discovered device & service */
self->daddr = daddr;
self->saddr = 0x0;
self->dtsap_sel = dtsap_sel;
IRDA_DEBUG(1, "%s(), discovered requested service ''%s'' at address %08x\n",
__func__, name, self->daddr);
return 0;
}
/*
* Function irda_getname (sock, uaddr, uaddr_len, peer)
*
* Return the our own, or peers socket address (sockaddr_irda)
*
*/
static int irda_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_irda saddr;
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
memset(&saddr, 0, sizeof(saddr));
if (peer) {
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
saddr.sir_family = AF_IRDA;
saddr.sir_lsap_sel = self->dtsap_sel;
saddr.sir_addr = self->daddr;
} else {
saddr.sir_family = AF_IRDA;
saddr.sir_lsap_sel = self->stsap_sel;
saddr.sir_addr = self->saddr;
}
IRDA_DEBUG(1, "%s(), tsap_sel = %#x\n", __func__, saddr.sir_lsap_sel);
IRDA_DEBUG(1, "%s(), addr = %08x\n", __func__, saddr.sir_addr);
/* uaddr_len come to us uninitialised */
*uaddr_len = sizeof (struct sockaddr_irda);
memcpy(uaddr, &saddr, *uaddr_len);
return 0;
}
/*
* Function irda_listen (sock, backlog)
*
* Just move to the listen state
*
*/
static int irda_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int err = -EOPNOTSUPP;
IRDA_DEBUG(2, "%s()\n", __func__);
lock_sock(sk);
if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) &&
(sk->sk_type != SOCK_DGRAM))
goto out;
if (sk->sk_state != TCP_LISTEN) {
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
err = 0;
}
out:
release_sock(sk);
return err;
}
/*
* Function irda_bind (sock, uaddr, addr_len)
*
* Used by servers to register their well known TSAP
*
*/
static int irda_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr;
struct irda_sock *self = irda_sk(sk);
int err;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
if (addr_len != sizeof(struct sockaddr_irda))
return -EINVAL;
lock_sock(sk);
#ifdef CONFIG_IRDA_ULTRA
/* Special care for Ultra sockets */
if ((sk->sk_type == SOCK_DGRAM) &&
(sk->sk_protocol == IRDAPROTO_ULTRA)) {
self->pid = addr->sir_lsap_sel;
err = -EOPNOTSUPP;
if (self->pid & 0x80) {
IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__);
goto out;
}
err = irda_open_lsap(self, self->pid);
if (err < 0)
goto out;
/* Pretend we are connected */
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
err = 0;
goto out;
}
#endif /* CONFIG_IRDA_ULTRA */
self->ias_obj = irias_new_object(addr->sir_name, jiffies);
err = -ENOMEM;
if (self->ias_obj == NULL)
goto out;
err = irda_open_tsap(self, addr->sir_lsap_sel, addr->sir_name);
if (err < 0) {
irias_delete_object(self->ias_obj);
self->ias_obj = NULL;
goto out;
}
/* Register with LM-IAS */
irias_add_integer_attrib(self->ias_obj, "IrDA:TinyTP:LsapSel",
self->stsap_sel, IAS_KERNEL_ATTR);
irias_insert_object(self->ias_obj);
err = 0;
out:
release_sock(sk);
return err;
}
/*
* Function irda_accept (sock, newsock, flags)
*
* Wait for incoming connection
*
*/
static int irda_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *new, *self = irda_sk(sk);
struct sock *newsk;
struct sk_buff *skb;
int err;
IRDA_DEBUG(2, "%s()\n", __func__);
err = irda_create(sock_net(sk), newsock, sk->sk_protocol, 0);
if (err)
return err;
err = -EINVAL;
lock_sock(sk);
if (sock->state != SS_UNCONNECTED)
goto out;
if ((sk = sock->sk) == NULL)
goto out;
err = -EOPNOTSUPP;
if ((sk->sk_type != SOCK_STREAM) && (sk->sk_type != SOCK_SEQPACKET) &&
(sk->sk_type != SOCK_DGRAM))
goto out;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out;
/*
* The read queue this time is holding sockets ready to use
* hooked into the SABM we saved
*/
/*
* We can perform the accept only if there is incoming data
* on the listening socket.
* So, we will block the caller until we receive any data.
* If the caller was waiting on select() or poll() before
* calling us, the data is waiting for us ;-)
* Jean II
*/
while (1) {
skb = skb_dequeue(&sk->sk_receive_queue);
if (skb)
break;
/* Non blocking operation */
err = -EWOULDBLOCK;
if (flags & O_NONBLOCK)
goto out;
err = wait_event_interruptible(*(sk_sleep(sk)),
skb_peek(&sk->sk_receive_queue));
if (err)
goto out;
}
newsk = newsock->sk;
err = -EIO;
if (newsk == NULL)
goto out;
newsk->sk_state = TCP_ESTABLISHED;
new = irda_sk(newsk);
/* Now attach up the new socket */
new->tsap = irttp_dup(self->tsap, new);
err = -EPERM; /* value does not seem to make sense. -arnd */
if (!new->tsap) {
IRDA_DEBUG(0, "%s(), dup failed!\n", __func__);
kfree_skb(skb);
goto out;
}
new->stsap_sel = new->tsap->stsap_sel;
new->dtsap_sel = new->tsap->dtsap_sel;
new->saddr = irttp_get_saddr(new->tsap);
new->daddr = irttp_get_daddr(new->tsap);
new->max_sdu_size_tx = self->max_sdu_size_tx;
new->max_sdu_size_rx = self->max_sdu_size_rx;
new->max_data_size = self->max_data_size;
new->max_header_size = self->max_header_size;
memcpy(&new->qos_tx, &self->qos_tx, sizeof(struct qos_info));
/* Clean up the original one to keep it in listen state */
irttp_listen(self->tsap);
kfree_skb(skb);
sk->sk_ack_backlog--;
newsock->state = SS_CONNECTED;
irda_connect_response(new);
err = 0;
out:
release_sock(sk);
return err;
}
/*
* Function irda_connect (sock, uaddr, addr_len, flags)
*
* Connect to a IrDA device
*
* The main difference with a "standard" connect is that with IrDA we need
* to resolve the service name into a TSAP selector (in TCP, port number
* doesn't have to be resolved).
* Because of this service name resolution, we can offer "auto-connect",
* where we connect to a service without specifying a destination address.
*
* Note : by consulting "errno", the user space caller may learn the cause
* of the failure. Most of them are visible in the function, others may come
* from subroutines called and are listed here :
* o EBUSY : already processing a connect
* o EHOSTUNREACH : bad addr->sir_addr argument
* o EADDRNOTAVAIL : bad addr->sir_name argument
* o ENOTUNIQ : more than one node has addr->sir_name (auto-connect)
* o ENETUNREACH : no node found on the network (auto-connect)
*/
static int irda_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_irda *addr = (struct sockaddr_irda *) uaddr;
struct irda_sock *self = irda_sk(sk);
int err;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
lock_sock(sk);
/* Don't allow connect for Ultra sockets */
err = -ESOCKTNOSUPPORT;
if ((sk->sk_type == SOCK_DGRAM) && (sk->sk_protocol == IRDAPROTO_ULTRA))
goto out;
if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) {
sock->state = SS_CONNECTED;
err = 0;
goto out; /* Connect completed during a ERESTARTSYS event */
}
if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) {
sock->state = SS_UNCONNECTED;
err = -ECONNREFUSED;
goto out;
}
err = -EISCONN; /* No reconnect on a seqpacket socket */
if (sk->sk_state == TCP_ESTABLISHED)
goto out;
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
err = -EINVAL;
if (addr_len != sizeof(struct sockaddr_irda))
goto out;
/* Check if user supplied any destination device address */
if ((!addr->sir_addr) || (addr->sir_addr == DEV_ADDR_ANY)) {
/* Try to find one suitable */
err = irda_discover_daddr_and_lsap_sel(self, addr->sir_name);
if (err) {
IRDA_DEBUG(0, "%s(), auto-connect failed!\n", __func__);
goto out;
}
} else {
/* Use the one provided by the user */
self->daddr = addr->sir_addr;
IRDA_DEBUG(1, "%s(), daddr = %08x\n", __func__, self->daddr);
/* If we don't have a valid service name, we assume the
* user want to connect on a specific LSAP. Prevent
* the use of invalid LSAPs (IrLMP 1.1 p10). Jean II */
if((addr->sir_name[0] != '\0') ||
(addr->sir_lsap_sel >= 0x70)) {
/* Query remote LM-IAS using service name */
err = irda_find_lsap_sel(self, addr->sir_name);
if (err) {
IRDA_DEBUG(0, "%s(), connect failed!\n", __func__);
goto out;
}
} else {
/* Directly connect to the remote LSAP
* specified by the sir_lsap field.
* Please use with caution, in IrDA LSAPs are
* dynamic and there is no "well-known" LSAP. */
self->dtsap_sel = addr->sir_lsap_sel;
}
}
/* Check if we have opened a local TSAP */
if (!self->tsap)
irda_open_tsap(self, LSAP_ANY, addr->sir_name);
/* Move to connecting socket, start sending Connect Requests */
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
/* Connect to remote device */
err = irttp_connect_request(self->tsap, self->dtsap_sel,
self->saddr, self->daddr, NULL,
self->max_sdu_size_rx, NULL);
if (err) {
IRDA_DEBUG(0, "%s(), connect failed!\n", __func__);
goto out;
}
/* Now the loop */
err = -EINPROGRESS;
if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK))
goto out;
err = -ERESTARTSYS;
if (wait_event_interruptible(*(sk_sleep(sk)),
(sk->sk_state != TCP_SYN_SENT)))
goto out;
if (sk->sk_state != TCP_ESTABLISHED) {
sock->state = SS_UNCONNECTED;
if (sk->sk_prot->disconnect(sk, flags))
sock->state = SS_DISCONNECTING;
err = sock_error(sk);
if (!err)
err = -ECONNRESET;
goto out;
}
sock->state = SS_CONNECTED;
/* At this point, IrLMP has assigned our source address */
self->saddr = irttp_get_saddr(self->tsap);
err = 0;
out:
release_sock(sk);
return err;
}
static struct proto irda_proto = {
.name = "IRDA",
.owner = THIS_MODULE,
.obj_size = sizeof(struct irda_sock),
};
/*
* Function irda_create (sock, protocol)
*
* Create IrDA socket
*
*/
static int irda_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct irda_sock *self;
IRDA_DEBUG(2, "%s()\n", __func__);
if (net != &init_net)
return -EAFNOSUPPORT;
/* Check for valid socket type */
switch (sock->type) {
case SOCK_STREAM: /* For TTP connections with SAR disabled */
case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */
case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */
break;
default:
return -ESOCKTNOSUPPORT;
}
/* Allocate networking socket */
sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto);
if (sk == NULL)
return -ENOMEM;
self = irda_sk(sk);
IRDA_DEBUG(2, "%s() : self is %p\n", __func__, self);
init_waitqueue_head(&self->query_wait);
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &irda_stream_ops;
self->max_sdu_size_rx = TTP_SAR_DISABLE;
break;
case SOCK_SEQPACKET:
sock->ops = &irda_seqpacket_ops;
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
case SOCK_DGRAM:
switch (protocol) {
#ifdef CONFIG_IRDA_ULTRA
case IRDAPROTO_ULTRA:
sock->ops = &irda_ultra_ops;
/* Initialise now, because we may send on unbound
* sockets. Jean II */
self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER;
self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER;
break;
#endif /* CONFIG_IRDA_ULTRA */
case IRDAPROTO_UNITDATA:
sock->ops = &irda_dgram_ops;
/* We let Unitdata conn. be like seqpack conn. */
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
/* Initialise networking socket struct */
sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */
sk->sk_family = PF_IRDA;
sk->sk_protocol = protocol;
/* Register as a client with IrLMP */
self->ckey = irlmp_register_client(0, NULL, NULL, NULL);
self->mask.word = 0xffff;
self->rx_flow = self->tx_flow = FLOW_START;
self->nslots = DISCOVERY_DEFAULT_SLOTS;
self->daddr = DEV_ADDR_ANY; /* Until we get connected */
self->saddr = 0x0; /* so IrLMP assign us any link */
return 0;
}
/*
* Function irda_destroy_socket (self)
*
* Destroy socket
*
*/
static void irda_destroy_socket(struct irda_sock *self)
{
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
/* Unregister with IrLMP */
irlmp_unregister_client(self->ckey);
irlmp_unregister_service(self->skey);
/* Unregister with LM-IAS */
if (self->ias_obj) {
irias_delete_object(self->ias_obj);
self->ias_obj = NULL;
}
if (self->iriap) {
iriap_close(self->iriap);
self->iriap = NULL;
}
if (self->tsap) {
irttp_disconnect_request(self->tsap, NULL, P_NORMAL);
irttp_close_tsap(self->tsap);
self->tsap = NULL;
}
#ifdef CONFIG_IRDA_ULTRA
if (self->lsap) {
irlmp_close_lsap(self->lsap);
self->lsap = NULL;
}
#endif /* CONFIG_IRDA_ULTRA */
}
/*
* Function irda_release (sock)
*/
static int irda_release(struct socket *sock)
{
struct sock *sk = sock->sk;
IRDA_DEBUG(2, "%s()\n", __func__);
if (sk == NULL)
return 0;
lock_sock(sk);
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
/* Destroy IrDA socket */
irda_destroy_socket(irda_sk(sk));
sock_orphan(sk);
sock->sk = NULL;
release_sock(sk);
/* Purge queues (see sock_init_data()) */
skb_queue_purge(&sk->sk_receive_queue);
/* Destroy networking socket if we are the last reference on it,
* i.e. if(sk->sk_refcnt == 0) -> sk_free(sk) */
sock_put(sk);
/* Notes on socket locking and deallocation... - Jean II
* In theory we should put pairs of sock_hold() / sock_put() to
* prevent the socket to be destroyed whenever there is an
* outstanding request or outstanding incoming packet or event.
*
* 1) This may include IAS request, both in connect and getsockopt.
* Unfortunately, the situation is a bit more messy than it looks,
* because we close iriap and kfree(self) above.
*
* 2) This may include selective discovery in getsockopt.
* Same stuff as above, irlmp registration and self are gone.
*
* Probably 1 and 2 may not matter, because it's all triggered
* by a process and the socket layer already prevent the
* socket to go away while a process is holding it, through
* sockfd_put() and fput()...
*
* 3) This may include deferred TSAP closure. In particular,
* we may receive a late irda_disconnect_indication()
* Fortunately, (tsap_cb *)->close_pend should protect us
* from that.
*
* I did some testing on SMP, and it looks solid. And the socket
* memory leak is now gone... - Jean II
*/
return 0;
}
/*
* Function irda_sendmsg (iocb, sock, msg, len)
*
* Send message down to TinyTP. This function is used for both STREAM and
* SEQPACK services. This is possible since it forces the client to
* fragment the message if necessary
*/
static int irda_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct irda_sock *self;
struct sk_buff *skb;
int err = -EPIPE;
IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len);
/* Note : socket.c set MSG_EOR on SEQPACKET sockets */
if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_EOR | MSG_CMSG_COMPAT |
MSG_NOSIGNAL)) {
return -EINVAL;
}
lock_sock(sk);
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto out_err;
if (sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
self = irda_sk(sk);
/* Check if IrTTP is wants us to slow down */
if (wait_event_interruptible(*(sk_sleep(sk)),
(self->tx_flow != FLOW_STOP || sk->sk_state != TCP_ESTABLISHED))) {
err = -ERESTARTSYS;
goto out;
}
/* Check if we are still connected */
if (sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
/* Check that we don't send out too big frames */
if (len > self->max_data_size) {
IRDA_DEBUG(2, "%s(), Chopping frame from %zd to %d bytes!\n",
__func__, len, self->max_data_size);
len = self->max_data_size;
}
skb = sock_alloc_send_skb(sk, len + self->max_header_size + 16,
msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb)
goto out_err;
skb_reserve(skb, self->max_header_size + 16);
skb_reset_transport_header(skb);
skb_put(skb, len);
err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (err) {
kfree_skb(skb);
goto out_err;
}
/*
* Just send the message to TinyTP, and let it deal with possible
* errors. No need to duplicate all that here
*/
err = irttp_data_request(self->tsap, skb);
if (err) {
IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err);
goto out_err;
}
release_sock(sk);
/* Tell client how much data we actually sent */
return len;
out_err:
err = sk_stream_error(sk, msg->msg_flags, err);
out:
release_sock(sk);
return err;
}
/*
* Function irda_recvmsg_dgram (iocb, sock, msg, size, flags)
*
* Try to receive message and copy it to user. The frame is discarded
* after being read, regardless of how much the user actually read
*/
static int irda_recvmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct sk_buff *skb;
size_t copied;
int err;
IRDA_DEBUG(4, "%s()\n", __func__);
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
IRDA_DEBUG(2, "%s(), Received truncated frame (%zd < %zd)!\n",
__func__, copied, size);
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
skb_free_datagram(sk, skb);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
/*
* Function irda_recvmsg_stream (iocb, sock, msg, size, flags)
*/
static int irda_recvmsg_stream(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
int noblock = flags & MSG_DONTWAIT;
size_t copied = 0;
int target, err;
long timeo;
IRDA_DEBUG(3, "%s()\n", __func__);
if ((err = sock_error(sk)) < 0)
return err;
if (sock->flags & __SO_ACCEPTCON)
return -EINVAL;
err =-EOPNOTSUPP;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
err = 0;
target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, noblock);
do {
int chunk;
struct sk_buff *skb = skb_dequeue(&sk->sk_receive_queue);
if (skb == NULL) {
DEFINE_WAIT(wait);
err = 0;
if (copied >= target)
break;
prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
;
else if (noblock)
err = -EAGAIN;
else if (signal_pending(current))
err = sock_intr_errno(timeo);
else if (sk->sk_state != TCP_ESTABLISHED)
err = -ENOTCONN;
else if (skb_peek(&sk->sk_receive_queue) == NULL)
/* Wait process until data arrives */
schedule();
finish_wait(sk_sleep(sk), &wait);
if (err)
return err;
if (sk->sk_shutdown & RCV_SHUTDOWN)
break;
continue;
}
chunk = min_t(unsigned int, skb->len, size);
if (memcpy_toiovec(msg->msg_iov, skb->data, chunk)) {
skb_queue_head(&sk->sk_receive_queue, skb);
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
/* put the skb back if we didn't use it up.. */
if (skb->len) {
IRDA_DEBUG(1, "%s(), back on q!\n",
__func__);
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
kfree_skb(skb);
} else {
IRDA_DEBUG(0, "%s() questionable!?\n", __func__);
/* put message back and return */
skb_queue_head(&sk->sk_receive_queue, skb);
break;
}
} while (size);
/*
* Check if we have previously stopped IrTTP and we know
* have more free space in our rx_queue. If so tell IrTTP
* to start delivering frames again before our rx_queue gets
* empty
*/
if (self->rx_flow == FLOW_STOP) {
if ((atomic_read(&sk->sk_rmem_alloc) << 2) <= sk->sk_rcvbuf) {
IRDA_DEBUG(2, "%s(), Starting IrTTP\n", __func__);
self->rx_flow = FLOW_START;
irttp_flow_request(self->tsap, FLOW_START);
}
}
return copied;
}
/*
* Function irda_sendmsg_dgram (iocb, sock, msg, len)
*
* Send message down to TinyTP for the unreliable sequenced
* packet service...
*
*/
static int irda_sendmsg_dgram(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct irda_sock *self;
struct sk_buff *skb;
int err;
IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len);
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT))
return -EINVAL;
lock_sock(sk);
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
goto out;
}
err = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
self = irda_sk(sk);
/*
* Check that we don't send out too big frames. This is an unreliable
* service, so we have no fragmentation and no coalescence
*/
if (len > self->max_data_size) {
IRDA_DEBUG(0, "%s(), Warning to much data! "
"Chopping frame from %zd to %d bytes!\n",
__func__, len, self->max_data_size);
len = self->max_data_size;
}
skb = sock_alloc_send_skb(sk, len + self->max_header_size,
msg->msg_flags & MSG_DONTWAIT, &err);
err = -ENOBUFS;
if (!skb)
goto out;
skb_reserve(skb, self->max_header_size);
skb_reset_transport_header(skb);
IRDA_DEBUG(4, "%s(), appending user data\n", __func__);
skb_put(skb, len);
err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (err) {
kfree_skb(skb);
goto out;
}
/*
* Just send the message to TinyTP, and let it deal with possible
* errors. No need to duplicate all that here
*/
err = irttp_udata_request(self->tsap, skb);
if (err) {
IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err);
goto out;
}
release_sock(sk);
return len;
out:
release_sock(sk);
return err;
}
/*
* Function irda_sendmsg_ultra (iocb, sock, msg, len)
*
* Send message down to IrLMP for the unreliable Ultra
* packet service...
*/
#ifdef CONFIG_IRDA_ULTRA
static int irda_sendmsg_ultra(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct irda_sock *self;
__u8 pid = 0;
int bound = 0;
struct sk_buff *skb;
int err;
IRDA_DEBUG(4, "%s(), len=%zd\n", __func__, len);
err = -EINVAL;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT))
return -EINVAL;
lock_sock(sk);
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
goto out;
}
self = irda_sk(sk);
/* Check if an address was specified with sendto. Jean II */
if (msg->msg_name) {
struct sockaddr_irda *addr = (struct sockaddr_irda *) msg->msg_name;
err = -EINVAL;
/* Check address, extract pid. Jean II */
if (msg->msg_namelen < sizeof(*addr))
goto out;
if (addr->sir_family != AF_IRDA)
goto out;
pid = addr->sir_lsap_sel;
if (pid & 0x80) {
IRDA_DEBUG(0, "%s(), extension in PID not supp!\n", __func__);
err = -EOPNOTSUPP;
goto out;
}
} else {
/* Check that the socket is properly bound to an Ultra
* port. Jean II */
if ((self->lsap == NULL) ||
(sk->sk_state != TCP_ESTABLISHED)) {
IRDA_DEBUG(0, "%s(), socket not bound to Ultra PID.\n",
__func__);
err = -ENOTCONN;
goto out;
}
/* Use PID from socket */
bound = 1;
}
/*
* Check that we don't send out too big frames. This is an unreliable
* service, so we have no fragmentation and no coalescence
*/
if (len > self->max_data_size) {
IRDA_DEBUG(0, "%s(), Warning to much data! "
"Chopping frame from %zd to %d bytes!\n",
__func__, len, self->max_data_size);
len = self->max_data_size;
}
skb = sock_alloc_send_skb(sk, len + self->max_header_size,
msg->msg_flags & MSG_DONTWAIT, &err);
err = -ENOBUFS;
if (!skb)
goto out;
skb_reserve(skb, self->max_header_size);
skb_reset_transport_header(skb);
IRDA_DEBUG(4, "%s(), appending user data\n", __func__);
skb_put(skb, len);
err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (err) {
kfree_skb(skb);
goto out;
}
err = irlmp_connless_data_request((bound ? self->lsap : NULL),
skb, pid);
if (err)
IRDA_DEBUG(0, "%s(), err=%d\n", __func__, err);
out:
release_sock(sk);
return err ? : len;
}
#endif /* CONFIG_IRDA_ULTRA */
/*
* Function irda_shutdown (sk, how)
*/
static int irda_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
IRDA_DEBUG(1, "%s(%p)\n", __func__, self);
lock_sock(sk);
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
if (self->iriap) {
iriap_close(self->iriap);
self->iriap = NULL;
}
if (self->tsap) {
irttp_disconnect_request(self->tsap, NULL, P_NORMAL);
irttp_close_tsap(self->tsap);
self->tsap = NULL;
}
/* A few cleanup so the socket look as good as new... */
self->rx_flow = self->tx_flow = FLOW_START; /* needed ??? */
self->daddr = DEV_ADDR_ANY; /* Until we get re-connected */
self->saddr = 0x0; /* so IrLMP assign us any link */
release_sock(sk);
return 0;
}
/*
* Function irda_poll (file, sock, wait)
*/
static unsigned int irda_poll(struct file * file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
unsigned int mask;
IRDA_DEBUG(4, "%s()\n", __func__);
poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* Exceptional events? */
if (sk->sk_err)
mask |= POLLERR;
if (sk->sk_shutdown & RCV_SHUTDOWN) {
IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__);
mask |= POLLHUP;
}
/* Readable? */
if (!skb_queue_empty(&sk->sk_receive_queue)) {
IRDA_DEBUG(4, "Socket is readable\n");
mask |= POLLIN | POLLRDNORM;
}
/* Connection-based need to check for termination and startup */
switch (sk->sk_type) {
case SOCK_STREAM:
if (sk->sk_state == TCP_CLOSE) {
IRDA_DEBUG(0, "%s(), POLLHUP\n", __func__);
mask |= POLLHUP;
}
if (sk->sk_state == TCP_ESTABLISHED) {
if ((self->tx_flow == FLOW_START) &&
sock_writeable(sk))
{
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
}
}
break;
case SOCK_SEQPACKET:
if ((self->tx_flow == FLOW_START) &&
sock_writeable(sk))
{
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
}
break;
case SOCK_DGRAM:
if (sock_writeable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
break;
default:
break;
}
return mask;
}
/*
* Function irda_ioctl (sock, cmd, arg)
*/
static int irda_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
int err;
IRDA_DEBUG(4, "%s(), cmd=%#x\n", __func__, cmd);
err = -EINVAL;
switch (cmd) {
case TIOCOUTQ: {
long amount;
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
err = put_user(amount, (unsigned int __user *)arg);
break;
}
case TIOCINQ: {
struct sk_buff *skb;
long amount = 0L;
/* These two are safe on a single CPU system as only user tasks fiddle here */
if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL)
amount = skb->len;
err = put_user(amount, (unsigned int __user *)arg);
break;
}
case SIOCGSTAMP:
if (sk != NULL)
err = sock_get_timestamp(sk, (struct timeval __user *)arg);
break;
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
break;
default:
IRDA_DEBUG(1, "%s(), doing device ioctl!\n", __func__);
err = -ENOIOCTLCMD;
}
return err;
}
#ifdef CONFIG_COMPAT
/*
* Function irda_ioctl (sock, cmd, arg)
*/
static int irda_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
/*
* All IRDA's ioctl are standard ones.
*/
return -ENOIOCTLCMD;
}
#endif
/*
* Function irda_setsockopt (sock, level, optname, optval, optlen)
*
* Set some options for the socket
*
*/
static int irda_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct irda_ias_set *ias_opt;
struct ias_object *ias_obj;
struct ias_attrib * ias_attr; /* Attribute in IAS object */
int opt, free_ias = 0, err = 0;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
if (level != SOL_IRLMP)
return -ENOPROTOOPT;
lock_sock(sk);
switch (optname) {
case IRLMP_IAS_SET:
/* The user want to add an attribute to an existing IAS object
* (in the IAS database) or to create a new object with this
* attribute.
* We first query IAS to know if the object exist, and then
* create the right attribute...
*/
if (optlen != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, optlen)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Find the object we target.
* If the user gives us an empty string, we use the object
* associated with this socket. This will workaround
* duplicated class name - Jean II */
if(ias_opt->irda_class_name[0] == '\0') {
if(self->ias_obj == NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
ias_obj = self->ias_obj;
} else
ias_obj = irias_find_object(ias_opt->irda_class_name);
/* Only ROOT can mess with the global IAS database.
* Users can only add attributes to the object associated
* with the socket they own - Jean II */
if((!capable(CAP_NET_ADMIN)) &&
((ias_obj == NULL) || (ias_obj != self->ias_obj))) {
kfree(ias_opt);
err = -EPERM;
goto out;
}
/* If the object doesn't exist, create it */
if(ias_obj == (struct ias_object *) NULL) {
/* Create a new object */
ias_obj = irias_new_object(ias_opt->irda_class_name,
jiffies);
if (ias_obj == NULL) {
kfree(ias_opt);
err = -ENOMEM;
goto out;
}
free_ias = 1;
}
/* Do we have the attribute already ? */
if(irias_find_attrib(ias_obj, ias_opt->irda_attrib_name)) {
kfree(ias_opt);
if (free_ias) {
kfree(ias_obj->name);
kfree(ias_obj);
}
err = -EINVAL;
goto out;
}
/* Look at the type */
switch(ias_opt->irda_attrib_type) {
case IAS_INTEGER:
/* Add an integer attribute */
irias_add_integer_attrib(
ias_obj,
ias_opt->irda_attrib_name,
ias_opt->attribute.irda_attrib_int,
IAS_USER_ATTR);
break;
case IAS_OCT_SEQ:
/* Check length */
if(ias_opt->attribute.irda_attrib_octet_seq.len >
IAS_MAX_OCTET_STRING) {
kfree(ias_opt);
if (free_ias) {
kfree(ias_obj->name);
kfree(ias_obj);
}
err = -EINVAL;
goto out;
}
/* Add an octet sequence attribute */
irias_add_octseq_attrib(
ias_obj,
ias_opt->irda_attrib_name,
ias_opt->attribute.irda_attrib_octet_seq.octet_seq,
ias_opt->attribute.irda_attrib_octet_seq.len,
IAS_USER_ATTR);
break;
case IAS_STRING:
/* Should check charset & co */
/* Check length */
/* The length is encoded in a __u8, and
* IAS_MAX_STRING == 256, so there is no way
* userspace can pass us a string too large.
* Jean II */
/* NULL terminate the string (avoid troubles) */
ias_opt->attribute.irda_attrib_string.string[ias_opt->attribute.irda_attrib_string.len] = '\0';
/* Add a string attribute */
irias_add_string_attrib(
ias_obj,
ias_opt->irda_attrib_name,
ias_opt->attribute.irda_attrib_string.string,
IAS_USER_ATTR);
break;
default :
kfree(ias_opt);
if (free_ias) {
kfree(ias_obj->name);
kfree(ias_obj);
}
err = -EINVAL;
goto out;
}
irias_insert_object(ias_obj);
kfree(ias_opt);
break;
case IRLMP_IAS_DEL:
/* The user want to delete an object from our local IAS
* database. We just need to query the IAS, check is the
* object is not owned by the kernel and delete it.
*/
if (optlen != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, optlen)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Find the object we target.
* If the user gives us an empty string, we use the object
* associated with this socket. This will workaround
* duplicated class name - Jean II */
if(ias_opt->irda_class_name[0] == '\0')
ias_obj = self->ias_obj;
else
ias_obj = irias_find_object(ias_opt->irda_class_name);
if(ias_obj == (struct ias_object *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Only ROOT can mess with the global IAS database.
* Users can only del attributes from the object associated
* with the socket they own - Jean II */
if((!capable(CAP_NET_ADMIN)) &&
((ias_obj == NULL) || (ias_obj != self->ias_obj))) {
kfree(ias_opt);
err = -EPERM;
goto out;
}
/* Find the attribute (in the object) we target */
ias_attr = irias_find_attrib(ias_obj,
ias_opt->irda_attrib_name);
if(ias_attr == (struct ias_attrib *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Check is the user space own the object */
if(ias_attr->value->owner != IAS_USER_ATTR) {
IRDA_DEBUG(1, "%s(), attempting to delete a kernel attribute\n", __func__);
kfree(ias_opt);
err = -EPERM;
goto out;
}
/* Remove the attribute (and maybe the object) */
irias_delete_attrib(ias_obj, ias_attr, 1);
kfree(ias_opt);
break;
case IRLMP_MAX_SDU_SIZE:
if (optlen < sizeof(int)) {
err = -EINVAL;
goto out;
}
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Only possible for a seqpacket service (TTP with SAR) */
if (sk->sk_type != SOCK_SEQPACKET) {
IRDA_DEBUG(2, "%s(), setting max_sdu_size = %d\n",
__func__, opt);
self->max_sdu_size_rx = opt;
} else {
IRDA_WARNING("%s: not allowed to set MAXSDUSIZE for this socket type!\n",
__func__);
err = -ENOPROTOOPT;
goto out;
}
break;
case IRLMP_HINTS_SET:
if (optlen < sizeof(int)) {
err = -EINVAL;
goto out;
}
/* The input is really a (__u8 hints[2]), easier as an int */
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Unregister any old registration */
if (self->skey)
irlmp_unregister_service(self->skey);
self->skey = irlmp_register_service((__u16) opt);
break;
case IRLMP_HINT_MASK_SET:
/* As opposed to the previous case which set the hint bits
* that we advertise, this one set the filter we use when
* making a discovery (nodes which don't match any hint
* bit in the mask are not reported).
*/
if (optlen < sizeof(int)) {
err = -EINVAL;
goto out;
}
/* The input is really a (__u8 hints[2]), easier as an int */
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Set the new hint mask */
self->mask.word = (__u16) opt;
/* Mask out extension bits */
self->mask.word &= 0x7f7f;
/* Check if no bits */
if(!self->mask.word)
self->mask.word = 0xFFFF;
break;
default:
err = -ENOPROTOOPT;
break;
}
out:
release_sock(sk);
return err;
}
/*
* Function irda_extract_ias_value(ias_opt, ias_value)
*
* Translate internal IAS value structure to the user space representation
*
* The external representation of IAS values, as we exchange them with
* user space program is quite different from the internal representation,
* as stored in the IAS database (because we need a flat structure for
* crossing kernel boundary).
* This function transform the former in the latter. We also check
* that the value type is valid.
*/
static int irda_extract_ias_value(struct irda_ias_set *ias_opt,
struct ias_value *ias_value)
{
/* Look at the type */
switch (ias_value->type) {
case IAS_INTEGER:
/* Copy the integer */
ias_opt->attribute.irda_attrib_int = ias_value->t.integer;
break;
case IAS_OCT_SEQ:
/* Set length */
ias_opt->attribute.irda_attrib_octet_seq.len = ias_value->len;
/* Copy over */
memcpy(ias_opt->attribute.irda_attrib_octet_seq.octet_seq,
ias_value->t.oct_seq, ias_value->len);
break;
case IAS_STRING:
/* Set length */
ias_opt->attribute.irda_attrib_string.len = ias_value->len;
ias_opt->attribute.irda_attrib_string.charset = ias_value->charset;
/* Copy over */
memcpy(ias_opt->attribute.irda_attrib_string.string,
ias_value->t.string, ias_value->len);
/* NULL terminate the string (avoid troubles) */
ias_opt->attribute.irda_attrib_string.string[ias_value->len] = '\0';
break;
case IAS_MISSING:
default :
return -EINVAL;
}
/* Copy type over */
ias_opt->irda_attrib_type = ias_value->type;
return 0;
}
/*
* Function irda_getsockopt (sock, level, optname, optval, optlen)
*/
static int irda_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct irda_sock *self = irda_sk(sk);
struct irda_device_list list;
struct irda_device_info *discoveries;
struct irda_ias_set * ias_opt; /* IAS get/query params */
struct ias_object * ias_obj; /* Object in IAS */
struct ias_attrib * ias_attr; /* Attribute in IAS object */
int daddr = DEV_ADDR_ANY; /* Dest address for IAS queries */
int val = 0;
int len = 0;
int err = 0;
int offset, total;
IRDA_DEBUG(2, "%s(%p)\n", __func__, self);
if (level != SOL_IRLMP)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if(len < 0)
return -EINVAL;
lock_sock(sk);
switch (optname) {
case IRLMP_ENUMDEVICES:
/* Offset to first device entry */
offset = sizeof(struct irda_device_list) -
sizeof(struct irda_device_info);
if (len < offset) {
err = -EINVAL;
goto out;
}
/* Ask lmp for the current discovery log */
discoveries = irlmp_get_discoveries(&list.len, self->mask.word,
self->nslots);
/* Check if the we got some results */
if (discoveries == NULL) {
err = -EAGAIN;
goto out; /* Didn't find any devices */
}
/* Write total list length back to client */
if (copy_to_user(optval, &list, offset))
err = -EFAULT;
/* Copy the list itself - watch for overflow */
if (list.len > 2048) {
err = -EINVAL;
goto bed;
}
total = offset + (list.len * sizeof(struct irda_device_info));
if (total > len)
total = len;
if (copy_to_user(optval+offset, discoveries, total - offset))
err = -EFAULT;
/* Write total number of bytes used back to client */
if (put_user(total, optlen))
err = -EFAULT;
bed:
/* Free up our buffer */
kfree(discoveries);
break;
case IRLMP_MAX_SDU_SIZE:
val = self->max_data_size;
len = sizeof(int);
if (put_user(len, optlen)) {
err = -EFAULT;
goto out;
}
if (copy_to_user(optval, &val, len)) {
err = -EFAULT;
goto out;
}
break;
case IRLMP_IAS_GET:
/* The user want an object from our local IAS database.
* We just need to query the IAS and return the value
* that we found */
/* Check that the user has allocated the right space for us */
if (len != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, len)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Find the object we target.
* If the user gives us an empty string, we use the object
* associated with this socket. This will workaround
* duplicated class name - Jean II */
if(ias_opt->irda_class_name[0] == '\0')
ias_obj = self->ias_obj;
else
ias_obj = irias_find_object(ias_opt->irda_class_name);
if(ias_obj == (struct ias_object *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Find the attribute (in the object) we target */
ias_attr = irias_find_attrib(ias_obj,
ias_opt->irda_attrib_name);
if(ias_attr == (struct ias_attrib *) NULL) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
/* Translate from internal to user structure */
err = irda_extract_ias_value(ias_opt, ias_attr->value);
if(err) {
kfree(ias_opt);
goto out;
}
/* Copy reply to the user */
if (copy_to_user(optval, ias_opt,
sizeof(struct irda_ias_set))) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Note : don't need to put optlen, we checked it */
kfree(ias_opt);
break;
case IRLMP_IAS_QUERY:
/* The user want an object from a remote IAS database.
* We need to use IAP to query the remote database and
* then wait for the answer to come back. */
/* Check that the user has allocated the right space for us */
if (len != sizeof(struct irda_ias_set)) {
err = -EINVAL;
goto out;
}
ias_opt = kmalloc(sizeof(struct irda_ias_set), GFP_ATOMIC);
if (ias_opt == NULL) {
err = -ENOMEM;
goto out;
}
/* Copy query to the driver. */
if (copy_from_user(ias_opt, optval, len)) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* At this point, there are two cases...
* 1) the socket is connected - that's the easy case, we
* just query the device we are connected to...
* 2) the socket is not connected - the user doesn't want
* to connect and/or may not have a valid service name
* (so can't create a fake connection). In this case,
* we assume that the user pass us a valid destination
* address in the requesting structure...
*/
if(self->daddr != DEV_ADDR_ANY) {
/* We are connected - reuse known daddr */
daddr = self->daddr;
} else {
/* We are not connected, we must specify a valid
* destination address */
daddr = ias_opt->daddr;
if((!daddr) || (daddr == DEV_ADDR_ANY)) {
kfree(ias_opt);
err = -EINVAL;
goto out;
}
}
/* Check that we can proceed with IAP */
if (self->iriap) {
IRDA_WARNING("%s: busy with a previous query\n",
__func__);
kfree(ias_opt);
err = -EBUSY;
goto out;
}
self->iriap = iriap_open(LSAP_ANY, IAS_CLIENT, self,
irda_getvalue_confirm);
if (self->iriap == NULL) {
kfree(ias_opt);
err = -ENOMEM;
goto out;
}
/* Treat unexpected wakeup as disconnect */
self->errno = -EHOSTUNREACH;
/* Query remote LM-IAS */
iriap_getvaluebyclass_request(self->iriap,
self->saddr, daddr,
ias_opt->irda_class_name,
ias_opt->irda_attrib_name);
/* Wait for answer, if not yet finished (or failed) */
if (wait_event_interruptible(self->query_wait,
(self->iriap == NULL))) {
/* pending request uses copy of ias_opt-content
* we can free it regardless! */
kfree(ias_opt);
/* Treat signals as disconnect */
err = -EHOSTUNREACH;
goto out;
}
/* Check what happened */
if (self->errno)
{
kfree(ias_opt);
/* Requested object/attribute doesn't exist */
if((self->errno == IAS_CLASS_UNKNOWN) ||
(self->errno == IAS_ATTRIB_UNKNOWN))
err = -EADDRNOTAVAIL;
else
err = -EHOSTUNREACH;
goto out;
}
/* Translate from internal to user structure */
err = irda_extract_ias_value(ias_opt, self->ias_result);
if (self->ias_result)
irias_delete_value(self->ias_result);
if (err) {
kfree(ias_opt);
goto out;
}
/* Copy reply to the user */
if (copy_to_user(optval, ias_opt,
sizeof(struct irda_ias_set))) {
kfree(ias_opt);
err = -EFAULT;
goto out;
}
/* Note : don't need to put optlen, we checked it */
kfree(ias_opt);
break;
case IRLMP_WAITDEVICE:
/* This function is just another way of seeing life ;-)
* IRLMP_ENUMDEVICES assumes that you have a static network,
* and that you just want to pick one of the devices present.
* On the other hand, in here we assume that no device is
* present and that at some point in the future a device will
* come into range. When this device arrive, we just wake
* up the caller, so that he has time to connect to it before
* the device goes away...
* Note : once the node has been discovered for more than a
* few second, it won't trigger this function, unless it
* goes away and come back changes its hint bits (so we
* might call it IRLMP_WAITNEWDEVICE).
*/
/* Check that the user is passing us an int */
if (len != sizeof(int)) {
err = -EINVAL;
goto out;
}
/* Get timeout in ms (max time we block the caller) */
if (get_user(val, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
/* Tell IrLMP we want to be notified */
irlmp_update_client(self->ckey, self->mask.word,
irda_selective_discovery_indication,
NULL, (void *) self);
/* Do some discovery (and also return cached results) */
irlmp_discovery_request(self->nslots);
/* Wait until a node is discovered */
if (!self->cachedaddr) {
IRDA_DEBUG(1, "%s(), nothing discovered yet, going to sleep...\n", __func__);
/* Set watchdog timer to expire in <val> ms. */
self->errno = 0;
setup_timer(&self->watchdog, irda_discovery_timeout,
(unsigned long)self);
mod_timer(&self->watchdog,
jiffies + msecs_to_jiffies(val));
/* Wait for IR-LMP to call us back */
err = __wait_event_interruptible(self->query_wait,
(self->cachedaddr != 0 || self->errno == -ETIME));
/* If watchdog is still activated, kill it! */
del_timer(&(self->watchdog));
IRDA_DEBUG(1, "%s(), ...waking up !\n", __func__);
if (err != 0)
goto out;
}
else
IRDA_DEBUG(1, "%s(), found immediately !\n",
__func__);
/* Tell IrLMP that we have been notified */
irlmp_update_client(self->ckey, self->mask.word,
NULL, NULL, NULL);
/* Check if the we got some results */
if (!self->cachedaddr) {
err = -EAGAIN; /* Didn't find any devices */
goto out;
}
daddr = self->cachedaddr;
/* Cleanup */
self->cachedaddr = 0;
/* We return the daddr of the device that trigger the
* wakeup. As irlmp pass us only the new devices, we
* are sure that it's not an old device.
* If the user want more details, he should query
* the whole discovery log and pick one device...
*/
if (put_user(daddr, (int __user *)optval)) {
err = -EFAULT;
goto out;
}
break;
default:
err = -ENOPROTOOPT;
}
out:
release_sock(sk);
return err;
}
static const struct net_proto_family irda_family_ops = {
.family = PF_IRDA,
.create = irda_create,
.owner = THIS_MODULE,
};
static const struct proto_ops irda_stream_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = irda_connect,
.socketpair = sock_no_socketpair,
.accept = irda_accept,
.getname = irda_getname,
.poll = irda_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = irda_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg,
.recvmsg = irda_recvmsg_stream,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops irda_seqpacket_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = irda_connect,
.socketpair = sock_no_socketpair,
.accept = irda_accept,
.getname = irda_getname,
.poll = datagram_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = irda_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg,
.recvmsg = irda_recvmsg_dgram,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops irda_dgram_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = irda_connect,
.socketpair = sock_no_socketpair,
.accept = irda_accept,
.getname = irda_getname,
.poll = datagram_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = irda_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg_dgram,
.recvmsg = irda_recvmsg_dgram,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
#ifdef CONFIG_IRDA_ULTRA
static const struct proto_ops irda_ultra_ops = {
.family = PF_IRDA,
.owner = THIS_MODULE,
.release = irda_release,
.bind = irda_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = irda_getname,
.poll = datagram_poll,
.ioctl = irda_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = irda_compat_ioctl,
#endif
.listen = sock_no_listen,
.shutdown = irda_shutdown,
.setsockopt = irda_setsockopt,
.getsockopt = irda_getsockopt,
.sendmsg = irda_sendmsg_ultra,
.recvmsg = irda_recvmsg_dgram,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
#endif /* CONFIG_IRDA_ULTRA */
/*
* Function irsock_init (pro)
*
* Initialize IrDA protocol
*
*/
int __init irsock_init(void)
{
int rc = proto_register(&irda_proto, 0);
if (rc == 0)
rc = sock_register(&irda_family_ops);
return rc;
}
/*
* Function irsock_cleanup (void)
*
* Remove IrDA protocol
*
*/
void irsock_cleanup(void)
{
sock_unregister(PF_IRDA);
proto_unregister(&irda_proto);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_16 |
crossvul-cpp_data_good_5845_7 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk)
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
* Copyright (C) Darryl Miles G7LED (dlm@g7led.demon.co.uk)
* Copyright (C) Steven Whitehouse GW7RRM (stevew@acm.org)
* Copyright (C) Joerg Reuter DL1BKE (jreuter@yaina.de)
* Copyright (C) Hans-Joachim Hetscher DD8NE (dd8ne@bnv-bamberg.de)
* Copyright (C) Hans Alblas PE1AYX (hans@esrac.ele.tue.nl)
* Copyright (C) Frederic Rible F1OAT (frible@teaser.fr)
*/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/slab.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/termios.h> /* For TIOCINQ/OUTQ */
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/netfilter.h>
#include <linux/sysctl.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <net/net_namespace.h>
#include <net/tcp_states.h>
#include <net/ip.h>
#include <net/arp.h>
HLIST_HEAD(ax25_list);
DEFINE_SPINLOCK(ax25_list_lock);
static const struct proto_ops ax25_proto_ops;
static void ax25_free_sock(struct sock *sk)
{
ax25_cb_put(ax25_sk(sk));
}
/*
* Socket removal during an interrupt is now safe.
*/
static void ax25_cb_del(ax25_cb *ax25)
{
if (!hlist_unhashed(&ax25->ax25_node)) {
spin_lock_bh(&ax25_list_lock);
hlist_del_init(&ax25->ax25_node);
spin_unlock_bh(&ax25_list_lock);
ax25_cb_put(ax25);
}
}
/*
* Kill all bound sockets on a dropped device.
*/
static void ax25_kill_by_device(struct net_device *dev)
{
ax25_dev *ax25_dev;
ax25_cb *s;
if ((ax25_dev = ax25_dev_ax25dev(dev)) == NULL)
return;
spin_lock_bh(&ax25_list_lock);
again:
ax25_for_each(s, &ax25_list) {
if (s->ax25_dev == ax25_dev) {
s->ax25_dev = NULL;
spin_unlock_bh(&ax25_list_lock);
ax25_disconnect(s, ENETUNREACH);
spin_lock_bh(&ax25_list_lock);
/* The entry could have been deleted from the
* list meanwhile and thus the next pointer is
* no longer valid. Play it safe and restart
* the scan. Forward progress is ensured
* because we set s->ax25_dev to NULL and we
* are never passed a NULL 'dev' argument.
*/
goto again;
}
}
spin_unlock_bh(&ax25_list_lock);
}
/*
* Handle device status changes.
*/
static int ax25_device_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
/* Reject non AX.25 devices */
if (dev->type != ARPHRD_AX25)
return NOTIFY_DONE;
switch (event) {
case NETDEV_UP:
ax25_dev_device_up(dev);
break;
case NETDEV_DOWN:
ax25_kill_by_device(dev);
ax25_rt_device_down(dev);
ax25_dev_device_down(dev);
break;
default:
break;
}
return NOTIFY_DONE;
}
/*
* Add a socket to the bound sockets list.
*/
void ax25_cb_add(ax25_cb *ax25)
{
spin_lock_bh(&ax25_list_lock);
ax25_cb_hold(ax25);
hlist_add_head(&ax25->ax25_node, &ax25_list);
spin_unlock_bh(&ax25_list_lock);
}
/*
* Find a socket that wants to accept the SABM we have just
* received.
*/
struct sock *ax25_find_listener(ax25_address *addr, int digi,
struct net_device *dev, int type)
{
ax25_cb *s;
spin_lock(&ax25_list_lock);
ax25_for_each(s, &ax25_list) {
if ((s->iamdigi && !digi) || (!s->iamdigi && digi))
continue;
if (s->sk && !ax25cmp(&s->source_addr, addr) &&
s->sk->sk_type == type && s->sk->sk_state == TCP_LISTEN) {
/* If device is null we match any device */
if (s->ax25_dev == NULL || s->ax25_dev->dev == dev) {
sock_hold(s->sk);
spin_unlock(&ax25_list_lock);
return s->sk;
}
}
}
spin_unlock(&ax25_list_lock);
return NULL;
}
/*
* Find an AX.25 socket given both ends.
*/
struct sock *ax25_get_socket(ax25_address *my_addr, ax25_address *dest_addr,
int type)
{
struct sock *sk = NULL;
ax25_cb *s;
spin_lock(&ax25_list_lock);
ax25_for_each(s, &ax25_list) {
if (s->sk && !ax25cmp(&s->source_addr, my_addr) &&
!ax25cmp(&s->dest_addr, dest_addr) &&
s->sk->sk_type == type) {
sk = s->sk;
sock_hold(sk);
break;
}
}
spin_unlock(&ax25_list_lock);
return sk;
}
/*
* Find an AX.25 control block given both ends. It will only pick up
* floating AX.25 control blocks or non Raw socket bound control blocks.
*/
ax25_cb *ax25_find_cb(ax25_address *src_addr, ax25_address *dest_addr,
ax25_digi *digi, struct net_device *dev)
{
ax25_cb *s;
spin_lock_bh(&ax25_list_lock);
ax25_for_each(s, &ax25_list) {
if (s->sk && s->sk->sk_type != SOCK_SEQPACKET)
continue;
if (s->ax25_dev == NULL)
continue;
if (ax25cmp(&s->source_addr, src_addr) == 0 && ax25cmp(&s->dest_addr, dest_addr) == 0 && s->ax25_dev->dev == dev) {
if (digi != NULL && digi->ndigi != 0) {
if (s->digipeat == NULL)
continue;
if (ax25digicmp(s->digipeat, digi) != 0)
continue;
} else {
if (s->digipeat != NULL && s->digipeat->ndigi != 0)
continue;
}
ax25_cb_hold(s);
spin_unlock_bh(&ax25_list_lock);
return s;
}
}
spin_unlock_bh(&ax25_list_lock);
return NULL;
}
EXPORT_SYMBOL(ax25_find_cb);
void ax25_send_to_raw(ax25_address *addr, struct sk_buff *skb, int proto)
{
ax25_cb *s;
struct sk_buff *copy;
spin_lock(&ax25_list_lock);
ax25_for_each(s, &ax25_list) {
if (s->sk != NULL && ax25cmp(&s->source_addr, addr) == 0 &&
s->sk->sk_type == SOCK_RAW &&
s->sk->sk_protocol == proto &&
s->ax25_dev->dev == skb->dev &&
atomic_read(&s->sk->sk_rmem_alloc) <= s->sk->sk_rcvbuf) {
if ((copy = skb_clone(skb, GFP_ATOMIC)) == NULL)
continue;
if (sock_queue_rcv_skb(s->sk, copy) != 0)
kfree_skb(copy);
}
}
spin_unlock(&ax25_list_lock);
}
/*
* Deferred destroy.
*/
void ax25_destroy_socket(ax25_cb *);
/*
* Handler for deferred kills.
*/
static void ax25_destroy_timer(unsigned long data)
{
ax25_cb *ax25=(ax25_cb *)data;
struct sock *sk;
sk=ax25->sk;
bh_lock_sock(sk);
sock_hold(sk);
ax25_destroy_socket(ax25);
bh_unlock_sock(sk);
sock_put(sk);
}
/*
* This is called from user mode and the timers. Thus it protects itself
* against interrupt users but doesn't worry about being called during
* work. Once it is removed from the queue no interrupt or bottom half
* will touch it and we are (fairly 8-) ) safe.
*/
void ax25_destroy_socket(ax25_cb *ax25)
{
struct sk_buff *skb;
ax25_cb_del(ax25);
ax25_stop_heartbeat(ax25);
ax25_stop_t1timer(ax25);
ax25_stop_t2timer(ax25);
ax25_stop_t3timer(ax25);
ax25_stop_idletimer(ax25);
ax25_clear_queues(ax25); /* Flush the queues */
if (ax25->sk != NULL) {
while ((skb = skb_dequeue(&ax25->sk->sk_receive_queue)) != NULL) {
if (skb->sk != ax25->sk) {
/* A pending connection */
ax25_cb *sax25 = ax25_sk(skb->sk);
/* Queue the unaccepted socket for death */
sock_orphan(skb->sk);
/* 9A4GL: hack to release unaccepted sockets */
skb->sk->sk_state = TCP_LISTEN;
ax25_start_heartbeat(sax25);
sax25->state = AX25_STATE_0;
}
kfree_skb(skb);
}
skb_queue_purge(&ax25->sk->sk_write_queue);
}
if (ax25->sk != NULL) {
if (sk_has_allocations(ax25->sk)) {
/* Defer: outstanding buffers */
setup_timer(&ax25->dtimer, ax25_destroy_timer,
(unsigned long)ax25);
ax25->dtimer.expires = jiffies + 2 * HZ;
add_timer(&ax25->dtimer);
} else {
struct sock *sk=ax25->sk;
ax25->sk=NULL;
sock_put(sk);
}
} else {
ax25_cb_put(ax25);
}
}
/*
* dl1bke 960311: set parameters for existing AX.25 connections,
* includes a KILL command to abort any connection.
* VERY useful for debugging ;-)
*/
static int ax25_ctl_ioctl(const unsigned int cmd, void __user *arg)
{
struct ax25_ctl_struct ax25_ctl;
ax25_digi digi;
ax25_dev *ax25_dev;
ax25_cb *ax25;
unsigned int k;
int ret = 0;
if (copy_from_user(&ax25_ctl, arg, sizeof(ax25_ctl)))
return -EFAULT;
if ((ax25_dev = ax25_addr_ax25dev(&ax25_ctl.port_addr)) == NULL)
return -ENODEV;
if (ax25_ctl.digi_count > AX25_MAX_DIGIS)
return -EINVAL;
if (ax25_ctl.arg > ULONG_MAX / HZ && ax25_ctl.cmd != AX25_KILL)
return -EINVAL;
digi.ndigi = ax25_ctl.digi_count;
for (k = 0; k < digi.ndigi; k++)
digi.calls[k] = ax25_ctl.digi_addr[k];
if ((ax25 = ax25_find_cb(&ax25_ctl.source_addr, &ax25_ctl.dest_addr, &digi, ax25_dev->dev)) == NULL)
return -ENOTCONN;
switch (ax25_ctl.cmd) {
case AX25_KILL:
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
#ifdef CONFIG_AX25_DAMA_SLAVE
if (ax25_dev->dama.slave && ax25->ax25_dev->values[AX25_VALUES_PROTOCOL] == AX25_PROTO_DAMA_SLAVE)
ax25_dama_off(ax25);
#endif
ax25_disconnect(ax25, ENETRESET);
break;
case AX25_WINDOW:
if (ax25->modulus == AX25_MODULUS) {
if (ax25_ctl.arg < 1 || ax25_ctl.arg > 7)
goto einval_put;
} else {
if (ax25_ctl.arg < 1 || ax25_ctl.arg > 63)
goto einval_put;
}
ax25->window = ax25_ctl.arg;
break;
case AX25_T1:
if (ax25_ctl.arg < 1 || ax25_ctl.arg > ULONG_MAX / HZ)
goto einval_put;
ax25->rtt = (ax25_ctl.arg * HZ) / 2;
ax25->t1 = ax25_ctl.arg * HZ;
break;
case AX25_T2:
if (ax25_ctl.arg < 1 || ax25_ctl.arg > ULONG_MAX / HZ)
goto einval_put;
ax25->t2 = ax25_ctl.arg * HZ;
break;
case AX25_N2:
if (ax25_ctl.arg < 1 || ax25_ctl.arg > 31)
goto einval_put;
ax25->n2count = 0;
ax25->n2 = ax25_ctl.arg;
break;
case AX25_T3:
if (ax25_ctl.arg > ULONG_MAX / HZ)
goto einval_put;
ax25->t3 = ax25_ctl.arg * HZ;
break;
case AX25_IDLE:
if (ax25_ctl.arg > ULONG_MAX / (60 * HZ))
goto einval_put;
ax25->idle = ax25_ctl.arg * 60 * HZ;
break;
case AX25_PACLEN:
if (ax25_ctl.arg < 16 || ax25_ctl.arg > 65535)
goto einval_put;
ax25->paclen = ax25_ctl.arg;
break;
default:
goto einval_put;
}
out_put:
ax25_cb_put(ax25);
return ret;
einval_put:
ret = -EINVAL;
goto out_put;
}
static void ax25_fillin_cb_from_dev(ax25_cb *ax25, ax25_dev *ax25_dev)
{
ax25->rtt = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T1]) / 2;
ax25->t1 = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T1]);
ax25->t2 = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T2]);
ax25->t3 = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_T3]);
ax25->n2 = ax25_dev->values[AX25_VALUES_N2];
ax25->paclen = ax25_dev->values[AX25_VALUES_PACLEN];
ax25->idle = msecs_to_jiffies(ax25_dev->values[AX25_VALUES_IDLE]);
ax25->backoff = ax25_dev->values[AX25_VALUES_BACKOFF];
if (ax25_dev->values[AX25_VALUES_AXDEFMODE]) {
ax25->modulus = AX25_EMODULUS;
ax25->window = ax25_dev->values[AX25_VALUES_EWINDOW];
} else {
ax25->modulus = AX25_MODULUS;
ax25->window = ax25_dev->values[AX25_VALUES_WINDOW];
}
}
/*
* Fill in a created AX.25 created control block with the default
* values for a particular device.
*/
void ax25_fillin_cb(ax25_cb *ax25, ax25_dev *ax25_dev)
{
ax25->ax25_dev = ax25_dev;
if (ax25->ax25_dev != NULL) {
ax25_fillin_cb_from_dev(ax25, ax25_dev);
return;
}
/*
* No device, use kernel / AX.25 spec default values
*/
ax25->rtt = msecs_to_jiffies(AX25_DEF_T1) / 2;
ax25->t1 = msecs_to_jiffies(AX25_DEF_T1);
ax25->t2 = msecs_to_jiffies(AX25_DEF_T2);
ax25->t3 = msecs_to_jiffies(AX25_DEF_T3);
ax25->n2 = AX25_DEF_N2;
ax25->paclen = AX25_DEF_PACLEN;
ax25->idle = msecs_to_jiffies(AX25_DEF_IDLE);
ax25->backoff = AX25_DEF_BACKOFF;
if (AX25_DEF_AXDEFMODE) {
ax25->modulus = AX25_EMODULUS;
ax25->window = AX25_DEF_EWINDOW;
} else {
ax25->modulus = AX25_MODULUS;
ax25->window = AX25_DEF_WINDOW;
}
}
/*
* Create an empty AX.25 control block.
*/
ax25_cb *ax25_create_cb(void)
{
ax25_cb *ax25;
if ((ax25 = kzalloc(sizeof(*ax25), GFP_ATOMIC)) == NULL)
return NULL;
atomic_set(&ax25->refcount, 1);
skb_queue_head_init(&ax25->write_queue);
skb_queue_head_init(&ax25->frag_queue);
skb_queue_head_init(&ax25->ack_queue);
skb_queue_head_init(&ax25->reseq_queue);
ax25_setup_timers(ax25);
ax25_fillin_cb(ax25, NULL);
ax25->state = AX25_STATE_0;
return ax25;
}
/*
* Handling for system calls applied via the various interfaces to an
* AX25 socket object
*/
static int ax25_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
ax25_cb *ax25;
struct net_device *dev;
char devname[IFNAMSIZ];
unsigned long opt;
int res = 0;
if (level != SOL_AX25)
return -ENOPROTOOPT;
if (optlen < sizeof(unsigned int))
return -EINVAL;
if (get_user(opt, (unsigned int __user *)optval))
return -EFAULT;
lock_sock(sk);
ax25 = ax25_sk(sk);
switch (optname) {
case AX25_WINDOW:
if (ax25->modulus == AX25_MODULUS) {
if (opt < 1 || opt > 7) {
res = -EINVAL;
break;
}
} else {
if (opt < 1 || opt > 63) {
res = -EINVAL;
break;
}
}
ax25->window = opt;
break;
case AX25_T1:
if (opt < 1 || opt > ULONG_MAX / HZ) {
res = -EINVAL;
break;
}
ax25->rtt = (opt * HZ) >> 1;
ax25->t1 = opt * HZ;
break;
case AX25_T2:
if (opt < 1 || opt > ULONG_MAX / HZ) {
res = -EINVAL;
break;
}
ax25->t2 = opt * HZ;
break;
case AX25_N2:
if (opt < 1 || opt > 31) {
res = -EINVAL;
break;
}
ax25->n2 = opt;
break;
case AX25_T3:
if (opt < 1 || opt > ULONG_MAX / HZ) {
res = -EINVAL;
break;
}
ax25->t3 = opt * HZ;
break;
case AX25_IDLE:
if (opt > ULONG_MAX / (60 * HZ)) {
res = -EINVAL;
break;
}
ax25->idle = opt * 60 * HZ;
break;
case AX25_BACKOFF:
if (opt > 2) {
res = -EINVAL;
break;
}
ax25->backoff = opt;
break;
case AX25_EXTSEQ:
ax25->modulus = opt ? AX25_EMODULUS : AX25_MODULUS;
break;
case AX25_PIDINCL:
ax25->pidincl = opt ? 1 : 0;
break;
case AX25_IAMDIGI:
ax25->iamdigi = opt ? 1 : 0;
break;
case AX25_PACLEN:
if (opt < 16 || opt > 65535) {
res = -EINVAL;
break;
}
ax25->paclen = opt;
break;
case SO_BINDTODEVICE:
if (optlen > IFNAMSIZ)
optlen = IFNAMSIZ;
if (copy_from_user(devname, optval, optlen)) {
res = -EFAULT;
break;
}
if (sk->sk_type == SOCK_SEQPACKET &&
(sock->state != SS_UNCONNECTED ||
sk->sk_state == TCP_LISTEN)) {
res = -EADDRNOTAVAIL;
break;
}
dev = dev_get_by_name(&init_net, devname);
if (!dev) {
res = -ENODEV;
break;
}
ax25->ax25_dev = ax25_dev_ax25dev(dev);
ax25_fillin_cb(ax25, ax25->ax25_dev);
dev_put(dev);
break;
default:
res = -ENOPROTOOPT;
}
release_sock(sk);
return res;
}
static int ax25_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
ax25_cb *ax25;
struct ax25_dev *ax25_dev;
char devname[IFNAMSIZ];
void *valptr;
int val = 0;
int maxlen, length;
if (level != SOL_AX25)
return -ENOPROTOOPT;
if (get_user(maxlen, optlen))
return -EFAULT;
if (maxlen < 1)
return -EFAULT;
valptr = (void *) &val;
length = min_t(unsigned int, maxlen, sizeof(int));
lock_sock(sk);
ax25 = ax25_sk(sk);
switch (optname) {
case AX25_WINDOW:
val = ax25->window;
break;
case AX25_T1:
val = ax25->t1 / HZ;
break;
case AX25_T2:
val = ax25->t2 / HZ;
break;
case AX25_N2:
val = ax25->n2;
break;
case AX25_T3:
val = ax25->t3 / HZ;
break;
case AX25_IDLE:
val = ax25->idle / (60 * HZ);
break;
case AX25_BACKOFF:
val = ax25->backoff;
break;
case AX25_EXTSEQ:
val = (ax25->modulus == AX25_EMODULUS);
break;
case AX25_PIDINCL:
val = ax25->pidincl;
break;
case AX25_IAMDIGI:
val = ax25->iamdigi;
break;
case AX25_PACLEN:
val = ax25->paclen;
break;
case SO_BINDTODEVICE:
ax25_dev = ax25->ax25_dev;
if (ax25_dev != NULL && ax25_dev->dev != NULL) {
strlcpy(devname, ax25_dev->dev->name, sizeof(devname));
length = strlen(devname) + 1;
} else {
*devname = '\0';
length = 1;
}
valptr = (void *) devname;
break;
default:
release_sock(sk);
return -ENOPROTOOPT;
}
release_sock(sk);
if (put_user(length, optlen))
return -EFAULT;
return copy_to_user(optval, valptr, length) ? -EFAULT : 0;
}
static int ax25_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
int res = 0;
lock_sock(sk);
if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_LISTEN) {
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
goto out;
}
res = -EOPNOTSUPP;
out:
release_sock(sk);
return res;
}
/*
* XXX: when creating ax25_sock we should update the .obj_size setting
* below.
*/
static struct proto ax25_proto = {
.name = "AX25",
.owner = THIS_MODULE,
.obj_size = sizeof(struct sock),
};
static int ax25_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
ax25_cb *ax25;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
switch (sock->type) {
case SOCK_DGRAM:
if (protocol == 0 || protocol == PF_AX25)
protocol = AX25_P_TEXT;
break;
case SOCK_SEQPACKET:
switch (protocol) {
case 0:
case PF_AX25: /* For CLX */
protocol = AX25_P_TEXT;
break;
case AX25_P_SEGMENT:
#ifdef CONFIG_INET
case AX25_P_ARP:
case AX25_P_IP:
#endif
#ifdef CONFIG_NETROM
case AX25_P_NETROM:
#endif
#ifdef CONFIG_ROSE
case AX25_P_ROSE:
#endif
return -ESOCKTNOSUPPORT;
#ifdef CONFIG_NETROM_MODULE
case AX25_P_NETROM:
if (ax25_protocol_is_registered(AX25_P_NETROM))
return -ESOCKTNOSUPPORT;
break;
#endif
#ifdef CONFIG_ROSE_MODULE
case AX25_P_ROSE:
if (ax25_protocol_is_registered(AX25_P_ROSE))
return -ESOCKTNOSUPPORT;
#endif
default:
break;
}
break;
case SOCK_RAW:
break;
default:
return -ESOCKTNOSUPPORT;
}
sk = sk_alloc(net, PF_AX25, GFP_ATOMIC, &ax25_proto);
if (sk == NULL)
return -ENOMEM;
ax25 = sk->sk_protinfo = ax25_create_cb();
if (!ax25) {
sk_free(sk);
return -ENOMEM;
}
sock_init_data(sock, sk);
sk->sk_destruct = ax25_free_sock;
sock->ops = &ax25_proto_ops;
sk->sk_protocol = protocol;
ax25->sk = sk;
return 0;
}
struct sock *ax25_make_new(struct sock *osk, struct ax25_dev *ax25_dev)
{
struct sock *sk;
ax25_cb *ax25, *oax25;
sk = sk_alloc(sock_net(osk), PF_AX25, GFP_ATOMIC, osk->sk_prot);
if (sk == NULL)
return NULL;
if ((ax25 = ax25_create_cb()) == NULL) {
sk_free(sk);
return NULL;
}
switch (osk->sk_type) {
case SOCK_DGRAM:
break;
case SOCK_SEQPACKET:
break;
default:
sk_free(sk);
ax25_cb_put(ax25);
return NULL;
}
sock_init_data(NULL, sk);
sk->sk_type = osk->sk_type;
sk->sk_priority = osk->sk_priority;
sk->sk_protocol = osk->sk_protocol;
sk->sk_rcvbuf = osk->sk_rcvbuf;
sk->sk_sndbuf = osk->sk_sndbuf;
sk->sk_state = TCP_ESTABLISHED;
sock_copy_flags(sk, osk);
oax25 = ax25_sk(osk);
ax25->modulus = oax25->modulus;
ax25->backoff = oax25->backoff;
ax25->pidincl = oax25->pidincl;
ax25->iamdigi = oax25->iamdigi;
ax25->rtt = oax25->rtt;
ax25->t1 = oax25->t1;
ax25->t2 = oax25->t2;
ax25->t3 = oax25->t3;
ax25->n2 = oax25->n2;
ax25->idle = oax25->idle;
ax25->paclen = oax25->paclen;
ax25->window = oax25->window;
ax25->ax25_dev = ax25_dev;
ax25->source_addr = oax25->source_addr;
if (oax25->digipeat != NULL) {
ax25->digipeat = kmemdup(oax25->digipeat, sizeof(ax25_digi),
GFP_ATOMIC);
if (ax25->digipeat == NULL) {
sk_free(sk);
ax25_cb_put(ax25);
return NULL;
}
}
sk->sk_protinfo = ax25;
sk->sk_destruct = ax25_free_sock;
ax25->sk = sk;
return sk;
}
static int ax25_release(struct socket *sock)
{
struct sock *sk = sock->sk;
ax25_cb *ax25;
if (sk == NULL)
return 0;
sock_hold(sk);
sock_orphan(sk);
lock_sock(sk);
ax25 = ax25_sk(sk);
if (sk->sk_type == SOCK_SEQPACKET) {
switch (ax25->state) {
case AX25_STATE_0:
release_sock(sk);
ax25_disconnect(ax25, 0);
lock_sock(sk);
ax25_destroy_socket(ax25);
break;
case AX25_STATE_1:
case AX25_STATE_2:
ax25_send_control(ax25, AX25_DISC, AX25_POLLON, AX25_COMMAND);
release_sock(sk);
ax25_disconnect(ax25, 0);
lock_sock(sk);
ax25_destroy_socket(ax25);
break;
case AX25_STATE_3:
case AX25_STATE_4:
ax25_clear_queues(ax25);
ax25->n2count = 0;
switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_send_control(ax25,
AX25_DISC,
AX25_POLLON,
AX25_COMMAND);
ax25_stop_t2timer(ax25);
ax25_stop_t3timer(ax25);
ax25_stop_idletimer(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
ax25_stop_t3timer(ax25);
ax25_stop_idletimer(ax25);
break;
#endif
}
ax25_calculate_t1(ax25);
ax25_start_t1timer(ax25);
ax25->state = AX25_STATE_2;
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DESTROY);
break;
default:
break;
}
} else {
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
ax25_destroy_socket(ax25);
}
sock->sk = NULL;
release_sock(sk);
sock_put(sk);
return 0;
}
/*
* We support a funny extension here so you can (as root) give any callsign
* digipeated via a local address as source. This hack is obsolete now
* that we've implemented support for SO_BINDTODEVICE. It is however small
* and trivially backward compatible.
*/
static int ax25_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct full_sockaddr_ax25 *addr = (struct full_sockaddr_ax25 *)uaddr;
ax25_dev *ax25_dev = NULL;
ax25_uid_assoc *user;
ax25_address call;
ax25_cb *ax25;
int err = 0;
if (addr_len != sizeof(struct sockaddr_ax25) &&
addr_len != sizeof(struct full_sockaddr_ax25))
/* support for old structure may go away some time
* ax25_bind(): uses old (6 digipeater) socket structure.
*/
if ((addr_len < sizeof(struct sockaddr_ax25) + sizeof(ax25_address) * 6) ||
(addr_len > sizeof(struct full_sockaddr_ax25)))
return -EINVAL;
if (addr->fsa_ax25.sax25_family != AF_AX25)
return -EINVAL;
user = ax25_findbyuid(current_euid());
if (user) {
call = user->call;
ax25_uid_put(user);
} else {
if (ax25_uid_policy && !capable(CAP_NET_ADMIN))
return -EACCES;
call = addr->fsa_ax25.sax25_call;
}
lock_sock(sk);
ax25 = ax25_sk(sk);
if (!sock_flag(sk, SOCK_ZAPPED)) {
err = -EINVAL;
goto out;
}
ax25->source_addr = call;
/*
* User already set interface with SO_BINDTODEVICE
*/
if (ax25->ax25_dev != NULL)
goto done;
if (addr_len > sizeof(struct sockaddr_ax25) && addr->fsa_ax25.sax25_ndigis == 1) {
if (ax25cmp(&addr->fsa_digipeater[0], &null_ax25_address) != 0 &&
(ax25_dev = ax25_addr_ax25dev(&addr->fsa_digipeater[0])) == NULL) {
err = -EADDRNOTAVAIL;
goto out;
}
} else {
if ((ax25_dev = ax25_addr_ax25dev(&addr->fsa_ax25.sax25_call)) == NULL) {
err = -EADDRNOTAVAIL;
goto out;
}
}
if (ax25_dev != NULL)
ax25_fillin_cb(ax25, ax25_dev);
done:
ax25_cb_add(ax25);
sock_reset_flag(sk, SOCK_ZAPPED);
out:
release_sock(sk);
return err;
}
/*
* FIXME: nonblock behaviour looks like it may have a bug.
*/
static int __must_check ax25_connect(struct socket *sock,
struct sockaddr *uaddr, int addr_len, int flags)
{
struct sock *sk = sock->sk;
ax25_cb *ax25 = ax25_sk(sk), *ax25t;
struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)uaddr;
ax25_digi *digi = NULL;
int ct = 0, err = 0;
/*
* some sanity checks. code further down depends on this
*/
if (addr_len == sizeof(struct sockaddr_ax25))
/* support for this will go away in early 2.5.x
* ax25_connect(): uses obsolete socket structure
*/
;
else if (addr_len != sizeof(struct full_sockaddr_ax25))
/* support for old structure may go away some time
* ax25_connect(): uses old (6 digipeater) socket structure.
*/
if ((addr_len < sizeof(struct sockaddr_ax25) + sizeof(ax25_address) * 6) ||
(addr_len > sizeof(struct full_sockaddr_ax25)))
return -EINVAL;
if (fsa->fsa_ax25.sax25_family != AF_AX25)
return -EINVAL;
lock_sock(sk);
/* deal with restarts */
if (sock->state == SS_CONNECTING) {
switch (sk->sk_state) {
case TCP_SYN_SENT: /* still trying */
err = -EINPROGRESS;
goto out_release;
case TCP_ESTABLISHED: /* connection established */
sock->state = SS_CONNECTED;
goto out_release;
case TCP_CLOSE: /* connection refused */
sock->state = SS_UNCONNECTED;
err = -ECONNREFUSED;
goto out_release;
}
}
if (sk->sk_state == TCP_ESTABLISHED && sk->sk_type == SOCK_SEQPACKET) {
err = -EISCONN; /* No reconnect on a seqpacket socket */
goto out_release;
}
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
kfree(ax25->digipeat);
ax25->digipeat = NULL;
/*
* Handle digi-peaters to be used.
*/
if (addr_len > sizeof(struct sockaddr_ax25) &&
fsa->fsa_ax25.sax25_ndigis != 0) {
/* Valid number of digipeaters ? */
if (fsa->fsa_ax25.sax25_ndigis < 1 || fsa->fsa_ax25.sax25_ndigis > AX25_MAX_DIGIS) {
err = -EINVAL;
goto out_release;
}
if ((digi = kmalloc(sizeof(ax25_digi), GFP_KERNEL)) == NULL) {
err = -ENOBUFS;
goto out_release;
}
digi->ndigi = fsa->fsa_ax25.sax25_ndigis;
digi->lastrepeat = -1;
while (ct < fsa->fsa_ax25.sax25_ndigis) {
if ((fsa->fsa_digipeater[ct].ax25_call[6] &
AX25_HBIT) && ax25->iamdigi) {
digi->repeated[ct] = 1;
digi->lastrepeat = ct;
} else {
digi->repeated[ct] = 0;
}
digi->calls[ct] = fsa->fsa_digipeater[ct];
ct++;
}
}
/*
* Must bind first - autobinding in this may or may not work. If
* the socket is already bound, check to see if the device has
* been filled in, error if it hasn't.
*/
if (sock_flag(sk, SOCK_ZAPPED)) {
/* check if we can remove this feature. It is broken. */
printk(KERN_WARNING "ax25_connect(): %s uses autobind, please contact jreuter@yaina.de\n",
current->comm);
if ((err = ax25_rt_autobind(ax25, &fsa->fsa_ax25.sax25_call)) < 0) {
kfree(digi);
goto out_release;
}
ax25_fillin_cb(ax25, ax25->ax25_dev);
ax25_cb_add(ax25);
} else {
if (ax25->ax25_dev == NULL) {
kfree(digi);
err = -EHOSTUNREACH;
goto out_release;
}
}
if (sk->sk_type == SOCK_SEQPACKET &&
(ax25t=ax25_find_cb(&ax25->source_addr, &fsa->fsa_ax25.sax25_call, digi,
ax25->ax25_dev->dev))) {
kfree(digi);
err = -EADDRINUSE; /* Already such a connection */
ax25_cb_put(ax25t);
goto out_release;
}
ax25->dest_addr = fsa->fsa_ax25.sax25_call;
ax25->digipeat = digi;
/* First the easy one */
if (sk->sk_type != SOCK_SEQPACKET) {
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
goto out_release;
}
/* Move to connecting socket, ax.25 lapb WAIT_UA.. */
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
switch (ax25->ax25_dev->values[AX25_VALUES_PROTOCOL]) {
case AX25_PROTO_STD_SIMPLEX:
case AX25_PROTO_STD_DUPLEX:
ax25_std_establish_data_link(ax25);
break;
#ifdef CONFIG_AX25_DAMA_SLAVE
case AX25_PROTO_DAMA_SLAVE:
ax25->modulus = AX25_MODULUS;
ax25->window = ax25->ax25_dev->values[AX25_VALUES_WINDOW];
if (ax25->ax25_dev->dama.slave)
ax25_ds_establish_data_link(ax25);
else
ax25_std_establish_data_link(ax25);
break;
#endif
}
ax25->state = AX25_STATE_1;
ax25_start_heartbeat(ax25);
/* Now the loop */
if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) {
err = -EINPROGRESS;
goto out_release;
}
if (sk->sk_state == TCP_SYN_SENT) {
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
if (sk->sk_state != TCP_SYN_SENT)
break;
if (!signal_pending(current)) {
release_sock(sk);
schedule();
lock_sock(sk);
continue;
}
err = -ERESTARTSYS;
break;
}
finish_wait(sk_sleep(sk), &wait);
if (err)
goto out_release;
}
if (sk->sk_state != TCP_ESTABLISHED) {
/* Not in ABM, not in WAIT_UA -> failed */
sock->state = SS_UNCONNECTED;
err = sock_error(sk); /* Always set at this point */
goto out_release;
}
sock->state = SS_CONNECTED;
err = 0;
out_release:
release_sock(sk);
return err;
}
static int ax25_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sk_buff *skb;
struct sock *newsk;
DEFINE_WAIT(wait);
struct sock *sk;
int err = 0;
if (sock->state != SS_UNCONNECTED)
return -EINVAL;
if ((sk = sock->sk) == NULL)
return -EINVAL;
lock_sock(sk);
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EOPNOTSUPP;
goto out;
}
if (sk->sk_state != TCP_LISTEN) {
err = -EINVAL;
goto out;
}
/*
* The read queue this time is holding sockets ready to use
* hooked into the SABM we saved
*/
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
skb = skb_dequeue(&sk->sk_receive_queue);
if (skb)
break;
if (flags & O_NONBLOCK) {
err = -EWOULDBLOCK;
break;
}
if (!signal_pending(current)) {
release_sock(sk);
schedule();
lock_sock(sk);
continue;
}
err = -ERESTARTSYS;
break;
}
finish_wait(sk_sleep(sk), &wait);
if (err)
goto out;
newsk = skb->sk;
sock_graft(newsk, newsock);
/* Now attach up the new socket */
kfree_skb(skb);
sk->sk_ack_backlog--;
newsock->state = SS_CONNECTED;
out:
release_sock(sk);
return err;
}
static int ax25_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)uaddr;
struct sock *sk = sock->sk;
unsigned char ndigi, i;
ax25_cb *ax25;
int err = 0;
memset(fsa, 0, sizeof(*fsa));
lock_sock(sk);
ax25 = ax25_sk(sk);
if (peer != 0) {
if (sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
fsa->fsa_ax25.sax25_family = AF_AX25;
fsa->fsa_ax25.sax25_call = ax25->dest_addr;
if (ax25->digipeat != NULL) {
ndigi = ax25->digipeat->ndigi;
fsa->fsa_ax25.sax25_ndigis = ndigi;
for (i = 0; i < ndigi; i++)
fsa->fsa_digipeater[i] =
ax25->digipeat->calls[i];
}
} else {
fsa->fsa_ax25.sax25_family = AF_AX25;
fsa->fsa_ax25.sax25_call = ax25->source_addr;
fsa->fsa_ax25.sax25_ndigis = 1;
if (ax25->ax25_dev != NULL) {
memcpy(&fsa->fsa_digipeater[0],
ax25->ax25_dev->dev->dev_addr, AX25_ADDR_LEN);
} else {
fsa->fsa_digipeater[0] = null_ax25_address;
}
}
*uaddr_len = sizeof (struct full_sockaddr_ax25);
out:
release_sock(sk);
return err;
}
static int ax25_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sockaddr_ax25 *usax = (struct sockaddr_ax25 *)msg->msg_name;
struct sock *sk = sock->sk;
struct sockaddr_ax25 sax;
struct sk_buff *skb;
ax25_digi dtmp, *dp;
ax25_cb *ax25;
size_t size;
int lv, err, addr_len = msg->msg_namelen;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT))
return -EINVAL;
lock_sock(sk);
ax25 = ax25_sk(sk);
if (sock_flag(sk, SOCK_ZAPPED)) {
err = -EADDRNOTAVAIL;
goto out;
}
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
goto out;
}
if (ax25->ax25_dev == NULL) {
err = -ENETUNREACH;
goto out;
}
if (len > ax25->ax25_dev->dev->mtu) {
err = -EMSGSIZE;
goto out;
}
if (usax != NULL) {
if (usax->sax25_family != AF_AX25) {
err = -EINVAL;
goto out;
}
if (addr_len == sizeof(struct sockaddr_ax25))
/* ax25_sendmsg(): uses obsolete socket structure */
;
else if (addr_len != sizeof(struct full_sockaddr_ax25))
/* support for old structure may go away some time
* ax25_sendmsg(): uses old (6 digipeater)
* socket structure.
*/
if ((addr_len < sizeof(struct sockaddr_ax25) + sizeof(ax25_address) * 6) ||
(addr_len > sizeof(struct full_sockaddr_ax25))) {
err = -EINVAL;
goto out;
}
if (addr_len > sizeof(struct sockaddr_ax25) && usax->sax25_ndigis != 0) {
int ct = 0;
struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)usax;
/* Valid number of digipeaters ? */
if (usax->sax25_ndigis < 1 || usax->sax25_ndigis > AX25_MAX_DIGIS) {
err = -EINVAL;
goto out;
}
dtmp.ndigi = usax->sax25_ndigis;
while (ct < usax->sax25_ndigis) {
dtmp.repeated[ct] = 0;
dtmp.calls[ct] = fsa->fsa_digipeater[ct];
ct++;
}
dtmp.lastrepeat = 0;
}
sax = *usax;
if (sk->sk_type == SOCK_SEQPACKET &&
ax25cmp(&ax25->dest_addr, &sax.sax25_call)) {
err = -EISCONN;
goto out;
}
if (usax->sax25_ndigis == 0)
dp = NULL;
else
dp = &dtmp;
} else {
/*
* FIXME: 1003.1g - if the socket is like this because
* it has become closed (not started closed) and is VC
* we ought to SIGPIPE, EPIPE
*/
if (sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
sax.sax25_family = AF_AX25;
sax.sax25_call = ax25->dest_addr;
dp = ax25->digipeat;
}
/* Build a packet */
/* Assume the worst case */
size = len + ax25->ax25_dev->dev->hard_header_len;
skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT, &err);
if (skb == NULL)
goto out;
skb_reserve(skb, size - len);
/* User data follows immediately after the AX.25 data */
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
err = -EFAULT;
kfree_skb(skb);
goto out;
}
skb_reset_network_header(skb);
/* Add the PID if one is not supplied by the user in the skb */
if (!ax25->pidincl)
*skb_push(skb, 1) = sk->sk_protocol;
if (sk->sk_type == SOCK_SEQPACKET) {
/* Connected mode sockets go via the LAPB machine */
if (sk->sk_state != TCP_ESTABLISHED) {
kfree_skb(skb);
err = -ENOTCONN;
goto out;
}
/* Shove it onto the queue and kick */
ax25_output(ax25, ax25->paclen, skb);
err = len;
goto out;
}
skb_push(skb, 1 + ax25_addr_size(dp));
/* Building AX.25 Header */
/* Build an AX.25 header */
lv = ax25_addr_build(skb->data, &ax25->source_addr, &sax.sax25_call,
dp, AX25_COMMAND, AX25_MODULUS);
skb_set_transport_header(skb, lv);
*skb_transport_header(skb) = AX25_UI;
/* Datagram frames go straight out of the door as UI */
ax25_queue_xmit(skb, ax25->ax25_dev->dev);
err = len;
out:
release_sock(sk);
return err;
}
static int ax25_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied;
int err = 0;
lock_sock(sk);
/*
* This works for seqpacket too. The receiver has ordered the
* queue for us! We do one quick check first though
*/
if (sk->sk_type == SOCK_SEQPACKET && sk->sk_state != TCP_ESTABLISHED) {
err = -ENOTCONN;
goto out;
}
/* Now we can treat all alike */
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out;
if (!ax25_sk(sk)->pidincl)
skb_pull(skb, 1); /* Remove PID */
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (msg->msg_name) {
ax25_digi digi;
ax25_address src;
const unsigned char *mac = skb_mac_header(skb);
struct sockaddr_ax25 *sax = msg->msg_name;
memset(sax, 0, sizeof(struct full_sockaddr_ax25));
ax25_addr_parse(mac + 1, skb->data - mac - 1, &src, NULL,
&digi, NULL, NULL);
sax->sax25_family = AF_AX25;
/* We set this correctly, even though we may not let the
application know the digi calls further down (because it
did NOT ask to know them). This could get political... **/
sax->sax25_ndigis = digi.ndigi;
sax->sax25_call = src;
if (sax->sax25_ndigis != 0) {
int ct;
struct full_sockaddr_ax25 *fsa = (struct full_sockaddr_ax25 *)sax;
for (ct = 0; ct < digi.ndigi; ct++)
fsa->fsa_digipeater[ct] = digi.calls[ct];
}
msg->msg_namelen = sizeof(struct full_sockaddr_ax25);
}
skb_free_datagram(sk, skb);
err = copied;
out:
release_sock(sk);
return err;
}
static int ax25_shutdown(struct socket *sk, int how)
{
/* FIXME - generate DM and RNR states */
return -EOPNOTSUPP;
}
static int ax25_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
void __user *argp = (void __user *)arg;
int res = 0;
lock_sock(sk);
switch (cmd) {
case TIOCOUTQ: {
long amount;
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
res = put_user(amount, (int __user *)argp);
break;
}
case TIOCINQ: {
struct sk_buff *skb;
long amount = 0L;
/* These two are safe on a single CPU system as only user tasks fiddle here */
if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL)
amount = skb->len;
res = put_user(amount, (int __user *) argp);
break;
}
case SIOCGSTAMP:
res = sock_get_timestamp(sk, argp);
break;
case SIOCGSTAMPNS:
res = sock_get_timestampns(sk, argp);
break;
case SIOCAX25ADDUID: /* Add a uid to the uid/call map table */
case SIOCAX25DELUID: /* Delete a uid from the uid/call map table */
case SIOCAX25GETUID: {
struct sockaddr_ax25 sax25;
if (copy_from_user(&sax25, argp, sizeof(sax25))) {
res = -EFAULT;
break;
}
res = ax25_uid_ioctl(cmd, &sax25);
break;
}
case SIOCAX25NOUID: { /* Set the default policy (default/bar) */
long amount;
if (!capable(CAP_NET_ADMIN)) {
res = -EPERM;
break;
}
if (get_user(amount, (long __user *)argp)) {
res = -EFAULT;
break;
}
if (amount < 0 || amount > AX25_NOUID_BLOCK) {
res = -EINVAL;
break;
}
ax25_uid_policy = amount;
res = 0;
break;
}
case SIOCADDRT:
case SIOCDELRT:
case SIOCAX25OPTRT:
if (!capable(CAP_NET_ADMIN)) {
res = -EPERM;
break;
}
res = ax25_rt_ioctl(cmd, argp);
break;
case SIOCAX25CTLCON:
if (!capable(CAP_NET_ADMIN)) {
res = -EPERM;
break;
}
res = ax25_ctl_ioctl(cmd, argp);
break;
case SIOCAX25GETINFO:
case SIOCAX25GETINFOOLD: {
ax25_cb *ax25 = ax25_sk(sk);
struct ax25_info_struct ax25_info;
ax25_info.t1 = ax25->t1 / HZ;
ax25_info.t2 = ax25->t2 / HZ;
ax25_info.t3 = ax25->t3 / HZ;
ax25_info.idle = ax25->idle / (60 * HZ);
ax25_info.n2 = ax25->n2;
ax25_info.t1timer = ax25_display_timer(&ax25->t1timer) / HZ;
ax25_info.t2timer = ax25_display_timer(&ax25->t2timer) / HZ;
ax25_info.t3timer = ax25_display_timer(&ax25->t3timer) / HZ;
ax25_info.idletimer = ax25_display_timer(&ax25->idletimer) / (60 * HZ);
ax25_info.n2count = ax25->n2count;
ax25_info.state = ax25->state;
ax25_info.rcv_q = sk_rmem_alloc_get(sk);
ax25_info.snd_q = sk_wmem_alloc_get(sk);
ax25_info.vs = ax25->vs;
ax25_info.vr = ax25->vr;
ax25_info.va = ax25->va;
ax25_info.vs_max = ax25->vs; /* reserved */
ax25_info.paclen = ax25->paclen;
ax25_info.window = ax25->window;
/* old structure? */
if (cmd == SIOCAX25GETINFOOLD) {
static int warned = 0;
if (!warned) {
printk(KERN_INFO "%s uses old SIOCAX25GETINFO\n",
current->comm);
warned=1;
}
if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct_deprecated))) {
res = -EFAULT;
break;
}
} else {
if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct))) {
res = -EINVAL;
break;
}
}
res = 0;
break;
}
case SIOCAX25ADDFWD:
case SIOCAX25DELFWD: {
struct ax25_fwd_struct ax25_fwd;
if (!capable(CAP_NET_ADMIN)) {
res = -EPERM;
break;
}
if (copy_from_user(&ax25_fwd, argp, sizeof(ax25_fwd))) {
res = -EFAULT;
break;
}
res = ax25_fwd_ioctl(cmd, &ax25_fwd);
break;
}
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
res = -EINVAL;
break;
default:
res = -ENOIOCTLCMD;
break;
}
release_sock(sk);
return res;
}
#ifdef CONFIG_PROC_FS
static void *ax25_info_start(struct seq_file *seq, loff_t *pos)
__acquires(ax25_list_lock)
{
spin_lock_bh(&ax25_list_lock);
return seq_hlist_start(&ax25_list, *pos);
}
static void *ax25_info_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_hlist_next(v, &ax25_list, pos);
}
static void ax25_info_stop(struct seq_file *seq, void *v)
__releases(ax25_list_lock)
{
spin_unlock_bh(&ax25_list_lock);
}
static int ax25_info_show(struct seq_file *seq, void *v)
{
ax25_cb *ax25 = hlist_entry(v, struct ax25_cb, ax25_node);
char buf[11];
int k;
/*
* New format:
* magic dev src_addr dest_addr,digi1,digi2,.. st vs vr va t1 t1 t2 t2 t3 t3 idle idle n2 n2 rtt window paclen Snd-Q Rcv-Q inode
*/
seq_printf(seq, "%8.8lx %s %s%s ",
(long) ax25,
ax25->ax25_dev == NULL? "???" : ax25->ax25_dev->dev->name,
ax2asc(buf, &ax25->source_addr),
ax25->iamdigi? "*":"");
seq_printf(seq, "%s", ax2asc(buf, &ax25->dest_addr));
for (k=0; (ax25->digipeat != NULL) && (k < ax25->digipeat->ndigi); k++) {
seq_printf(seq, ",%s%s",
ax2asc(buf, &ax25->digipeat->calls[k]),
ax25->digipeat->repeated[k]? "*":"");
}
seq_printf(seq, " %d %d %d %d %lu %lu %lu %lu %lu %lu %lu %lu %d %d %lu %d %d",
ax25->state,
ax25->vs, ax25->vr, ax25->va,
ax25_display_timer(&ax25->t1timer) / HZ, ax25->t1 / HZ,
ax25_display_timer(&ax25->t2timer) / HZ, ax25->t2 / HZ,
ax25_display_timer(&ax25->t3timer) / HZ, ax25->t3 / HZ,
ax25_display_timer(&ax25->idletimer) / (60 * HZ),
ax25->idle / (60 * HZ),
ax25->n2count, ax25->n2,
ax25->rtt / HZ,
ax25->window,
ax25->paclen);
if (ax25->sk != NULL) {
seq_printf(seq, " %d %d %lu\n",
sk_wmem_alloc_get(ax25->sk),
sk_rmem_alloc_get(ax25->sk),
sock_i_ino(ax25->sk));
} else {
seq_puts(seq, " * * *\n");
}
return 0;
}
static const struct seq_operations ax25_info_seqops = {
.start = ax25_info_start,
.next = ax25_info_next,
.stop = ax25_info_stop,
.show = ax25_info_show,
};
static int ax25_info_open(struct inode *inode, struct file *file)
{
return seq_open(file, &ax25_info_seqops);
}
static const struct file_operations ax25_info_fops = {
.owner = THIS_MODULE,
.open = ax25_info_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
#endif
static const struct net_proto_family ax25_family_ops = {
.family = PF_AX25,
.create = ax25_create,
.owner = THIS_MODULE,
};
static const struct proto_ops ax25_proto_ops = {
.family = PF_AX25,
.owner = THIS_MODULE,
.release = ax25_release,
.bind = ax25_bind,
.connect = ax25_connect,
.socketpair = sock_no_socketpair,
.accept = ax25_accept,
.getname = ax25_getname,
.poll = datagram_poll,
.ioctl = ax25_ioctl,
.listen = ax25_listen,
.shutdown = ax25_shutdown,
.setsockopt = ax25_setsockopt,
.getsockopt = ax25_getsockopt,
.sendmsg = ax25_sendmsg,
.recvmsg = ax25_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
/*
* Called by socket.c on kernel start up
*/
static struct packet_type ax25_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_AX25),
.func = ax25_kiss_rcv,
};
static struct notifier_block ax25_dev_notifier = {
.notifier_call = ax25_device_event,
};
static int __init ax25_init(void)
{
int rc = proto_register(&ax25_proto, 0);
if (rc != 0)
goto out;
sock_register(&ax25_family_ops);
dev_add_pack(&ax25_packet_type);
register_netdevice_notifier(&ax25_dev_notifier);
proc_create("ax25_route", S_IRUGO, init_net.proc_net,
&ax25_route_fops);
proc_create("ax25", S_IRUGO, init_net.proc_net, &ax25_info_fops);
proc_create("ax25_calls", S_IRUGO, init_net.proc_net, &ax25_uid_fops);
out:
return rc;
}
module_init(ax25_init);
MODULE_AUTHOR("Jonathan Naylor G4KLX <g4klx@g4klx.demon.co.uk>");
MODULE_DESCRIPTION("The amateur radio AX.25 link layer protocol");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_AX25);
static void __exit ax25_exit(void)
{
remove_proc_entry("ax25_route", init_net.proc_net);
remove_proc_entry("ax25", init_net.proc_net);
remove_proc_entry("ax25_calls", init_net.proc_net);
unregister_netdevice_notifier(&ax25_dev_notifier);
dev_remove_pack(&ax25_packet_type);
sock_unregister(PF_AX25);
proto_unregister(&ax25_proto);
ax25_rt_free();
ax25_uid_free();
ax25_dev_free();
}
module_exit(ax25_exit);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_7 |
crossvul-cpp_data_good_2802_1 | /* nautilus-file-operations.c - Nautilus file operations.
*
* Copyright (C) 1999, 2000 Free Software Foundation
* Copyright (C) 2000, 2001 Eazel, Inc.
* Copyright (C) 2007 Red Hat, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*
* Authors: Alexander Larsson <alexl@redhat.com>
* Ettore Perazzoli <ettore@gnu.org>
* Pavel Cisler <pavel@eazel.com>
*/
#include <config.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <locale.h>
#include <math.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include "nautilus-file-operations.h"
#include "nautilus-file-changes-queue.h"
#include "nautilus-lib-self-check-functions.h"
#include "nautilus-progress-info.h"
#include <eel/eel-glib-extensions.h>
#include <eel/eel-gtk-extensions.h>
#include <eel/eel-stock-dialogs.h>
#include <eel/eel-vfs-extensions.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>
#include <gdk/gdk.h>
#include <gtk/gtk.h>
#include <gio/gio.h>
#include <glib.h>
#include "nautilus-operations-ui-manager.h"
#include "nautilus-file-changes-queue.h"
#include "nautilus-file-private.h"
#include "nautilus-global-preferences.h"
#include "nautilus-link.h"
#include "nautilus-trash-monitor.h"
#include "nautilus-file-utilities.h"
#include "nautilus-file-undo-operations.h"
#include "nautilus-file-undo-manager.h"
/* TODO: TESTING!!! */
typedef struct
{
GTimer *time;
GtkWindow *parent_window;
int screen_num;
guint inhibit_cookie;
NautilusProgressInfo *progress;
GCancellable *cancellable;
GHashTable *skip_files;
GHashTable *skip_readdir_error;
NautilusFileUndoInfo *undo_info;
gboolean skip_all_error;
gboolean skip_all_conflict;
gboolean merge_all;
gboolean replace_all;
gboolean delete_all;
} CommonJob;
typedef struct
{
CommonJob common;
gboolean is_move;
GList *files;
GFile *destination;
GFile *desktop_location;
GFile *fake_display_source;
GdkPoint *icon_positions;
int n_icon_positions;
GHashTable *debuting_files;
gchar *target_name;
NautilusCopyCallback done_callback;
gpointer done_callback_data;
} CopyMoveJob;
typedef struct
{
CommonJob common;
GList *files;
gboolean try_trash;
gboolean user_cancel;
NautilusDeleteCallback done_callback;
gpointer done_callback_data;
} DeleteJob;
typedef struct
{
CommonJob common;
GFile *dest_dir;
char *filename;
gboolean make_dir;
GFile *src;
char *src_data;
int length;
GdkPoint position;
gboolean has_position;
GFile *created_file;
NautilusCreateCallback done_callback;
gpointer done_callback_data;
} CreateJob;
typedef struct
{
CommonJob common;
GList *trash_dirs;
gboolean should_confirm;
NautilusOpCallback done_callback;
gpointer done_callback_data;
} EmptyTrashJob;
typedef struct
{
CommonJob common;
GFile *file;
gboolean interactive;
NautilusOpCallback done_callback;
gpointer done_callback_data;
} MarkTrustedJob;
typedef struct
{
CommonJob common;
GFile *file;
NautilusOpCallback done_callback;
gpointer done_callback_data;
guint32 file_permissions;
guint32 file_mask;
guint32 dir_permissions;
guint32 dir_mask;
} SetPermissionsJob;
typedef enum
{
OP_KIND_COPY,
OP_KIND_MOVE,
OP_KIND_DELETE,
OP_KIND_TRASH,
OP_KIND_COMPRESS
} OpKind;
typedef struct
{
int num_files;
goffset num_bytes;
int num_files_since_progress;
OpKind op;
} SourceInfo;
typedef struct
{
int num_files;
goffset num_bytes;
OpKind op;
guint64 last_report_time;
int last_reported_files_left;
} TransferInfo;
typedef struct
{
CommonJob common;
GList *source_files;
GFile *destination_directory;
GList *output_files;
gdouble base_progress;
guint64 archive_compressed_size;
guint64 total_compressed_size;
NautilusExtractCallback done_callback;
gpointer done_callback_data;
} ExtractJob;
typedef struct
{
CommonJob common;
GList *source_files;
GFile *output_file;
AutoarFormat format;
AutoarFilter filter;
guint64 total_size;
guint total_files;
gboolean success;
NautilusCreateCallback done_callback;
gpointer done_callback_data;
} CompressJob;
#define SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE 8
#define NSEC_PER_MICROSEC 1000
#define PROGRESS_NOTIFY_INTERVAL 100 * NSEC_PER_MICROSEC
#define MAXIMUM_DISPLAYED_FILE_NAME_LENGTH 50
#define IS_IO_ERROR(__error, KIND) (((__error)->domain == G_IO_ERROR && (__error)->code == G_IO_ERROR_ ## KIND))
#define CANCEL _("_Cancel")
#define SKIP _("_Skip")
#define SKIP_ALL _("S_kip All")
#define RETRY _("_Retry")
#define DELETE _("_Delete")
#define DELETE_ALL _("Delete _All")
#define REPLACE _("_Replace")
#define REPLACE_ALL _("Replace _All")
#define MERGE _("_Merge")
#define MERGE_ALL _("Merge _All")
#define COPY_FORCE _("Copy _Anyway")
static void
mark_desktop_file_executable (CommonJob *common,
GCancellable *cancellable,
GFile *file,
gboolean interactive);
static gboolean
is_all_button_text (const char *button_text)
{
g_assert (button_text != NULL);
return !strcmp (button_text, SKIP_ALL) ||
!strcmp (button_text, REPLACE_ALL) ||
!strcmp (button_text, DELETE_ALL) ||
!strcmp (button_text, MERGE_ALL);
}
static void scan_sources (GList *files,
SourceInfo *source_info,
CommonJob *job,
OpKind kind);
static void empty_trash_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable);
static void empty_trash_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data);
static char *query_fs_type (GFile *file,
GCancellable *cancellable);
/* keep in time with format_time()
*
* This counts and outputs the number of “time units”
* formatted and displayed by format_time().
* For instance, if format_time outputs “3 hours, 4 minutes”
* it yields 7.
*/
static int
seconds_count_format_time_units (int seconds)
{
int minutes;
int hours;
if (seconds < 0)
{
/* Just to make sure... */
seconds = 0;
}
if (seconds < 60)
{
/* seconds */
return seconds;
}
if (seconds < 60 * 60)
{
/* minutes */
minutes = seconds / 60;
return minutes;
}
hours = seconds / (60 * 60);
if (seconds < 60 * 60 * 4)
{
/* minutes + hours */
minutes = (seconds - hours * 60 * 60) / 60;
return minutes + hours;
}
return hours;
}
static char *
format_time (int seconds)
{
int minutes;
int hours;
char *res;
if (seconds < 0)
{
/* Just to make sure... */
seconds = 0;
}
if (seconds < 60)
{
return g_strdup_printf (ngettext ("%'d second", "%'d seconds", (int) seconds), (int) seconds);
}
if (seconds < 60 * 60)
{
minutes = seconds / 60;
return g_strdup_printf (ngettext ("%'d minute", "%'d minutes", minutes), minutes);
}
hours = seconds / (60 * 60);
if (seconds < 60 * 60 * 4)
{
char *h, *m;
minutes = (seconds - hours * 60 * 60) / 60;
h = g_strdup_printf (ngettext ("%'d hour", "%'d hours", hours), hours);
m = g_strdup_printf (ngettext ("%'d minute", "%'d minutes", minutes), minutes);
res = g_strconcat (h, ", ", m, NULL);
g_free (h);
g_free (m);
return res;
}
return g_strdup_printf (ngettext ("approximately %'d hour",
"approximately %'d hours",
hours), hours);
}
static char *
shorten_utf8_string (const char *base,
int reduce_by_num_bytes)
{
int len;
char *ret;
const char *p;
len = strlen (base);
len -= reduce_by_num_bytes;
if (len <= 0)
{
return NULL;
}
ret = g_new (char, len + 1);
p = base;
while (len)
{
char *next;
next = g_utf8_next_char (p);
if (next - p > len || *next == '\0')
{
break;
}
len -= next - p;
p = next;
}
if (p - base == 0)
{
g_free (ret);
return NULL;
}
else
{
memcpy (ret, base, p - base);
ret[p - base] = '\0';
return ret;
}
}
/* Note that we have these two separate functions with separate format
* strings for ease of localization.
*/
static char *
get_link_name (const char *name,
int count,
int max_length)
{
const char *format;
char *result;
int unshortened_length;
gboolean use_count;
g_assert (name != NULL);
if (count < 0)
{
g_warning ("bad count in get_link_name");
count = 0;
}
if (count <= 2)
{
/* Handle special cases for low numbers.
* Perhaps for some locales we will need to add more.
*/
switch (count)
{
default:
{
g_assert_not_reached ();
/* fall through */
}
case 0:
{
/* duplicate original file name */
format = "%s";
}
break;
case 1:
{
/* appended to new link file */
format = _("Link to %s");
}
break;
case 2:
{
/* appended to new link file */
format = _("Another link to %s");
}
break;
}
use_count = FALSE;
}
else
{
/* Handle special cases for the first few numbers of each ten.
* For locales where getting this exactly right is difficult,
* these can just be made all the same as the general case below.
*/
switch (count % 10)
{
case 1:
{
/* Localizers: Feel free to leave out the "st" suffix
* if there's no way to do that nicely for a
* particular language.
*/
format = _("%'dst link to %s");
}
break;
case 2:
{
/* appended to new link file */
format = _("%'dnd link to %s");
}
break;
case 3:
{
/* appended to new link file */
format = _("%'drd link to %s");
}
break;
default:
{
/* appended to new link file */
format = _("%'dth link to %s");
}
break;
}
use_count = TRUE;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
if (use_count)
{
result = g_strdup_printf (format, count, name);
}
else
{
result = g_strdup_printf (format, name);
}
if (max_length > 0 && (unshortened_length = strlen (result)) > max_length)
{
char *new_name;
new_name = shorten_utf8_string (name, unshortened_length - max_length);
if (new_name)
{
g_free (result);
if (use_count)
{
result = g_strdup_printf (format, count, new_name);
}
else
{
result = g_strdup_printf (format, new_name);
}
g_assert (strlen (result) <= max_length);
g_free (new_name);
}
}
#pragma GCC diagnostic pop
return result;
}
/* Localizers:
* Feel free to leave out the st, nd, rd and th suffix or
* make some or all of them match.
*/
/* localizers: tag used to detect the first copy of a file */
static const char untranslated_copy_duplicate_tag[] = N_(" (copy)");
/* localizers: tag used to detect the second copy of a file */
static const char untranslated_another_copy_duplicate_tag[] = N_(" (another copy)");
/* localizers: tag used to detect the x11th copy of a file */
static const char untranslated_x11th_copy_duplicate_tag[] = N_("th copy)");
/* localizers: tag used to detect the x12th copy of a file */
static const char untranslated_x12th_copy_duplicate_tag[] = N_("th copy)");
/* localizers: tag used to detect the x13th copy of a file */
static const char untranslated_x13th_copy_duplicate_tag[] = N_("th copy)");
/* localizers: tag used to detect the x1st copy of a file */
static const char untranslated_st_copy_duplicate_tag[] = N_("st copy)");
/* localizers: tag used to detect the x2nd copy of a file */
static const char untranslated_nd_copy_duplicate_tag[] = N_("nd copy)");
/* localizers: tag used to detect the x3rd copy of a file */
static const char untranslated_rd_copy_duplicate_tag[] = N_("rd copy)");
/* localizers: tag used to detect the xxth copy of a file */
static const char untranslated_th_copy_duplicate_tag[] = N_("th copy)");
#define COPY_DUPLICATE_TAG _(untranslated_copy_duplicate_tag)
#define ANOTHER_COPY_DUPLICATE_TAG _(untranslated_another_copy_duplicate_tag)
#define X11TH_COPY_DUPLICATE_TAG _(untranslated_x11th_copy_duplicate_tag)
#define X12TH_COPY_DUPLICATE_TAG _(untranslated_x12th_copy_duplicate_tag)
#define X13TH_COPY_DUPLICATE_TAG _(untranslated_x13th_copy_duplicate_tag)
#define ST_COPY_DUPLICATE_TAG _(untranslated_st_copy_duplicate_tag)
#define ND_COPY_DUPLICATE_TAG _(untranslated_nd_copy_duplicate_tag)
#define RD_COPY_DUPLICATE_TAG _(untranslated_rd_copy_duplicate_tag)
#define TH_COPY_DUPLICATE_TAG _(untranslated_th_copy_duplicate_tag)
/* localizers: appended to first file copy */
static const char untranslated_first_copy_duplicate_format[] = N_("%s (copy)%s");
/* localizers: appended to second file copy */
static const char untranslated_second_copy_duplicate_format[] = N_("%s (another copy)%s");
/* localizers: appended to x11th file copy */
static const char untranslated_x11th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
/* localizers: appended to x12th file copy */
static const char untranslated_x12th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
/* localizers: appended to x13th file copy */
static const char untranslated_x13th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
/* localizers: if in your language there's no difference between 1st, 2nd, 3rd and nth
* plurals, you can leave the st, nd, rd suffixes out and just make all the translated
* strings look like "%s (copy %'d)%s".
*/
/* localizers: appended to x1st file copy */
static const char untranslated_st_copy_duplicate_format[] = N_("%s (%'dst copy)%s");
/* localizers: appended to x2nd file copy */
static const char untranslated_nd_copy_duplicate_format[] = N_("%s (%'dnd copy)%s");
/* localizers: appended to x3rd file copy */
static const char untranslated_rd_copy_duplicate_format[] = N_("%s (%'drd copy)%s");
/* localizers: appended to xxth file copy */
static const char untranslated_th_copy_duplicate_format[] = N_("%s (%'dth copy)%s");
#define FIRST_COPY_DUPLICATE_FORMAT _(untranslated_first_copy_duplicate_format)
#define SECOND_COPY_DUPLICATE_FORMAT _(untranslated_second_copy_duplicate_format)
#define X11TH_COPY_DUPLICATE_FORMAT _(untranslated_x11th_copy_duplicate_format)
#define X12TH_COPY_DUPLICATE_FORMAT _(untranslated_x12th_copy_duplicate_format)
#define X13TH_COPY_DUPLICATE_FORMAT _(untranslated_x13th_copy_duplicate_format)
#define ST_COPY_DUPLICATE_FORMAT _(untranslated_st_copy_duplicate_format)
#define ND_COPY_DUPLICATE_FORMAT _(untranslated_nd_copy_duplicate_format)
#define RD_COPY_DUPLICATE_FORMAT _(untranslated_rd_copy_duplicate_format)
#define TH_COPY_DUPLICATE_FORMAT _(untranslated_th_copy_duplicate_format)
static char *
extract_string_until (const char *original,
const char *until_substring)
{
char *result;
g_assert ((int) strlen (original) >= until_substring - original);
g_assert (until_substring - original >= 0);
result = g_malloc (until_substring - original + 1);
strncpy (result, original, until_substring - original);
result[until_substring - original] = '\0';
return result;
}
/* Dismantle a file name, separating the base name, the file suffix and removing any
* (xxxcopy), etc. string. Figure out the count that corresponds to the given
* (xxxcopy) substring.
*/
static void
parse_previous_duplicate_name (const char *name,
char **name_base,
const char **suffix,
int *count)
{
const char *tag;
g_assert (name[0] != '\0');
*suffix = eel_filename_get_extension_offset (name);
if (*suffix == NULL || (*suffix)[1] == '\0')
{
/* no suffix */
*suffix = "";
}
tag = strstr (name, COPY_DUPLICATE_TAG);
if (tag != NULL)
{
if (tag > *suffix)
{
/* handle case "foo. (copy)" */
*suffix = "";
}
*name_base = extract_string_until (name, tag);
*count = 1;
return;
}
tag = strstr (name, ANOTHER_COPY_DUPLICATE_TAG);
if (tag != NULL)
{
if (tag > *suffix)
{
/* handle case "foo. (another copy)" */
*suffix = "";
}
*name_base = extract_string_until (name, tag);
*count = 2;
return;
}
/* Check to see if we got one of st, nd, rd, th. */
tag = strstr (name, X11TH_COPY_DUPLICATE_TAG);
if (tag == NULL)
{
tag = strstr (name, X12TH_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, X13TH_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, ST_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, ND_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, RD_COPY_DUPLICATE_TAG);
}
if (tag == NULL)
{
tag = strstr (name, TH_COPY_DUPLICATE_TAG);
}
/* If we got one of st, nd, rd, th, fish out the duplicate number. */
if (tag != NULL)
{
/* localizers: opening parentheses to match the "th copy)" string */
tag = strstr (name, _(" ("));
if (tag != NULL)
{
if (tag > *suffix)
{
/* handle case "foo. (22nd copy)" */
*suffix = "";
}
*name_base = extract_string_until (name, tag);
/* localizers: opening parentheses of the "th copy)" string */
if (sscanf (tag, _(" (%'d"), count) == 1)
{
if (*count < 1 || *count > 1000000)
{
/* keep the count within a reasonable range */
*count = 0;
}
return;
}
*count = 0;
return;
}
}
*count = 0;
if (**suffix != '\0')
{
*name_base = extract_string_until (name, *suffix);
}
else
{
*name_base = g_strdup (name);
}
}
static char *
make_next_duplicate_name (const char *base,
const char *suffix,
int count,
int max_length)
{
const char *format;
char *result;
int unshortened_length;
gboolean use_count;
if (count < 1)
{
g_warning ("bad count %d in get_duplicate_name", count);
count = 1;
}
if (count <= 2)
{
/* Handle special cases for low numbers.
* Perhaps for some locales we will need to add more.
*/
switch (count)
{
default:
{
g_assert_not_reached ();
/* fall through */
}
case 1:
{
format = FIRST_COPY_DUPLICATE_FORMAT;
}
break;
case 2:
{
format = SECOND_COPY_DUPLICATE_FORMAT;
}
break;
}
use_count = FALSE;
}
else
{
/* Handle special cases for the first few numbers of each ten.
* For locales where getting this exactly right is difficult,
* these can just be made all the same as the general case below.
*/
/* Handle special cases for x11th - x20th.
*/
switch (count % 100)
{
case 11:
{
format = X11TH_COPY_DUPLICATE_FORMAT;
}
break;
case 12:
{
format = X12TH_COPY_DUPLICATE_FORMAT;
}
break;
case 13:
{
format = X13TH_COPY_DUPLICATE_FORMAT;
}
break;
default:
{
format = NULL;
}
break;
}
if (format == NULL)
{
switch (count % 10)
{
case 1:
{
format = ST_COPY_DUPLICATE_FORMAT;
}
break;
case 2:
{
format = ND_COPY_DUPLICATE_FORMAT;
}
break;
case 3:
{
format = RD_COPY_DUPLICATE_FORMAT;
}
break;
default:
{
/* The general case. */
format = TH_COPY_DUPLICATE_FORMAT;
}
break;
}
}
use_count = TRUE;
}
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
if (use_count)
{
result = g_strdup_printf (format, base, count, suffix);
}
else
{
result = g_strdup_printf (format, base, suffix);
}
if (max_length > 0 && (unshortened_length = strlen (result)) > max_length)
{
char *new_base;
new_base = shorten_utf8_string (base, unshortened_length - max_length);
if (new_base)
{
g_free (result);
if (use_count)
{
result = g_strdup_printf (format, new_base, count, suffix);
}
else
{
result = g_strdup_printf (format, new_base, suffix);
}
g_assert (strlen (result) <= max_length);
g_free (new_base);
}
}
#pragma GCC diagnostic pop
return result;
}
static char *
get_duplicate_name (const char *name,
int count_increment,
int max_length)
{
char *result;
char *name_base;
const char *suffix;
int count;
parse_previous_duplicate_name (name, &name_base, &suffix, &count);
result = make_next_duplicate_name (name_base, suffix, count + count_increment, max_length);
g_free (name_base);
return result;
}
static gboolean
has_invalid_xml_char (char *str)
{
gunichar c;
while (*str != 0)
{
c = g_utf8_get_char (str);
/* characters XML permits */
if (!(c == 0x9 ||
c == 0xA ||
c == 0xD ||
(c >= 0x20 && c <= 0xD7FF) ||
(c >= 0xE000 && c <= 0xFFFD) ||
(c >= 0x10000 && c <= 0x10FFFF)))
{
return TRUE;
}
str = g_utf8_next_char (str);
}
return FALSE;
}
static char *
custom_full_name_to_string (char *format,
va_list va)
{
GFile *file;
file = va_arg (va, GFile *);
return g_file_get_parse_name (file);
}
static void
custom_full_name_skip (va_list *va)
{
(void) va_arg (*va, GFile *);
}
static char *
custom_basename_to_string (char *format,
va_list va)
{
GFile *file;
GFileInfo *info;
char *name, *basename, *tmp;
GMount *mount;
file = va_arg (va, GFile *);
if ((mount = nautilus_get_mounted_mount_for_root (file)) != NULL)
{
name = g_mount_get_name (mount);
g_object_unref (mount);
}
else
{
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_DISPLAY_NAME,
0,
g_cancellable_get_current (),
NULL);
name = NULL;
if (info)
{
name = g_strdup (g_file_info_get_display_name (info));
g_object_unref (info);
}
}
if (name == NULL)
{
basename = g_file_get_basename (file);
if (g_utf8_validate (basename, -1, NULL))
{
name = basename;
}
else
{
name = g_uri_escape_string (basename, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
g_free (basename);
}
}
/* Some chars can't be put in the markup we use for the dialogs... */
if (has_invalid_xml_char (name))
{
tmp = name;
name = g_uri_escape_string (name, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, TRUE);
g_free (tmp);
}
/* Finally, if the string is too long, truncate it. */
if (name != NULL)
{
tmp = name;
name = eel_str_middle_truncate (tmp, MAXIMUM_DISPLAYED_FILE_NAME_LENGTH);
g_free (tmp);
}
return name;
}
static void
custom_basename_skip (va_list *va)
{
(void) va_arg (*va, GFile *);
}
static char *
custom_size_to_string (char *format,
va_list va)
{
goffset size;
size = va_arg (va, goffset);
return g_format_size (size);
}
static void
custom_size_skip (va_list *va)
{
(void) va_arg (*va, goffset);
}
static char *
custom_time_to_string (char *format,
va_list va)
{
int secs;
secs = va_arg (va, int);
return format_time (secs);
}
static void
custom_time_skip (va_list *va)
{
(void) va_arg (*va, int);
}
static char *
custom_mount_to_string (char *format,
va_list va)
{
GMount *mount;
mount = va_arg (va, GMount *);
return g_mount_get_name (mount);
}
static void
custom_mount_skip (va_list *va)
{
(void) va_arg (*va, GMount *);
}
static EelPrintfHandler handlers[] =
{
{ 'F', custom_full_name_to_string, custom_full_name_skip },
{ 'B', custom_basename_to_string, custom_basename_skip },
{ 'S', custom_size_to_string, custom_size_skip },
{ 'T', custom_time_to_string, custom_time_skip },
{ 'V', custom_mount_to_string, custom_mount_skip },
{ 0 }
};
static char *
f (const char *format,
...)
{
va_list va;
char *res;
va_start (va, format);
res = eel_strdup_vprintf_with_custom (handlers, format, va);
va_end (va);
return res;
}
#define op_job_new(__type, parent_window) ((__type *) (init_common (sizeof (__type), parent_window)))
static gpointer
init_common (gsize job_size,
GtkWindow *parent_window)
{
CommonJob *common;
GdkScreen *screen;
common = g_malloc0 (job_size);
if (parent_window)
{
common->parent_window = parent_window;
g_object_add_weak_pointer (G_OBJECT (common->parent_window),
(gpointer *) &common->parent_window);
}
common->progress = nautilus_progress_info_new ();
common->cancellable = nautilus_progress_info_get_cancellable (common->progress);
common->time = g_timer_new ();
common->inhibit_cookie = 0;
common->screen_num = 0;
if (parent_window)
{
screen = gtk_widget_get_screen (GTK_WIDGET (parent_window));
common->screen_num = gdk_screen_get_number (screen);
}
return common;
}
static void
finalize_common (CommonJob *common)
{
nautilus_progress_info_finish (common->progress);
if (common->inhibit_cookie != 0)
{
gtk_application_uninhibit (GTK_APPLICATION (g_application_get_default ()),
common->inhibit_cookie);
}
common->inhibit_cookie = 0;
g_timer_destroy (common->time);
if (common->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (common->parent_window),
(gpointer *) &common->parent_window);
}
if (common->skip_files)
{
g_hash_table_destroy (common->skip_files);
}
if (common->skip_readdir_error)
{
g_hash_table_destroy (common->skip_readdir_error);
}
if (common->undo_info != NULL)
{
nautilus_file_undo_manager_set_action (common->undo_info);
g_object_unref (common->undo_info);
}
g_object_unref (common->progress);
g_object_unref (common->cancellable);
g_free (common);
}
static void
skip_file (CommonJob *common,
GFile *file)
{
if (common->skip_files == NULL)
{
common->skip_files =
g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
}
g_hash_table_insert (common->skip_files, g_object_ref (file), file);
}
static void
skip_readdir_error (CommonJob *common,
GFile *dir)
{
if (common->skip_readdir_error == NULL)
{
common->skip_readdir_error =
g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
}
g_hash_table_insert (common->skip_readdir_error, g_object_ref (dir), dir);
}
static gboolean
should_skip_file (CommonJob *common,
GFile *file)
{
if (common->skip_files != NULL)
{
return g_hash_table_lookup (common->skip_files, file) != NULL;
}
return FALSE;
}
static gboolean
should_skip_readdir_error (CommonJob *common,
GFile *dir)
{
if (common->skip_readdir_error != NULL)
{
return g_hash_table_lookup (common->skip_readdir_error, dir) != NULL;
}
return FALSE;
}
static gboolean
can_delete_without_confirm (GFile *file)
{
if (g_file_has_uri_scheme (file, "burn") ||
g_file_has_uri_scheme (file, "recent") ||
g_file_has_uri_scheme (file, "x-nautilus-desktop"))
{
return TRUE;
}
return FALSE;
}
static gboolean
can_delete_files_without_confirm (GList *files)
{
g_assert (files != NULL);
while (files != NULL)
{
if (!can_delete_without_confirm (files->data))
{
return FALSE;
}
files = files->next;
}
return TRUE;
}
typedef struct
{
GtkWindow **parent_window;
gboolean ignore_close_box;
GtkMessageType message_type;
const char *primary_text;
const char *secondary_text;
const char *details_text;
const char **button_titles;
gboolean show_all;
int result;
/* Dialogs are ran from operation threads, which need to be blocked until
* the user gives a valid response
*/
gboolean completed;
GMutex mutex;
GCond cond;
} RunSimpleDialogData;
static gboolean
do_run_simple_dialog (gpointer _data)
{
RunSimpleDialogData *data = _data;
const char *button_title;
GtkWidget *dialog;
int result;
int response_id;
g_mutex_lock (&data->mutex);
/* Create the dialog. */
dialog = gtk_message_dialog_new (*data->parent_window,
0,
data->message_type,
GTK_BUTTONS_NONE,
NULL);
g_object_set (dialog,
"text", data->primary_text,
"secondary-text", data->secondary_text,
NULL);
for (response_id = 0;
data->button_titles[response_id] != NULL;
response_id++)
{
button_title = data->button_titles[response_id];
if (!data->show_all && is_all_button_text (button_title))
{
continue;
}
gtk_dialog_add_button (GTK_DIALOG (dialog), button_title, response_id);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), response_id);
}
if (data->details_text)
{
eel_gtk_message_dialog_set_details_label (GTK_MESSAGE_DIALOG (dialog),
data->details_text);
}
/* Run it. */
result = gtk_dialog_run (GTK_DIALOG (dialog));
while ((result == GTK_RESPONSE_NONE || result == GTK_RESPONSE_DELETE_EVENT) && data->ignore_close_box)
{
result = gtk_dialog_run (GTK_DIALOG (dialog));
}
gtk_widget_destroy (dialog);
data->result = result;
data->completed = TRUE;
g_cond_signal (&data->cond);
g_mutex_unlock (&data->mutex);
return FALSE;
}
/* NOTE: This frees the primary / secondary strings, in order to
* avoid doing that everywhere. So, make sure they are strduped */
static int
run_simple_dialog_va (CommonJob *job,
gboolean ignore_close_box,
GtkMessageType message_type,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
va_list varargs)
{
RunSimpleDialogData *data;
int res;
const char *button_title;
GPtrArray *ptr_array;
g_timer_stop (job->time);
data = g_new0 (RunSimpleDialogData, 1);
data->parent_window = &job->parent_window;
data->ignore_close_box = ignore_close_box;
data->message_type = message_type;
data->primary_text = primary_text;
data->secondary_text = secondary_text;
data->details_text = details_text;
data->show_all = show_all;
data->completed = FALSE;
g_mutex_init (&data->mutex);
g_cond_init (&data->cond);
ptr_array = g_ptr_array_new ();
while ((button_title = va_arg (varargs, const char *)) != NULL)
{
g_ptr_array_add (ptr_array, (char *) button_title);
}
g_ptr_array_add (ptr_array, NULL);
data->button_titles = (const char **) g_ptr_array_free (ptr_array, FALSE);
nautilus_progress_info_pause (job->progress);
g_mutex_lock (&data->mutex);
g_main_context_invoke (NULL,
do_run_simple_dialog,
data);
while (!data->completed)
{
g_cond_wait (&data->cond, &data->mutex);
}
nautilus_progress_info_resume (job->progress);
res = data->result;
g_mutex_unlock (&data->mutex);
g_mutex_clear (&data->mutex);
g_cond_clear (&data->cond);
g_free (data->button_titles);
g_free (data);
g_timer_continue (job->time);
g_free (primary_text);
g_free (secondary_text);
return res;
}
#if 0 /* Not used at the moment */
static int
run_simple_dialog (CommonJob *job,
gboolean ignore_close_box,
GtkMessageType message_type,
char *primary_text,
char *secondary_text,
const char *details_text,
...)
{
va_list varargs;
int res;
va_start (varargs, details_text);
res = run_simple_dialog_va (job,
ignore_close_box,
message_type,
primary_text,
secondary_text,
details_text,
varargs);
va_end (varargs);
return res;
}
#endif
static int
run_error (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
...)
{
va_list varargs;
int res;
va_start (varargs, show_all);
res = run_simple_dialog_va (job,
FALSE,
GTK_MESSAGE_ERROR,
primary_text,
secondary_text,
details_text,
show_all,
varargs);
va_end (varargs);
return res;
}
static int
run_warning (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
...)
{
va_list varargs;
int res;
va_start (varargs, show_all);
res = run_simple_dialog_va (job,
FALSE,
GTK_MESSAGE_WARNING,
primary_text,
secondary_text,
details_text,
show_all,
varargs);
va_end (varargs);
return res;
}
static int
run_question (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
gboolean show_all,
...)
{
va_list varargs;
int res;
va_start (varargs, show_all);
res = run_simple_dialog_va (job,
FALSE,
GTK_MESSAGE_QUESTION,
primary_text,
secondary_text,
details_text,
show_all,
varargs);
va_end (varargs);
return res;
}
static int
run_cancel_or_skip_warning (CommonJob *job,
char *primary_text,
char *secondary_text,
const char *details_text,
int total_operations,
int operations_remaining)
{
int response;
if (total_operations == 1)
{
response = run_warning (job,
primary_text,
secondary_text,
details_text,
FALSE,
CANCEL,
NULL);
}
else
{
response = run_warning (job,
primary_text,
secondary_text,
details_text,
operations_remaining > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
}
return response;
}
static void
inhibit_power_manager (CommonJob *job,
const char *message)
{
job->inhibit_cookie = gtk_application_inhibit (GTK_APPLICATION (g_application_get_default ()),
GTK_WINDOW (job->parent_window),
GTK_APPLICATION_INHIBIT_LOGOUT |
GTK_APPLICATION_INHIBIT_SUSPEND,
message);
}
static void
abort_job (CommonJob *job)
{
/* destroy the undo action data too */
g_clear_object (&job->undo_info);
g_cancellable_cancel (job->cancellable);
}
static gboolean
job_aborted (CommonJob *job)
{
return g_cancellable_is_cancelled (job->cancellable);
}
/* Since this happens on a thread we can't use the global prefs object */
static gboolean
should_confirm_trash (void)
{
GSettings *prefs;
gboolean confirm_trash;
prefs = g_settings_new ("org.gnome.nautilus.preferences");
confirm_trash = g_settings_get_boolean (prefs, NAUTILUS_PREFERENCES_CONFIRM_TRASH);
g_object_unref (prefs);
return confirm_trash;
}
static gboolean
confirm_delete_from_trash (CommonJob *job,
GList *files)
{
char *prompt;
int file_count;
int response;
/* Just Say Yes if the preference says not to confirm. */
if (!should_confirm_trash ())
{
return TRUE;
}
file_count = g_list_length (files);
g_assert (file_count > 0);
if (file_count == 1)
{
prompt = f (_("Are you sure you want to permanently delete “%B” "
"from the trash?"), files->data);
}
else
{
prompt = f (ngettext ("Are you sure you want to permanently delete "
"the %'d selected item from the trash?",
"Are you sure you want to permanently delete "
"the %'d selected items from the trash?",
file_count),
file_count);
}
response = run_warning (job,
prompt,
f (_("If you delete an item, it will be permanently lost.")),
NULL,
FALSE,
CANCEL, DELETE,
NULL);
return (response == 1);
}
static gboolean
confirm_empty_trash (CommonJob *job)
{
char *prompt;
int response;
/* Just Say Yes if the preference says not to confirm. */
if (!should_confirm_trash ())
{
return TRUE;
}
prompt = f (_("Empty all items from Trash?"));
response = run_warning (job,
prompt,
f (_("All items in the Trash will be permanently deleted.")),
NULL,
FALSE,
CANCEL, _("Empty _Trash"),
NULL);
return (response == 1);
}
static gboolean
confirm_delete_directly (CommonJob *job,
GList *files)
{
char *prompt;
int file_count;
int response;
/* Just Say Yes if the preference says not to confirm. */
if (!should_confirm_trash ())
{
return TRUE;
}
file_count = g_list_length (files);
g_assert (file_count > 0);
if (can_delete_files_without_confirm (files))
{
return TRUE;
}
if (file_count == 1)
{
prompt = f (_("Are you sure you want to permanently delete “%B”?"),
files->data);
}
else
{
prompt = f (ngettext ("Are you sure you want to permanently delete "
"the %'d selected item?",
"Are you sure you want to permanently delete "
"the %'d selected items?", file_count),
file_count);
}
response = run_warning (job,
prompt,
f (_("If you delete an item, it will be permanently lost.")),
NULL,
FALSE,
CANCEL, DELETE,
NULL);
return response == 1;
}
static void
report_delete_progress (CommonJob *job,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
int files_left;
double elapsed, transfer_rate;
int remaining_time;
gint64 now;
char *details;
char *status;
DeleteJob *delete_job;
delete_job = (DeleteJob *) job;
now = g_get_monotonic_time ();
files_left = source_info->num_files - transfer_info->num_files;
/* Races and whatnot could cause this to be negative... */
if (files_left < 0)
{
files_left = 0;
}
/* If the number of files left is 0, we want to update the status without
* considering this time, since we want to change the status to completed
* and probably we won't get more calls to this function */
if (transfer_info->last_report_time != 0 &&
ABS ((gint64) (transfer_info->last_report_time - now)) < 100 * NSEC_PER_MICROSEC &&
files_left > 0)
{
return;
}
transfer_info->last_report_time = now;
if (source_info->num_files == 1)
{
if (files_left == 0)
{
status = _("Deleted “%B”");
}
else
{
status = _("Deleting “%B”");
}
nautilus_progress_info_take_status (job->progress,
f (status,
(GFile *) delete_job->files->data));
}
else
{
if (files_left == 0)
{
status = ngettext ("Deleted %'d file",
"Deleted %'d files",
source_info->num_files);
}
else
{
status = ngettext ("Deleting %'d file",
"Deleting %'d files",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files));
}
elapsed = g_timer_elapsed (job->time, NULL);
transfer_rate = 0;
remaining_time = INT_MAX;
if (elapsed > 0)
{
transfer_rate = transfer_info->num_files / elapsed;
if (transfer_rate > 0)
{
remaining_time = (source_info->num_files - transfer_info->num_files) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE)
{
if (files_left > 0)
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files + 1,
source_info->num_files);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
else
{
if (files_left > 0)
{
gchar *time_left_message;
gchar *files_per_second_message;
gchar *concat_detail;
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4 files/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
time_left_message = ngettext ("%'d / %'d \xE2\x80\x94 %T left",
"%'d / %'d \xE2\x80\x94 %T left",
seconds_count_format_time_units (remaining_time));
transfer_rate += 0.5;
files_per_second_message = ngettext ("(%d file/sec)",
"(%d files/sec)",
(int) transfer_rate);
concat_detail = g_strconcat (time_left_message, " ", files_per_second_message, NULL);
details = f (concat_detail,
transfer_info->num_files + 1, source_info->num_files,
remaining_time,
(int) transfer_rate);
g_free (concat_detail);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
nautilus_progress_info_take_details (job->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (job->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (job->progress,
elapsed);
}
if (source_info->num_files != 0)
{
nautilus_progress_info_set_progress (job->progress, transfer_info->num_files, source_info->num_files);
}
}
typedef void (*DeleteCallback) (GFile *file,
GError *error,
gpointer callback_data);
static gboolean
delete_file_recursively (GFile *file,
GCancellable *cancellable,
DeleteCallback callback,
gpointer callback_data)
{
gboolean success;
g_autoptr (GError) error = NULL;
do
{
g_autoptr (GFileEnumerator) enumerator = NULL;
success = g_file_delete (file, cancellable, &error);
if (success ||
!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_EMPTY))
{
break;
}
g_clear_error (&error);
enumerator = g_file_enumerate_children (file,
G_FILE_ATTRIBUTE_STANDARD_NAME,
G_FILE_QUERY_INFO_NONE,
cancellable, &error);
if (enumerator)
{
GFileInfo *info;
success = TRUE;
info = g_file_enumerator_next_file (enumerator,
cancellable,
&error);
while (info != NULL)
{
g_autoptr (GFile) child = NULL;
child = g_file_enumerator_get_child (enumerator, info);
success = success && delete_file_recursively (child,
cancellable,
callback,
callback_data);
g_object_unref (info);
info = g_file_enumerator_next_file (enumerator,
cancellable,
&error);
}
}
if (error != NULL)
{
success = FALSE;
}
}
while (success);
if (callback)
{
callback (file, error, callback_data);
}
return success;
}
typedef struct
{
CommonJob *job;
SourceInfo *source_info;
TransferInfo *transfer_info;
} DeleteData;
static void
file_deleted_callback (GFile *file,
GError *error,
gpointer callback_data)
{
DeleteData *data = callback_data;
CommonJob *job;
SourceInfo *source_info;
TransferInfo *transfer_info;
GFileType file_type;
char *primary;
char *secondary;
char *details = NULL;
int response;
job = data->job;
source_info = data->source_info;
transfer_info = data->transfer_info;
data->transfer_info->num_files++;
if (error == NULL)
{
nautilus_file_changes_queue_file_removed (file);
report_delete_progress (data->job, data->source_info, data->transfer_info);
return;
}
if (job_aborted (job) ||
job->skip_all_error ||
should_skip_file (job, file) ||
should_skip_readdir_error (job, file))
{
return;
}
primary = f (_("Error while deleting."));
file_type = g_file_query_file_type (file,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable);
if (file_type == G_FILE_TYPE_DIRECTORY)
{
secondary = IS_IO_ERROR (error, PERMISSION_DENIED) ?
f (_("There was an error deleting the folder “%B”."),
file) :
f (_("You do not have sufficient permissions to delete the folder “%B”."),
file);
}
else
{
secondary = IS_IO_ERROR (error, PERMISSION_DENIED) ?
f (_("There was an error deleting the file “%B”."),
file) :
f (_("You do not have sufficient permissions to delete the file “%B”."),
file);
}
details = error->message;
response = run_cancel_or_skip_warning (job,
primary,
secondary,
details,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* skip all */
job->skip_all_error = TRUE;
}
}
static void
delete_files (CommonJob *job,
GList *files,
int *files_skipped)
{
GList *l;
GFile *file;
SourceInfo source_info;
TransferInfo transfer_info;
DeleteData data;
if (job_aborted (job))
{
return;
}
scan_sources (files,
&source_info,
job,
OP_KIND_DELETE);
if (job_aborted (job))
{
return;
}
g_timer_start (job->time);
memset (&transfer_info, 0, sizeof (transfer_info));
report_delete_progress (job, &source_info, &transfer_info);
data.job = job;
data.source_info = &source_info;
data.transfer_info = &transfer_info;
for (l = files;
l != NULL && !job_aborted (job);
l = l->next)
{
gboolean success;
file = l->data;
if (should_skip_file (job, file))
{
(*files_skipped)++;
continue;
}
success = delete_file_recursively (file, job->cancellable,
file_deleted_callback,
&data);
if (!success)
{
(*files_skipped)++;
}
}
}
static void
report_trash_progress (CommonJob *job,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
int files_left;
double elapsed, transfer_rate;
int remaining_time;
gint64 now;
char *details;
char *status;
DeleteJob *delete_job;
delete_job = (DeleteJob *) job;
now = g_get_monotonic_time ();
files_left = source_info->num_files - transfer_info->num_files;
/* Races and whatnot could cause this to be negative... */
if (files_left < 0)
{
files_left = 0;
}
/* If the number of files left is 0, we want to update the status without
* considering this time, since we want to change the status to completed
* and probably we won't get more calls to this function */
if (transfer_info->last_report_time != 0 &&
ABS ((gint64) (transfer_info->last_report_time - now)) < 100 * NSEC_PER_MICROSEC &&
files_left > 0)
{
return;
}
transfer_info->last_report_time = now;
if (source_info->num_files == 1)
{
if (files_left > 0)
{
status = _("Trashing “%B”");
}
else
{
status = _("Trashed “%B”");
}
nautilus_progress_info_take_status (job->progress,
f (status,
(GFile *) delete_job->files->data));
}
else
{
if (files_left > 0)
{
status = ngettext ("Trashing %'d file",
"Trashing %'d files",
source_info->num_files);
}
else
{
status = ngettext ("Trashed %'d file",
"Trashed %'d files",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files));
}
elapsed = g_timer_elapsed (job->time, NULL);
transfer_rate = 0;
remaining_time = INT_MAX;
if (elapsed > 0)
{
transfer_rate = transfer_info->num_files / elapsed;
if (transfer_rate > 0)
{
remaining_time = (source_info->num_files - transfer_info->num_files) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE)
{
if (files_left > 0)
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files + 1,
source_info->num_files);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
else
{
if (files_left > 0)
{
gchar *time_left_message;
gchar *files_per_second_message;
gchar *concat_detail;
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4 files/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
time_left_message = ngettext ("%'d / %'d \xE2\x80\x94 %T left",
"%'d / %'d \xE2\x80\x94 %T left",
seconds_count_format_time_units (remaining_time));
files_per_second_message = ngettext ("(%d file/sec)",
"(%d files/sec)",
(int) (transfer_rate + 0.5));
concat_detail = g_strconcat (time_left_message, " ", files_per_second_message, NULL);
details = f (concat_detail,
transfer_info->num_files + 1, source_info->num_files,
remaining_time,
(int) transfer_rate + 0.5);
g_free (concat_detail);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
nautilus_progress_info_set_details (job->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (job->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (job->progress,
elapsed);
}
if (source_info->num_files != 0)
{
nautilus_progress_info_set_progress (job->progress, transfer_info->num_files, source_info->num_files);
}
}
static void
trash_file (CommonJob *job,
GFile *file,
gboolean *skipped_file,
SourceInfo *source_info,
TransferInfo *transfer_info,
gboolean toplevel,
GList **to_delete)
{
GError *error;
char *primary, *secondary, *details;
int response;
if (should_skip_file (job, file))
{
*skipped_file = TRUE;
return;
}
error = NULL;
if (g_file_trash (file, job->cancellable, &error))
{
transfer_info->num_files++;
nautilus_file_changes_queue_file_removed (file);
if (job->undo_info != NULL)
{
nautilus_file_undo_info_trash_add_file (NAUTILUS_FILE_UNDO_INFO_TRASH (job->undo_info), file);
}
report_trash_progress (job, source_info, transfer_info);
return;
}
if (job->skip_all_error)
{
*skipped_file = TRUE;
goto skip;
}
if (job->delete_all)
{
*to_delete = g_list_prepend (*to_delete, file);
goto skip;
}
/* Translators: %B is a file name */
primary = f (_("“%B” can’t be put in the trash. Do you want to delete it immediately?"), file);
details = NULL;
secondary = NULL;
if (!IS_IO_ERROR (error, NOT_SUPPORTED))
{
details = error->message;
}
else if (!g_file_is_native (file))
{
secondary = f (_("This remote location does not support sending items to the trash."));
}
response = run_question (job,
primary,
secondary,
details,
(source_info->num_files - transfer_info->num_files) > 1,
CANCEL, SKIP_ALL, SKIP, DELETE_ALL, DELETE,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
((DeleteJob *) job)->user_cancel = TRUE;
abort_job (job);
}
else if (response == 1) /* skip all */
{
*skipped_file = TRUE;
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{
*skipped_file = TRUE;
job->skip_all_error = TRUE;
}
else if (response == 3) /* delete all */
{
*to_delete = g_list_prepend (*to_delete, file);
job->delete_all = TRUE;
}
else if (response == 4) /* delete */
{
*to_delete = g_list_prepend (*to_delete, file);
}
skip:
g_error_free (error);
}
static void
transfer_add_file_to_count (GFile *file,
CommonJob *job,
TransferInfo *transfer_info)
{
g_autoptr (GFileInfo) file_info = NULL;
if (g_cancellable_is_cancelled (job->cancellable))
{
return;
}
file_info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
NULL);
transfer_info->num_files++;
if (file_info != NULL)
{
transfer_info->num_bytes += g_file_info_get_size (file_info);
}
}
static void
trash_files (CommonJob *job,
GList *files,
int *files_skipped)
{
GList *l;
GFile *file;
GList *to_delete;
SourceInfo source_info;
TransferInfo transfer_info;
gboolean skipped_file;
if (job_aborted (job))
{
return;
}
scan_sources (files,
&source_info,
job,
OP_KIND_TRASH);
if (job_aborted (job))
{
return;
}
g_timer_start (job->time);
memset (&transfer_info, 0, sizeof (transfer_info));
report_trash_progress (job, &source_info, &transfer_info);
to_delete = NULL;
for (l = files;
l != NULL && !job_aborted (job);
l = l->next)
{
file = l->data;
skipped_file = FALSE;
trash_file (job, file,
&skipped_file,
&source_info, &transfer_info,
TRUE, &to_delete);
if (skipped_file)
{
(*files_skipped)++;
transfer_add_file_to_count (file, job, &transfer_info);
report_trash_progress (job, &source_info, &transfer_info);
}
}
if (to_delete)
{
to_delete = g_list_reverse (to_delete);
delete_files (job, to_delete, files_skipped);
g_list_free (to_delete);
}
}
static void
delete_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
DeleteJob *job;
GHashTable *debuting_uris;
job = user_data;
g_list_free_full (job->files, g_object_unref);
if (job->done_callback)
{
debuting_uris = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
job->done_callback (debuting_uris, job->user_cancel, job->done_callback_data);
g_hash_table_unref (debuting_uris);
}
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
delete_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
DeleteJob *job = task_data;
GList *to_trash_files;
GList *to_delete_files;
GList *l;
GFile *file;
gboolean confirmed;
CommonJob *common;
gboolean must_confirm_delete_in_trash;
gboolean must_confirm_delete;
int files_skipped;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
to_trash_files = NULL;
to_delete_files = NULL;
must_confirm_delete_in_trash = FALSE;
must_confirm_delete = FALSE;
files_skipped = 0;
for (l = job->files; l != NULL; l = l->next)
{
file = l->data;
if (job->try_trash &&
g_file_has_uri_scheme (file, "trash"))
{
must_confirm_delete_in_trash = TRUE;
to_delete_files = g_list_prepend (to_delete_files, file);
}
else if (can_delete_without_confirm (file))
{
to_delete_files = g_list_prepend (to_delete_files, file);
}
else
{
if (job->try_trash)
{
to_trash_files = g_list_prepend (to_trash_files, file);
}
else
{
must_confirm_delete = TRUE;
to_delete_files = g_list_prepend (to_delete_files, file);
}
}
}
if (to_delete_files != NULL)
{
to_delete_files = g_list_reverse (to_delete_files);
confirmed = TRUE;
if (must_confirm_delete_in_trash)
{
confirmed = confirm_delete_from_trash (common, to_delete_files);
}
else if (must_confirm_delete)
{
confirmed = confirm_delete_directly (common, to_delete_files);
}
if (confirmed)
{
delete_files (common, to_delete_files, &files_skipped);
}
else
{
job->user_cancel = TRUE;
}
}
if (to_trash_files != NULL)
{
to_trash_files = g_list_reverse (to_trash_files);
trash_files (common, to_trash_files, &files_skipped);
}
g_list_free (to_trash_files);
g_list_free (to_delete_files);
if (files_skipped == g_list_length (job->files))
{
/* User has skipped all files, report user cancel */
job->user_cancel = TRUE;
}
}
static void
trash_or_delete_internal (GList *files,
GtkWindow *parent_window,
gboolean try_trash,
NautilusDeleteCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
DeleteJob *job;
/* TODO: special case desktop icon link files ... */
job = op_job_new (DeleteJob, parent_window);
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->try_trash = try_trash;
job->user_cancel = FALSE;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
if (try_trash)
{
inhibit_power_manager ((CommonJob *) job, _("Trashing Files"));
}
else
{
inhibit_power_manager ((CommonJob *) job, _("Deleting Files"));
}
if (!nautilus_file_undo_manager_is_operating () && try_trash)
{
job->common.undo_info = nautilus_file_undo_info_trash_new (g_list_length (files));
}
task = g_task_new (NULL, NULL, delete_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, delete_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_trash_or_delete (GList *files,
GtkWindow *parent_window,
NautilusDeleteCallback done_callback,
gpointer done_callback_data)
{
trash_or_delete_internal (files, parent_window,
TRUE,
done_callback, done_callback_data);
}
void
nautilus_file_operations_delete (GList *files,
GtkWindow *parent_window,
NautilusDeleteCallback done_callback,
gpointer done_callback_data)
{
trash_or_delete_internal (files, parent_window,
FALSE,
done_callback, done_callback_data);
}
typedef struct
{
gboolean eject;
GMount *mount;
GMountOperation *mount_operation;
GtkWindow *parent_window;
NautilusUnmountCallback callback;
gpointer callback_data;
} UnmountData;
static void
unmount_data_free (UnmountData *data)
{
if (data->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (data->parent_window),
(gpointer *) &data->parent_window);
}
g_clear_object (&data->mount_operation);
g_object_unref (data->mount);
g_free (data);
}
static void
unmount_mount_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
UnmountData *data = user_data;
GError *error;
char *primary;
gboolean unmounted;
error = NULL;
if (data->eject)
{
unmounted = g_mount_eject_with_operation_finish (G_MOUNT (source_object),
res, &error);
}
else
{
unmounted = g_mount_unmount_with_operation_finish (G_MOUNT (source_object),
res, &error);
}
if (!unmounted)
{
if (error->code != G_IO_ERROR_FAILED_HANDLED)
{
if (data->eject)
{
primary = f (_("Unable to eject %V"), source_object);
}
else
{
primary = f (_("Unable to unmount %V"), source_object);
}
eel_show_error_dialog (primary,
error->message,
data->parent_window);
g_free (primary);
}
}
if (data->callback)
{
data->callback (data->callback_data);
}
if (error != NULL)
{
g_error_free (error);
}
unmount_data_free (data);
}
static void
do_unmount (UnmountData *data)
{
GMountOperation *mount_op;
if (data->mount_operation)
{
mount_op = g_object_ref (data->mount_operation);
}
else
{
mount_op = gtk_mount_operation_new (data->parent_window);
}
if (data->eject)
{
g_mount_eject_with_operation (data->mount,
0,
mount_op,
NULL,
unmount_mount_callback,
data);
}
else
{
g_mount_unmount_with_operation (data->mount,
0,
mount_op,
NULL,
unmount_mount_callback,
data);
}
g_object_unref (mount_op);
}
static gboolean
dir_has_files (GFile *dir)
{
GFileEnumerator *enumerator;
gboolean res;
GFileInfo *file_info;
res = FALSE;
enumerator = g_file_enumerate_children (dir,
G_FILE_ATTRIBUTE_STANDARD_NAME,
0,
NULL, NULL);
if (enumerator)
{
file_info = g_file_enumerator_next_file (enumerator, NULL, NULL);
if (file_info != NULL)
{
res = TRUE;
g_object_unref (file_info);
}
g_file_enumerator_close (enumerator, NULL, NULL);
g_object_unref (enumerator);
}
return res;
}
static GList *
get_trash_dirs_for_mount (GMount *mount)
{
GFile *root;
GFile *trash;
char *relpath;
GList *list;
root = g_mount_get_root (mount);
if (root == NULL)
{
return NULL;
}
list = NULL;
if (g_file_is_native (root))
{
relpath = g_strdup_printf (".Trash/%d", getuid ());
trash = g_file_resolve_relative_path (root, relpath);
g_free (relpath);
list = g_list_prepend (list, g_file_get_child (trash, "files"));
list = g_list_prepend (list, g_file_get_child (trash, "info"));
g_object_unref (trash);
relpath = g_strdup_printf (".Trash-%d", getuid ());
trash = g_file_get_child (root, relpath);
g_free (relpath);
list = g_list_prepend (list, g_file_get_child (trash, "files"));
list = g_list_prepend (list, g_file_get_child (trash, "info"));
g_object_unref (trash);
}
g_object_unref (root);
return list;
}
static gboolean
has_trash_files (GMount *mount)
{
GList *dirs, *l;
GFile *dir;
gboolean res;
dirs = get_trash_dirs_for_mount (mount);
res = FALSE;
for (l = dirs; l != NULL; l = l->next)
{
dir = l->data;
if (dir_has_files (dir))
{
res = TRUE;
break;
}
}
g_list_free_full (dirs, g_object_unref);
return res;
}
static gint
prompt_empty_trash (GtkWindow *parent_window)
{
gint result;
GtkWidget *dialog;
GdkScreen *screen;
screen = NULL;
if (parent_window != NULL)
{
screen = gtk_widget_get_screen (GTK_WIDGET (parent_window));
}
/* Do we need to be modal ? */
dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL,
GTK_MESSAGE_QUESTION, GTK_BUTTONS_NONE,
_("Do you want to empty the trash before you unmount?"));
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("In order to regain the "
"free space on this volume "
"the trash must be emptied. "
"All trashed items on the volume "
"will be permanently lost."));
gtk_dialog_add_buttons (GTK_DIALOG (dialog),
_("Do _not Empty Trash"), GTK_RESPONSE_REJECT,
CANCEL, GTK_RESPONSE_CANCEL,
_("Empty _Trash"), GTK_RESPONSE_ACCEPT, NULL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_ACCEPT);
gtk_window_set_title (GTK_WINDOW (dialog), ""); /* as per HIG */
gtk_window_set_skip_taskbar_hint (GTK_WINDOW (dialog), TRUE);
if (screen)
{
gtk_window_set_screen (GTK_WINDOW (dialog), screen);
}
atk_object_set_role (gtk_widget_get_accessible (dialog), ATK_ROLE_ALERT);
gtk_window_set_wmclass (GTK_WINDOW (dialog), "empty_trash",
"Nautilus");
/* Make transient for the window group */
gtk_widget_realize (dialog);
if (screen != NULL)
{
gdk_window_set_transient_for (gtk_widget_get_window (GTK_WIDGET (dialog)),
gdk_screen_get_root_window (screen));
}
result = gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_destroy (dialog);
return result;
}
static void
empty_trash_for_unmount_done (gboolean success,
gpointer user_data)
{
UnmountData *data = user_data;
do_unmount (data);
}
void
nautilus_file_operations_unmount_mount_full (GtkWindow *parent_window,
GMount *mount,
GMountOperation *mount_operation,
gboolean eject,
gboolean check_trash,
NautilusUnmountCallback callback,
gpointer callback_data)
{
UnmountData *data;
int response;
data = g_new0 (UnmountData, 1);
data->callback = callback;
data->callback_data = callback_data;
if (parent_window)
{
data->parent_window = parent_window;
g_object_add_weak_pointer (G_OBJECT (data->parent_window),
(gpointer *) &data->parent_window);
}
if (mount_operation)
{
data->mount_operation = g_object_ref (mount_operation);
}
data->eject = eject;
data->mount = g_object_ref (mount);
if (check_trash && has_trash_files (mount))
{
response = prompt_empty_trash (parent_window);
if (response == GTK_RESPONSE_ACCEPT)
{
GTask *task;
EmptyTrashJob *job;
job = op_job_new (EmptyTrashJob, parent_window);
job->should_confirm = FALSE;
job->trash_dirs = get_trash_dirs_for_mount (mount);
job->done_callback = empty_trash_for_unmount_done;
job->done_callback_data = data;
task = g_task_new (NULL, NULL, empty_trash_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, empty_trash_thread_func);
g_object_unref (task);
return;
}
else if (response == GTK_RESPONSE_CANCEL)
{
if (callback)
{
callback (callback_data);
}
unmount_data_free (data);
return;
}
}
do_unmount (data);
}
void
nautilus_file_operations_unmount_mount (GtkWindow *parent_window,
GMount *mount,
gboolean eject,
gboolean check_trash)
{
nautilus_file_operations_unmount_mount_full (parent_window, mount, NULL, eject,
check_trash, NULL, NULL);
}
static void
mount_callback_data_notify (gpointer data,
GObject *object)
{
GMountOperation *mount_op;
mount_op = G_MOUNT_OPERATION (data);
g_object_set_data (G_OBJECT (mount_op), "mount-callback", NULL);
g_object_set_data (G_OBJECT (mount_op), "mount-callback-data", NULL);
}
static void
volume_mount_cb (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
NautilusMountCallback mount_callback;
GObject *mount_callback_data_object;
GMountOperation *mount_op = user_data;
GError *error;
char *primary;
char *name;
gboolean success;
success = TRUE;
error = NULL;
if (!g_volume_mount_finish (G_VOLUME (source_object), res, &error))
{
if (error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED)
{
GtkWindow *parent;
parent = gtk_mount_operation_get_parent (GTK_MOUNT_OPERATION (mount_op));
name = g_volume_get_name (G_VOLUME (source_object));
primary = g_strdup_printf (_("Unable to access “%s”"), name);
g_free (name);
success = FALSE;
eel_show_error_dialog (primary,
error->message,
parent);
g_free (primary);
}
g_error_free (error);
}
mount_callback = (NautilusMountCallback)
g_object_get_data (G_OBJECT (mount_op), "mount-callback");
mount_callback_data_object =
g_object_get_data (G_OBJECT (mount_op), "mount-callback-data");
if (mount_callback != NULL)
{
(*mount_callback)(G_VOLUME (source_object),
success,
mount_callback_data_object);
if (mount_callback_data_object != NULL)
{
g_object_weak_unref (mount_callback_data_object,
mount_callback_data_notify,
mount_op);
}
}
g_object_unref (mount_op);
}
void
nautilus_file_operations_mount_volume (GtkWindow *parent_window,
GVolume *volume)
{
nautilus_file_operations_mount_volume_full (parent_window, volume,
NULL, NULL);
}
void
nautilus_file_operations_mount_volume_full (GtkWindow *parent_window,
GVolume *volume,
NautilusMountCallback mount_callback,
GObject *mount_callback_data_object)
{
GMountOperation *mount_op;
mount_op = gtk_mount_operation_new (parent_window);
g_mount_operation_set_password_save (mount_op, G_PASSWORD_SAVE_FOR_SESSION);
g_object_set_data (G_OBJECT (mount_op),
"mount-callback",
mount_callback);
if (mount_callback != NULL &&
mount_callback_data_object != NULL)
{
g_object_weak_ref (mount_callback_data_object,
mount_callback_data_notify,
mount_op);
}
g_object_set_data (G_OBJECT (mount_op),
"mount-callback-data",
mount_callback_data_object);
g_volume_mount (volume, 0, mount_op, NULL, volume_mount_cb, mount_op);
}
static void
report_preparing_count_progress (CommonJob *job,
SourceInfo *source_info)
{
char *s;
switch (source_info->op)
{
default:
case OP_KIND_COPY:
{
s = f (ngettext ("Preparing to copy %'d file (%S)",
"Preparing to copy %'d files (%S)",
source_info->num_files),
source_info->num_files, source_info->num_bytes);
}
break;
case OP_KIND_MOVE:
{
s = f (ngettext ("Preparing to move %'d file (%S)",
"Preparing to move %'d files (%S)",
source_info->num_files),
source_info->num_files, source_info->num_bytes);
}
break;
case OP_KIND_DELETE:
{
s = f (ngettext ("Preparing to delete %'d file (%S)",
"Preparing to delete %'d files (%S)",
source_info->num_files),
source_info->num_files, source_info->num_bytes);
}
break;
case OP_KIND_TRASH:
{
s = f (ngettext ("Preparing to trash %'d file",
"Preparing to trash %'d files",
source_info->num_files),
source_info->num_files);
}
break;
case OP_KIND_COMPRESS:
s = f (ngettext ("Preparing to compress %'d file",
"Preparing to compress %'d files",
source_info->num_files),
source_info->num_files);
}
nautilus_progress_info_take_details (job->progress, s);
nautilus_progress_info_pulse_progress (job->progress);
}
static void
count_file (GFileInfo *info,
CommonJob *job,
SourceInfo *source_info)
{
source_info->num_files += 1;
source_info->num_bytes += g_file_info_get_size (info);
if (source_info->num_files_since_progress++ > 100)
{
report_preparing_count_progress (job, source_info);
source_info->num_files_since_progress = 0;
}
}
static char *
get_scan_primary (OpKind kind)
{
switch (kind)
{
default:
case OP_KIND_COPY:
{
return f (_("Error while copying."));
}
case OP_KIND_MOVE:
{
return f (_("Error while moving."));
}
case OP_KIND_DELETE:
{
return f (_("Error while deleting."));
}
case OP_KIND_TRASH:
{
return f (_("Error while moving files to trash."));
}
case OP_KIND_COMPRESS:
return f (_("Error while compressing files."));
}
}
static void
scan_dir (GFile *dir,
SourceInfo *source_info,
CommonJob *job,
GQueue *dirs,
GHashTable *scanned)
{
GFileInfo *info;
GError *error;
GFile *subdir;
GFileEnumerator *enumerator;
char *primary, *secondary, *details;
int response;
SourceInfo saved_info;
saved_info = *source_info;
retry:
error = NULL;
enumerator = g_file_enumerate_children (dir,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (enumerator)
{
error = NULL;
while ((info = g_file_enumerator_next_file (enumerator, job->cancellable, &error)) != NULL)
{
g_autoptr (GFile) file = NULL;
g_autofree char *file_uri = NULL;
file = g_file_enumerator_get_child (enumerator, info);
file_uri = g_file_get_uri (file);
if (!g_hash_table_contains (scanned, file_uri))
{
g_hash_table_add (scanned, g_strdup (file_uri));
count_file (info, job, source_info);
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
subdir = g_file_get_child (dir,
g_file_info_get_name (info));
/* Push to head, since we want depth-first */
g_queue_push_head (dirs, subdir);
}
}
g_object_unref (info);
}
g_file_enumerator_close (enumerator, job->cancellable, NULL);
g_object_unref (enumerator);
if (error && IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else if (error)
{
primary = get_scan_primary (source_info->op);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("Files in the folder “%B” cannot be handled because you do "
"not have permissions to see them."), dir);
}
else
{
secondary = f (_("There was an error getting information about the files in the folder “%B”."), dir);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, RETRY, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
*source_info = saved_info;
goto retry;
}
else if (response == 2)
{
skip_readdir_error (job, dir);
}
else
{
g_assert_not_reached ();
}
}
}
else if (job->skip_all_error)
{
g_error_free (error);
skip_file (job, dir);
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else
{
primary = get_scan_primary (source_info->op);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The folder “%B” cannot be handled because you do not have "
"permissions to read it."), dir);
}
else
{
secondary = f (_("There was an error reading the folder “%B”."), dir);
details = error->message;
}
/* set show_all to TRUE here, as we don't know how many
* files we'll end up processing yet.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1 || response == 2)
{
if (response == 1)
{
job->skip_all_error = TRUE;
}
skip_file (job, dir);
}
else if (response == 3)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
}
}
static void
scan_file (GFile *file,
SourceInfo *source_info,
CommonJob *job,
GHashTable *scanned)
{
GFileInfo *info;
GError *error;
GQueue *dirs;
GFile *dir;
char *primary;
char *secondary;
char *details;
int response;
dirs = g_queue_new ();
retry:
error = NULL;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (info)
{
g_autofree char *file_uri = NULL;
file_uri = g_file_get_uri (file);
if (!g_hash_table_contains (scanned, file_uri))
{
g_hash_table_add (scanned, g_strdup (file_uri));
count_file (info, job, source_info);
/* trashing operation doesn't recurse */
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY &&
source_info->op != OP_KIND_TRASH)
{
g_queue_push_head (dirs, g_object_ref (file));
}
}
g_object_unref (info);
}
else if (job->skip_all_error)
{
g_error_free (error);
skip_file (job, file);
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else
{
primary = get_scan_primary (source_info->op);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The file “%B” cannot be handled because you do not have "
"permissions to read it."), file);
}
else
{
secondary = f (_("There was an error getting information about “%B”."), file);
details = error->message;
}
/* set show_all to TRUE here, as we don't know how many
* files we'll end up processing yet.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1 || response == 2)
{
if (response == 1)
{
job->skip_all_error = TRUE;
}
skip_file (job, file);
}
else if (response == 3)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
}
while (!job_aborted (job) &&
(dir = g_queue_pop_head (dirs)) != NULL)
{
scan_dir (dir, source_info, job, dirs, scanned);
g_object_unref (dir);
}
/* Free all from queue if we exited early */
g_queue_foreach (dirs, (GFunc) g_object_unref, NULL);
g_queue_free (dirs);
}
static void
scan_sources (GList *files,
SourceInfo *source_info,
CommonJob *job,
OpKind kind)
{
GList *l;
GFile *file;
g_autoptr (GHashTable) scanned = NULL;
memset (source_info, 0, sizeof (SourceInfo));
source_info->op = kind;
scanned = g_hash_table_new_full (g_str_hash,
g_str_equal,
(GDestroyNotify) g_free,
NULL);
report_preparing_count_progress (job, source_info);
for (l = files; l != NULL && !job_aborted (job); l = l->next)
{
file = l->data;
scan_file (file,
source_info,
job,
scanned);
}
/* Make sure we report the final count */
report_preparing_count_progress (job, source_info);
}
static void
verify_destination (CommonJob *job,
GFile *dest,
char **dest_fs_id,
goffset required_size)
{
GFileInfo *info, *fsinfo;
GError *error;
guint64 free_size;
guint64 size_difference;
char *primary, *secondary, *details;
int response;
GFileType file_type;
gboolean dest_is_symlink = FALSE;
if (dest_fs_id)
{
*dest_fs_id = NULL;
}
retry:
error = NULL;
info = g_file_query_info (dest,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_ID_FILESYSTEM,
dest_is_symlink ? G_FILE_QUERY_INFO_NONE : G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (info == NULL)
{
if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
return;
}
primary = f (_("Error while copying to “%B”."), dest);
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("You do not have permissions to access the destination folder."));
}
else
{
secondary = f (_("There was an error getting information about the destination."));
details = error->message;
}
response = run_error (job,
primary,
secondary,
details,
FALSE,
CANCEL, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
return;
}
file_type = g_file_info_get_file_type (info);
if (!dest_is_symlink && file_type == G_FILE_TYPE_SYMBOLIC_LINK)
{
/* Record that destination is a symlink and do real stat() once again */
dest_is_symlink = TRUE;
g_object_unref (info);
goto retry;
}
if (dest_fs_id)
{
*dest_fs_id =
g_strdup (g_file_info_get_attribute_string (info,
G_FILE_ATTRIBUTE_ID_FILESYSTEM));
}
g_object_unref (info);
if (file_type != G_FILE_TYPE_DIRECTORY)
{
primary = f (_("Error while copying to “%B”."), dest);
secondary = f (_("The destination is not a folder."));
run_error (job,
primary,
secondary,
NULL,
FALSE,
CANCEL,
NULL);
abort_job (job);
return;
}
if (dest_is_symlink)
{
/* We can't reliably statfs() destination if it's a symlink, thus not doing any further checks. */
return;
}
fsinfo = g_file_query_filesystem_info (dest,
G_FILE_ATTRIBUTE_FILESYSTEM_FREE ","
G_FILE_ATTRIBUTE_FILESYSTEM_READONLY,
job->cancellable,
NULL);
if (fsinfo == NULL)
{
/* All sorts of things can go wrong getting the fs info (like not supported)
* only check these things if the fs returns them
*/
return;
}
if (required_size > 0 &&
g_file_info_has_attribute (fsinfo, G_FILE_ATTRIBUTE_FILESYSTEM_FREE))
{
free_size = g_file_info_get_attribute_uint64 (fsinfo,
G_FILE_ATTRIBUTE_FILESYSTEM_FREE);
if (free_size < required_size)
{
size_difference = required_size - free_size;
primary = f (_("Error while copying to “%B”."), dest);
secondary = f (_("There is not enough space on the destination. Try to remove files to make space."));
details = f (_("%S more space is required to copy to the destination."), size_difference);
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL,
COPY_FORCE,
RETRY,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 2)
{
goto retry;
}
else if (response == 1)
{
/* We are forced to copy - just fall through ... */
}
else
{
g_assert_not_reached ();
}
}
}
if (!job_aborted (job) &&
g_file_info_get_attribute_boolean (fsinfo,
G_FILE_ATTRIBUTE_FILESYSTEM_READONLY))
{
primary = f (_("Error while copying to “%B”."), dest);
secondary = f (_("The destination is read-only."));
run_error (job,
primary,
secondary,
NULL,
FALSE,
CANCEL,
NULL);
g_error_free (error);
abort_job (job);
}
g_object_unref (fsinfo);
}
static void
report_copy_progress (CopyMoveJob *copy_job,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
int files_left;
goffset total_size;
double elapsed, transfer_rate;
int remaining_time;
guint64 now;
CommonJob *job;
gboolean is_move;
gchar *status;
char *details;
job = (CommonJob *) copy_job;
is_move = copy_job->is_move;
now = g_get_monotonic_time ();
files_left = source_info->num_files - transfer_info->num_files;
/* Races and whatnot could cause this to be negative... */
if (files_left < 0)
{
files_left = 0;
}
/* If the number of files left is 0, we want to update the status without
* considering this time, since we want to change the status to completed
* and probably we won't get more calls to this function */
if (transfer_info->last_report_time != 0 &&
ABS ((gint64) (transfer_info->last_report_time - now)) < 100 * NSEC_PER_MICROSEC &&
files_left > 0)
{
return;
}
transfer_info->last_report_time = now;
if (files_left != transfer_info->last_reported_files_left ||
transfer_info->last_reported_files_left == 0)
{
/* Avoid changing this unless files_left changed since last time */
transfer_info->last_reported_files_left = files_left;
if (source_info->num_files == 1)
{
if (copy_job->destination != NULL)
{
if (is_move)
{
if (files_left > 0)
{
status = _("Moving “%B” to “%B”");
}
else
{
status = _("Moved “%B” to “%B”");
}
}
else
{
if (files_left > 0)
{
status = _("Copying “%B” to “%B”");
}
else
{
status = _("Copied “%B” to “%B”");
}
}
nautilus_progress_info_take_status (job->progress,
f (status,
copy_job->fake_display_source != NULL ?
copy_job->fake_display_source :
(GFile *) copy_job->files->data,
copy_job->destination));
}
else
{
if (files_left > 0)
{
status = _("Duplicating “%B”");
}
else
{
status = _("Duplicated “%B”");
}
nautilus_progress_info_take_status (job->progress,
f (status,
(GFile *) copy_job->files->data));
}
}
else if (copy_job->files != NULL)
{
if (copy_job->destination != NULL)
{
if (files_left > 0)
{
if (is_move)
{
status = ngettext ("Moving %'d file to “%B”",
"Moving %'d files to “%B”",
source_info->num_files);
}
else
{
status = ngettext ("Copying %'d file to “%B”",
"Copying %'d files to “%B”",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
(GFile *) copy_job->destination));
}
else
{
if (is_move)
{
status = ngettext ("Moved %'d file to “%B”",
"Moved %'d files to “%B”",
source_info->num_files);
}
else
{
status = ngettext ("Copied %'d file to “%B”",
"Copied %'d files to “%B”",
source_info->num_files);
}
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
(GFile *) copy_job->destination));
}
}
else
{
GFile *parent;
parent = g_file_get_parent (copy_job->files->data);
if (files_left > 0)
{
status = ngettext ("Duplicating %'d file in “%B”",
"Duplicating %'d files in “%B”",
source_info->num_files);
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
parent));
}
else
{
status = ngettext ("Duplicated %'d file in “%B”",
"Duplicated %'d files in “%B”",
source_info->num_files);
nautilus_progress_info_take_status (job->progress,
f (status,
source_info->num_files,
parent));
}
g_object_unref (parent);
}
}
}
total_size = MAX (source_info->num_bytes, transfer_info->num_bytes);
elapsed = g_timer_elapsed (job->time, NULL);
transfer_rate = 0;
remaining_time = INT_MAX;
if (elapsed > 0)
{
transfer_rate = transfer_info->num_bytes / elapsed;
if (transfer_rate > 0)
{
remaining_time = (total_size - transfer_info->num_bytes) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE &&
transfer_rate > 0)
{
if (source_info->num_files == 1)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", so something like "4 kb / 4 MB" */
details = f (_("%S / %S"), transfer_info->num_bytes, total_size);
}
else
{
if (files_left > 0)
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files + 1,
source_info->num_files);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
}
else
{
if (source_info->num_files == 1)
{
if (files_left > 0)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", %T to a time duration like
* "2 minutes". So the whole thing will be something like "2 kb / 4 MB -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%S / %S \xE2\x80\x94 %T left (%S/sec)",
"%S / %S \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
transfer_info->num_bytes, total_size,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB". */
details = f (_("%S / %S"),
transfer_info->num_bytes,
total_size);
}
}
else
{
if (files_left > 0)
{
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
"%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
transfer_info->num_files + 1, source_info->num_files,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
transfer_info->num_files,
source_info->num_files);
}
}
}
nautilus_progress_info_take_details (job->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (job->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (job->progress,
elapsed);
}
nautilus_progress_info_set_progress (job->progress, transfer_info->num_bytes, total_size);
}
static int
get_max_name_length (GFile *file_dir)
{
int max_length;
char *dir;
long max_path;
long max_name;
max_length = -1;
if (!g_file_has_uri_scheme (file_dir, "file"))
{
return max_length;
}
dir = g_file_get_path (file_dir);
if (!dir)
{
return max_length;
}
max_path = pathconf (dir, _PC_PATH_MAX);
max_name = pathconf (dir, _PC_NAME_MAX);
if (max_name == -1 && max_path == -1)
{
max_length = -1;
}
else if (max_name == -1 && max_path != -1)
{
max_length = max_path - (strlen (dir) + 1);
}
else if (max_name != -1 && max_path == -1)
{
max_length = max_name;
}
else
{
int leftover;
leftover = max_path - (strlen (dir) + 1);
max_length = MIN (leftover, max_name);
}
g_free (dir);
return max_length;
}
#define FAT_FORBIDDEN_CHARACTERS "/:;*?\"<>"
static gboolean
fat_str_replace (char *str,
char replacement)
{
gboolean success;
int i;
success = FALSE;
for (i = 0; str[i] != '\0'; i++)
{
if (strchr (FAT_FORBIDDEN_CHARACTERS, str[i]) ||
str[i] < 32)
{
success = TRUE;
str[i] = replacement;
}
}
return success;
}
static gboolean
make_file_name_valid_for_dest_fs (char *filename,
const char *dest_fs_type)
{
if (dest_fs_type != NULL && filename != NULL)
{
if (!strcmp (dest_fs_type, "fat") ||
!strcmp (dest_fs_type, "vfat") ||
!strcmp (dest_fs_type, "msdos") ||
!strcmp (dest_fs_type, "msdosfs"))
{
gboolean ret;
int i, old_len;
ret = fat_str_replace (filename, '_');
old_len = strlen (filename);
for (i = 0; i < old_len; i++)
{
if (filename[i] != ' ')
{
g_strchomp (filename);
ret |= (old_len != strlen (filename));
break;
}
}
return ret;
}
}
return FALSE;
}
static GFile *
get_unique_target_file (GFile *src,
GFile *dest_dir,
gboolean same_fs,
const char *dest_fs_type,
int count)
{
const char *editname, *end;
char *basename, *new_name;
GFileInfo *info;
GFile *dest;
int max_length;
max_length = get_max_name_length (dest_dir);
dest = NULL;
info = g_file_query_info (src,
G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME,
0, NULL, NULL);
if (info != NULL)
{
editname = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME);
if (editname != NULL)
{
new_name = get_duplicate_name (editname, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
g_object_unref (info);
}
if (dest == NULL)
{
basename = g_file_get_basename (src);
if (g_utf8_validate (basename, -1, NULL))
{
new_name = get_duplicate_name (basename, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
if (dest == NULL)
{
end = strrchr (basename, '.');
if (end != NULL)
{
count += atoi (end + 1);
}
new_name = g_strdup_printf ("%s.%d", basename, count);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child (dest_dir, new_name);
g_free (new_name);
}
g_free (basename);
}
return dest;
}
static GFile *
get_target_file_for_link (GFile *src,
GFile *dest_dir,
const char *dest_fs_type,
int count)
{
const char *editname;
char *basename, *new_name;
GFileInfo *info;
GFile *dest;
int max_length;
max_length = get_max_name_length (dest_dir);
dest = NULL;
info = g_file_query_info (src,
G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME,
0, NULL, NULL);
if (info != NULL)
{
editname = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_EDIT_NAME);
if (editname != NULL)
{
new_name = get_link_name (editname, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
g_object_unref (info);
}
if (dest == NULL)
{
basename = g_file_get_basename (src);
make_file_name_valid_for_dest_fs (basename, dest_fs_type);
if (g_utf8_validate (basename, -1, NULL))
{
new_name = get_link_name (basename, count, max_length);
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, new_name, NULL);
g_free (new_name);
}
if (dest == NULL)
{
if (count == 1)
{
new_name = g_strdup_printf ("%s.lnk", basename);
}
else
{
new_name = g_strdup_printf ("%s.lnk%d", basename, count);
}
make_file_name_valid_for_dest_fs (new_name, dest_fs_type);
dest = g_file_get_child (dest_dir, new_name);
g_free (new_name);
}
g_free (basename);
}
return dest;
}
static GFile *
get_target_file_with_custom_name (GFile *src,
GFile *dest_dir,
const char *dest_fs_type,
gboolean same_fs,
const gchar *custom_name)
{
char *basename;
GFile *dest;
GFileInfo *info;
char *copyname;
dest = NULL;
if (custom_name != NULL)
{
copyname = g_strdup (custom_name);
make_file_name_valid_for_dest_fs (copyname, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, copyname, NULL);
g_free (copyname);
}
if (dest == NULL && !same_fs)
{
info = g_file_query_info (src,
G_FILE_ATTRIBUTE_STANDARD_COPY_NAME ","
G_FILE_ATTRIBUTE_TRASH_ORIG_PATH,
0, NULL, NULL);
if (info)
{
copyname = NULL;
/* if file is being restored from trash make sure it uses its original name */
if (g_file_has_uri_scheme (src, "trash"))
{
copyname = g_path_get_basename (g_file_info_get_attribute_byte_string (info, G_FILE_ATTRIBUTE_TRASH_ORIG_PATH));
}
if (copyname == NULL)
{
copyname = g_strdup (g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_STANDARD_COPY_NAME));
}
if (copyname)
{
make_file_name_valid_for_dest_fs (copyname, dest_fs_type);
dest = g_file_get_child_for_display_name (dest_dir, copyname, NULL);
g_free (copyname);
}
g_object_unref (info);
}
}
if (dest == NULL)
{
basename = g_file_get_basename (src);
make_file_name_valid_for_dest_fs (basename, dest_fs_type);
dest = g_file_get_child (dest_dir, basename);
g_free (basename);
}
return dest;
}
static GFile *
get_target_file (GFile *src,
GFile *dest_dir,
const char *dest_fs_type,
gboolean same_fs)
{
return get_target_file_with_custom_name (src, dest_dir, dest_fs_type, same_fs, NULL);
}
static gboolean
has_fs_id (GFile *file,
const char *fs_id)
{
const char *id;
GFileInfo *info;
gboolean res;
res = FALSE;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_ID_FILESYSTEM,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
NULL, NULL);
if (info)
{
id = g_file_info_get_attribute_string (info, G_FILE_ATTRIBUTE_ID_FILESYSTEM);
if (id && strcmp (id, fs_id) == 0)
{
res = TRUE;
}
g_object_unref (info);
}
return res;
}
static gboolean
is_dir (GFile *file)
{
GFileInfo *info;
gboolean res;
res = FALSE;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
NULL, NULL);
if (info)
{
res = g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY;
g_object_unref (info);
}
return res;
}
static GFile *
map_possibly_volatile_file_to_real (GFile *volatile_file,
GCancellable *cancellable,
GError **error)
{
GFile *real_file = NULL;
GFileInfo *info = NULL;
info = g_file_query_info (volatile_file,
G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK ","
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE ","
G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
cancellable,
error);
if (info == NULL)
{
return NULL;
}
else
{
gboolean is_volatile;
is_volatile = g_file_info_get_attribute_boolean (info,
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE);
if (is_volatile)
{
const gchar *target;
target = g_file_info_get_symlink_target (info);
real_file = g_file_resolve_relative_path (volatile_file, target);
}
}
g_object_unref (info);
if (real_file == NULL)
{
real_file = g_object_ref (volatile_file);
}
return real_file;
}
static GFile *
map_possibly_volatile_file_to_real_on_write (GFile *volatile_file,
GFileOutputStream *stream,
GCancellable *cancellable,
GError **error)
{
GFile *real_file = NULL;
GFileInfo *info = NULL;
info = g_file_output_stream_query_info (stream,
G_FILE_ATTRIBUTE_STANDARD_IS_SYMLINK ","
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE ","
G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
cancellable,
error);
if (info == NULL)
{
return NULL;
}
else
{
gboolean is_volatile;
is_volatile = g_file_info_get_attribute_boolean (info,
G_FILE_ATTRIBUTE_STANDARD_IS_VOLATILE);
if (is_volatile)
{
const gchar *target;
target = g_file_info_get_symlink_target (info);
real_file = g_file_resolve_relative_path (volatile_file, target);
}
}
g_object_unref (info);
if (real_file == NULL)
{
real_file = g_object_ref (volatile_file);
}
return real_file;
}
static void copy_move_file (CopyMoveJob *job,
GFile *src,
GFile *dest_dir,
gboolean same_fs,
gboolean unique_names,
char **dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info,
GHashTable *debuting_files,
GdkPoint *point,
gboolean overwrite,
gboolean *skipped_file,
gboolean readonly_source_fs);
typedef enum
{
CREATE_DEST_DIR_RETRY,
CREATE_DEST_DIR_FAILED,
CREATE_DEST_DIR_SUCCESS
} CreateDestDirResult;
static CreateDestDirResult
create_dest_dir (CommonJob *job,
GFile *src,
GFile **dest,
gboolean same_fs,
char **dest_fs_type)
{
GError *error;
GFile *new_dest, *dest_dir;
char *primary, *secondary, *details;
int response;
gboolean handled_invalid_filename;
gboolean res;
handled_invalid_filename = *dest_fs_type != NULL;
retry:
/* First create the directory, then copy stuff to it before
* copying the attributes, because we need to be sure we can write to it */
error = NULL;
res = g_file_make_directory (*dest, job->cancellable, &error);
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (*dest, job->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (*dest);
*dest = real;
}
}
if (!res)
{
if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
return CREATE_DEST_DIR_FAILED;
}
else if (IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
dest_dir = g_file_get_parent (*dest);
if (dest_dir != NULL)
{
*dest_fs_type = query_fs_type (dest_dir, job->cancellable);
new_dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
g_object_unref (dest_dir);
if (!g_file_equal (*dest, new_dest))
{
g_object_unref (*dest);
*dest = new_dest;
g_error_free (error);
return CREATE_DEST_DIR_RETRY;
}
else
{
g_object_unref (new_dest);
}
}
}
primary = f (_("Error while copying."));
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The folder “%B” cannot be copied because you do not have "
"permissions to create it in the destination."), src);
}
else
{
secondary = f (_("There was an error creating the folder “%B”."), src);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* Skip: Do Nothing */
}
else if (response == 2)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
return CREATE_DEST_DIR_FAILED;
}
nautilus_file_changes_queue_file_added (*dest);
if (job->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (job->undo_info),
src, *dest);
}
return CREATE_DEST_DIR_SUCCESS;
}
/* a return value of FALSE means retry, i.e.
* the destination has changed and the source
* is expected to re-try the preceding
* g_file_move() or g_file_copy() call with
* the new destination.
*/
static gboolean
copy_move_directory (CopyMoveJob *copy_job,
GFile *src,
GFile **dest,
gboolean same_fs,
gboolean create_dest,
char **parent_dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info,
GHashTable *debuting_files,
gboolean *skipped_file,
gboolean readonly_source_fs)
{
GFileInfo *info;
GError *error;
GFile *src_file;
GFileEnumerator *enumerator;
char *primary, *secondary, *details;
char *dest_fs_type;
int response;
gboolean skip_error;
gboolean local_skipped_file;
CommonJob *job;
GFileCopyFlags flags;
job = (CommonJob *) copy_job;
if (create_dest)
{
switch (create_dest_dir (job, src, dest, same_fs, parent_dest_fs_type))
{
case CREATE_DEST_DIR_RETRY:
{
/* next time copy_move_directory() is called,
* create_dest will be FALSE if a directory already
* exists under the new name (i.e. WOULD_RECURSE)
*/
return FALSE;
}
case CREATE_DEST_DIR_FAILED:
{
*skipped_file = TRUE;
return TRUE;
}
case CREATE_DEST_DIR_SUCCESS:
default:
{
}
break;
}
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (*dest), GINT_TO_POINTER (TRUE));
}
}
local_skipped_file = FALSE;
dest_fs_type = NULL;
skip_error = should_skip_readdir_error (job, src);
retry:
error = NULL;
enumerator = g_file_enumerate_children (src,
G_FILE_ATTRIBUTE_STANDARD_NAME,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
&error);
if (enumerator)
{
error = NULL;
while (!job_aborted (job) &&
(info = g_file_enumerator_next_file (enumerator, job->cancellable, skip_error ? NULL : &error)) != NULL)
{
src_file = g_file_get_child (src,
g_file_info_get_name (info));
copy_move_file (copy_job, src_file, *dest, same_fs, FALSE, &dest_fs_type,
source_info, transfer_info, NULL, NULL, FALSE, &local_skipped_file,
readonly_source_fs);
if (local_skipped_file)
{
transfer_add_file_to_count (src_file, job, transfer_info);
report_copy_progress (copy_job, source_info, transfer_info);
}
g_object_unref (src_file);
g_object_unref (info);
}
g_file_enumerator_close (enumerator, job->cancellable, NULL);
g_object_unref (enumerator);
if (error && IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else if (error)
{
if (copy_job->is_move)
{
primary = f (_("Error while moving."));
}
else
{
primary = f (_("Error while copying."));
}
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("Files in the folder “%B” cannot be copied because you do "
"not have permissions to see them."), src);
}
else
{
secondary = f (_("There was an error getting information about the files in the folder “%B”."), src);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, _("_Skip files"),
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* Skip: Do Nothing */
local_skipped_file = TRUE;
}
else
{
g_assert_not_reached ();
}
}
/* Count the copied directory as a file */
transfer_info->num_files++;
report_copy_progress (copy_job, source_info, transfer_info);
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (*dest), GINT_TO_POINTER (create_dest));
}
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
else
{
if (copy_job->is_move)
{
primary = f (_("Error while moving."));
}
else
{
primary = f (_("Error while copying."));
}
details = NULL;
if (IS_IO_ERROR (error, PERMISSION_DENIED))
{
secondary = f (_("The folder “%B” cannot be copied because you do not have "
"permissions to read it."), src);
}
else
{
secondary = f (_("There was an error reading the folder “%B”."), src);
details = error->message;
}
response = run_warning (job,
primary,
secondary,
details,
FALSE,
CANCEL, SKIP, RETRY,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* Skip: Do Nothing */
local_skipped_file = TRUE;
}
else if (response == 2)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
}
if (create_dest)
{
flags = (readonly_source_fs) ? G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_TARGET_DEFAULT_PERMS
: G_FILE_COPY_NOFOLLOW_SYMLINKS;
/* Ignore errors here. Failure to copy metadata is not a hard error */
g_file_copy_attributes (src, *dest,
flags,
job->cancellable, NULL);
}
if (!job_aborted (job) && copy_job->is_move &&
/* Don't delete source if there was a skipped file */
!local_skipped_file)
{
if (!g_file_delete (src, job->cancellable, &error))
{
if (job->skip_all_error)
{
goto skip;
}
primary = f (_("Error while moving “%B”."), src);
secondary = f (_("Could not remove the source folder."));
details = error->message;
response = run_cancel_or_skip_warning (job,
primary,
secondary,
details,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
local_skipped_file = TRUE;
}
else if (response == 2) /* skip */
{
local_skipped_file = TRUE;
}
else
{
g_assert_not_reached ();
}
skip:
g_error_free (error);
}
}
if (local_skipped_file)
{
*skipped_file = TRUE;
}
g_free (dest_fs_type);
return TRUE;
}
typedef struct
{
CommonJob *job;
GFile *source;
} DeleteExistingFileData;
static void
existing_file_removed_callback (GFile *file,
GError *error,
gpointer callback_data)
{
DeleteExistingFileData *data = callback_data;
CommonJob *job;
GFile *source;
GFileType file_type;
char *primary;
char *secondary;
char *details = NULL;
int response;
job = data->job;
source = data->source;
if (error == NULL)
{
nautilus_file_changes_queue_file_removed (file);
return;
}
if (job_aborted (job) || job->skip_all_error)
{
return;
}
primary = f (_("Error while copying “%B”."), source);
file_type = g_file_query_file_type (file,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable);
if (file_type == G_FILE_TYPE_DIRECTORY)
{
secondary = f (_("Could not remove the already existing folder %F."),
file);
}
else
{
secondary = f (_("Could not remove the already existing file %F."),
file);
}
details = error->message;
/* set show_all to TRUE here, as we don't know how many
* files we'll end up processing yet.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1)
{
/* skip all */
job->skip_all_error = TRUE;
}
}
typedef struct
{
CopyMoveJob *job;
goffset last_size;
SourceInfo *source_info;
TransferInfo *transfer_info;
} ProgressData;
static void
copy_file_progress_callback (goffset current_num_bytes,
goffset total_num_bytes,
gpointer user_data)
{
ProgressData *pdata;
goffset new_size;
pdata = user_data;
new_size = current_num_bytes - pdata->last_size;
if (new_size > 0)
{
pdata->transfer_info->num_bytes += new_size;
pdata->last_size = current_num_bytes;
report_copy_progress (pdata->job,
pdata->source_info,
pdata->transfer_info);
}
}
static gboolean
test_dir_is_parent (GFile *child,
GFile *root)
{
GFile *f, *tmp;
f = g_file_dup (child);
while (f)
{
if (g_file_equal (f, root))
{
g_object_unref (f);
return TRUE;
}
tmp = f;
f = g_file_get_parent (f);
g_object_unref (tmp);
}
if (f)
{
g_object_unref (f);
}
return FALSE;
}
static char *
query_fs_type (GFile *file,
GCancellable *cancellable)
{
GFileInfo *fsinfo;
char *ret;
ret = NULL;
fsinfo = g_file_query_filesystem_info (file,
G_FILE_ATTRIBUTE_FILESYSTEM_TYPE,
cancellable,
NULL);
if (fsinfo != NULL)
{
ret = g_strdup (g_file_info_get_attribute_string (fsinfo, G_FILE_ATTRIBUTE_FILESYSTEM_TYPE));
g_object_unref (fsinfo);
}
if (ret == NULL)
{
/* ensure that we don't attempt to query
* the FS type for each file in a given
* directory, if it can't be queried. */
ret = g_strdup ("");
}
return ret;
}
static gboolean
is_trusted_desktop_file (GFile *file,
GCancellable *cancellable)
{
char *basename;
gboolean res;
GFileInfo *info;
/* Don't trust non-local files */
if (!g_file_is_native (file))
{
return FALSE;
}
basename = g_file_get_basename (file);
if (!g_str_has_suffix (basename, ".desktop"))
{
g_free (basename);
return FALSE;
}
g_free (basename);
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
cancellable,
NULL);
if (info == NULL)
{
return FALSE;
}
res = FALSE;
/* Weird file => not trusted,
* Already executable => no need to mark trusted */
if (g_file_info_get_file_type (info) == G_FILE_TYPE_REGULAR &&
!g_file_info_get_attribute_boolean (info,
G_FILE_ATTRIBUTE_ACCESS_CAN_EXECUTE) &&
nautilus_is_in_system_dir (file))
{
res = TRUE;
}
g_object_unref (info);
return res;
}
static FileConflictResponse *
handle_copy_move_conflict (CommonJob *job,
GFile *src,
GFile *dest,
GFile *dest_dir)
{
FileConflictResponse *response;
g_timer_stop (job->time);
nautilus_progress_info_pause (job->progress);
response = copy_move_conflict_ask_user_action (job->parent_window,
src,
dest,
dest_dir);
nautilus_progress_info_resume (job->progress);
g_timer_continue (job->time);
return response;
}
static GFile *
get_target_file_for_display_name (GFile *dir,
const gchar *name)
{
GFile *dest;
dest = NULL;
dest = g_file_get_child_for_display_name (dir, name, NULL);
if (dest == NULL)
{
dest = g_file_get_child (dir, name);
}
return dest;
}
/* Debuting files is non-NULL only for toplevel items */
static void
copy_move_file (CopyMoveJob *copy_job,
GFile *src,
GFile *dest_dir,
gboolean same_fs,
gboolean unique_names,
char **dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info,
GHashTable *debuting_files,
GdkPoint *position,
gboolean overwrite,
gboolean *skipped_file,
gboolean readonly_source_fs)
{
GFile *dest, *new_dest;
g_autofree gchar *dest_uri = NULL;
GError *error;
GFileCopyFlags flags;
char *primary, *secondary, *details;
int response;
ProgressData pdata;
gboolean would_recurse, is_merge;
CommonJob *job;
gboolean res;
int unique_name_nr;
gboolean handled_invalid_filename;
job = (CommonJob *) copy_job;
if (should_skip_file (job, src))
{
*skipped_file = TRUE;
return;
}
unique_name_nr = 1;
/* another file in the same directory might have handled the invalid
* filename condition for us
*/
handled_invalid_filename = *dest_fs_type != NULL;
if (unique_names)
{
dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr++);
}
else if (copy_job->target_name != NULL)
{
dest = get_target_file_with_custom_name (src, dest_dir, *dest_fs_type, same_fs,
copy_job->target_name);
}
else
{
dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
}
/* Don't allow recursive move/copy into itself.
* (We would get a file system error if we proceeded but it is nicer to
* detect and report it at this level) */
if (test_dir_is_parent (dest_dir, src))
{
if (job->skip_all_error)
{
goto out;
}
/* the run_warning() frees all strings passed in automatically */
primary = copy_job->is_move ? g_strdup (_("You cannot move a folder into itself."))
: g_strdup (_("You cannot copy a folder into itself."));
secondary = g_strdup (_("The destination folder is inside the source folder."));
response = run_cancel_or_skip_warning (job,
primary,
secondary,
NULL,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
/* Don't allow copying over the source or one of the parents of the source.
*/
if (test_dir_is_parent (src, dest))
{
if (job->skip_all_error)
{
goto out;
}
/* the run_warning() frees all strings passed in automatically */
primary = copy_job->is_move ? g_strdup (_("You cannot move a file over itself."))
: g_strdup (_("You cannot copy a file over itself."));
secondary = g_strdup (_("The source file would be overwritten by the destination."));
response = run_cancel_or_skip_warning (job,
primary,
secondary,
NULL,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
retry:
error = NULL;
flags = G_FILE_COPY_NOFOLLOW_SYMLINKS;
if (overwrite)
{
flags |= G_FILE_COPY_OVERWRITE;
}
if (readonly_source_fs)
{
flags |= G_FILE_COPY_TARGET_DEFAULT_PERMS;
}
pdata.job = copy_job;
pdata.last_size = 0;
pdata.source_info = source_info;
pdata.transfer_info = transfer_info;
if (copy_job->is_move)
{
res = g_file_move (src, dest,
flags,
job->cancellable,
copy_file_progress_callback,
&pdata,
&error);
}
else
{
res = g_file_copy (src, dest,
flags,
job->cancellable,
copy_file_progress_callback,
&pdata,
&error);
}
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (dest, job->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (dest);
dest = real;
}
}
if (res)
{
transfer_info->num_files++;
report_copy_progress (copy_job, source_info, transfer_info);
if (debuting_files)
{
dest_uri = g_file_get_uri (dest);
if (position)
{
nautilus_file_changes_queue_schedule_position_set (dest, *position, job->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
g_hash_table_replace (debuting_files, g_object_ref (dest), GINT_TO_POINTER (TRUE));
}
if (copy_job->is_move)
{
nautilus_file_changes_queue_file_moved (src, dest);
}
else
{
nautilus_file_changes_queue_file_added (dest);
}
/* If copying a trusted desktop file to the desktop,
* mark it as trusted. */
if (copy_job->desktop_location != NULL &&
g_file_equal (copy_job->desktop_location, dest_dir) &&
is_trusted_desktop_file (src, job->cancellable))
{
mark_desktop_file_executable (job,
job->cancellable,
dest,
FALSE);
}
if (job->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (job->undo_info),
src, dest);
}
g_object_unref (dest);
return;
}
if (!handled_invalid_filename &&
IS_IO_ERROR (error, INVALID_FILENAME))
{
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
*dest_fs_type = query_fs_type (dest_dir, job->cancellable);
if (unique_names)
{
new_dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr);
}
else
{
new_dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
}
if (!g_file_equal (dest, new_dest))
{
g_object_unref (dest);
dest = new_dest;
g_error_free (error);
goto retry;
}
else
{
g_object_unref (new_dest);
}
}
/* Conflict */
if (!overwrite &&
IS_IO_ERROR (error, EXISTS))
{
gboolean is_merge;
FileConflictResponse *response;
g_error_free (error);
if (unique_names)
{
g_object_unref (dest);
dest = get_unique_target_file (src, dest_dir, same_fs, *dest_fs_type, unique_name_nr++);
goto retry;
}
is_merge = FALSE;
if (is_dir (dest) && is_dir (src))
{
is_merge = TRUE;
}
if ((is_merge && job->merge_all) ||
(!is_merge && job->replace_all))
{
overwrite = TRUE;
goto retry;
}
if (job->skip_all_conflict)
{
goto out;
}
response = handle_copy_move_conflict (job, src, dest, dest_dir);
if (response->id == GTK_RESPONSE_CANCEL ||
response->id == GTK_RESPONSE_DELETE_EVENT)
{
file_conflict_response_free (response);
abort_job (job);
}
else if (response->id == CONFLICT_RESPONSE_SKIP)
{
if (response->apply_to_all)
{
job->skip_all_conflict = TRUE;
}
file_conflict_response_free (response);
}
else if (response->id == CONFLICT_RESPONSE_REPLACE) /* merge/replace */
{
if (response->apply_to_all)
{
if (is_merge)
{
job->merge_all = TRUE;
}
else
{
job->replace_all = TRUE;
}
}
overwrite = TRUE;
file_conflict_response_free (response);
goto retry;
}
else if (response->id == CONFLICT_RESPONSE_RENAME)
{
g_object_unref (dest);
dest = get_target_file_for_display_name (dest_dir,
response->new_name);
file_conflict_response_free (response);
goto retry;
}
else
{
g_assert_not_reached ();
}
}
else if (overwrite &&
IS_IO_ERROR (error, IS_DIRECTORY))
{
gboolean existing_file_deleted;
DeleteExistingFileData data;
g_error_free (error);
data.job = job;
data.source = src;
existing_file_deleted =
delete_file_recursively (dest,
job->cancellable,
existing_file_removed_callback,
&data);
if (existing_file_deleted)
{
goto retry;
}
}
/* Needs to recurse */
else if (IS_IO_ERROR (error, WOULD_RECURSE) ||
IS_IO_ERROR (error, WOULD_MERGE))
{
is_merge = error->code == G_IO_ERROR_WOULD_MERGE;
would_recurse = error->code == G_IO_ERROR_WOULD_RECURSE;
g_error_free (error);
if (overwrite && would_recurse)
{
error = NULL;
/* Copying a dir onto file, first remove the file */
if (!g_file_delete (dest, job->cancellable, &error) &&
!IS_IO_ERROR (error, NOT_FOUND))
{
if (job->skip_all_error)
{
g_error_free (error);
goto out;
}
if (copy_job->is_move)
{
primary = f (_("Error while moving “%B”."), src);
}
else
{
primary = f (_("Error while copying “%B”."), src);
}
secondary = f (_("Could not remove the already existing file with the same name in %F."), dest_dir);
details = error->message;
/* setting TRUE on show_all here, as we could have
* another error on the same file later.
*/
response = run_warning (job,
primary,
secondary,
details,
TRUE,
CANCEL, SKIP_ALL, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
if (error)
{
g_error_free (error);
error = NULL;
}
nautilus_file_changes_queue_file_removed (dest);
}
if (is_merge)
{
/* On merge we now write in the target directory, which may not
* be in the same directory as the source, even if the parent is
* (if the merged directory is a mountpoint). This could cause
* problems as we then don't transcode filenames.
* We just set same_fs to FALSE which is safe but a bit slower. */
same_fs = FALSE;
}
if (!copy_move_directory (copy_job, src, &dest, same_fs,
would_recurse, dest_fs_type,
source_info, transfer_info,
debuting_files, skipped_file,
readonly_source_fs))
{
/* destination changed, since it was an invalid file name */
g_assert (*dest_fs_type != NULL);
handled_invalid_filename = TRUE;
goto retry;
}
g_object_unref (dest);
return;
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else
{
if (job->skip_all_error)
{
g_error_free (error);
goto out;
}
primary = f (_("Error while copying “%B”."), src);
secondary = f (_("There was an error copying the file into %F."), dest_dir);
details = error->message;
response = run_cancel_or_skip_warning (job,
primary,
secondary,
details,
source_info->num_files,
source_info->num_files - transfer_info->num_files);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
out:
*skipped_file = TRUE; /* Or aborted, but same-same */
g_object_unref (dest);
}
static void
copy_files (CopyMoveJob *job,
const char *dest_fs_id,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
CommonJob *common;
GList *l;
GFile *src;
gboolean same_fs;
int i;
GdkPoint *point;
gboolean skipped_file;
gboolean unique_names;
GFile *dest;
GFile *source_dir;
char *dest_fs_type;
GFileInfo *inf;
gboolean readonly_source_fs;
dest_fs_type = NULL;
readonly_source_fs = FALSE;
common = &job->common;
report_copy_progress (job, source_info, transfer_info);
/* Query the source dir, not the file because if it's a symlink we'll follow it */
source_dir = g_file_get_parent ((GFile *) job->files->data);
if (source_dir)
{
inf = g_file_query_filesystem_info (source_dir, "filesystem::readonly", NULL, NULL);
if (inf != NULL)
{
readonly_source_fs = g_file_info_get_attribute_boolean (inf, "filesystem::readonly");
g_object_unref (inf);
}
g_object_unref (source_dir);
}
unique_names = (job->destination == NULL);
i = 0;
for (l = job->files;
l != NULL && !job_aborted (common);
l = l->next)
{
src = l->data;
if (i < job->n_icon_positions)
{
point = &job->icon_positions[i];
}
else
{
point = NULL;
}
same_fs = FALSE;
if (dest_fs_id)
{
same_fs = has_fs_id (src, dest_fs_id);
}
if (job->destination)
{
dest = g_object_ref (job->destination);
}
else
{
dest = g_file_get_parent (src);
}
if (dest)
{
skipped_file = FALSE;
copy_move_file (job, src, dest,
same_fs, unique_names,
&dest_fs_type,
source_info, transfer_info,
job->debuting_files,
point, FALSE, &skipped_file,
readonly_source_fs);
g_object_unref (dest);
if (skipped_file)
{
transfer_add_file_to_count (src, common, transfer_info);
report_copy_progress (job, source_info, transfer_info);
}
}
i++;
}
g_free (dest_fs_type);
}
static void
copy_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CopyMoveJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->debuting_files,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_list_free_full (job->files, g_object_unref);
if (job->destination)
{
g_object_unref (job->destination);
}
if (job->desktop_location)
{
g_object_unref (job->desktop_location);
}
g_hash_table_unref (job->debuting_files);
g_free (job->icon_positions);
g_free (job->target_name);
g_clear_object (&job->fake_display_source);
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
copy_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CopyMoveJob *job;
CommonJob *common;
SourceInfo source_info;
TransferInfo transfer_info;
char *dest_fs_id;
GFile *dest;
job = task_data;
common = &job->common;
dest_fs_id = NULL;
nautilus_progress_info_start (job->common.progress);
scan_sources (job->files,
&source_info,
common,
OP_KIND_COPY);
if (job_aborted (common))
{
goto aborted;
}
if (job->destination)
{
dest = g_object_ref (job->destination);
}
else
{
/* Duplication, no dest,
* use source for free size, etc
*/
dest = g_file_get_parent (job->files->data);
}
verify_destination (&job->common,
dest,
&dest_fs_id,
source_info.num_bytes);
g_object_unref (dest);
if (job_aborted (common))
{
goto aborted;
}
g_timer_start (job->common.time);
memset (&transfer_info, 0, sizeof (transfer_info));
copy_files (job,
dest_fs_id,
&source_info, &transfer_info);
aborted:
g_free (dest_fs_id);
}
void
nautilus_file_operations_copy_file (GFile *source_file,
GFile *target_dir,
const gchar *source_display_name,
const gchar *new_name,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_append (NULL, g_object_ref (source_file));
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
job->target_name = g_strdup (new_name);
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
if (source_display_name != NULL)
{
gchar *path;
path = g_build_filename ("/", source_display_name, NULL);
job->fake_display_source = g_file_new_for_path (path);
g_free (path);
}
inhibit_power_manager ((CommonJob *) job, _("Copying Files"));
task = g_task_new (NULL, job->common.cancellable, copy_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, copy_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_copy (GList *files,
GArray *relative_item_points,
GFile *target_dir,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->desktop_location = nautilus_get_desktop_location ();
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
inhibit_power_manager ((CommonJob *) job, _("Copying Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_COPY,
g_list_length (files),
src_dir, target_dir);
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, copy_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, copy_task_thread_func);
g_object_unref (task);
}
static void
report_preparing_move_progress (CopyMoveJob *move_job,
int total,
int left)
{
CommonJob *job;
job = (CommonJob *) move_job;
nautilus_progress_info_take_status (job->progress,
f (_("Preparing to move to “%B”"),
move_job->destination));
nautilus_progress_info_take_details (job->progress,
f (ngettext ("Preparing to move %'d file",
"Preparing to move %'d files",
left), left));
nautilus_progress_info_pulse_progress (job->progress);
}
typedef struct
{
GFile *file;
gboolean overwrite;
gboolean has_position;
GdkPoint position;
} MoveFileCopyFallback;
static MoveFileCopyFallback *
move_copy_file_callback_new (GFile *file,
gboolean overwrite,
GdkPoint *position)
{
MoveFileCopyFallback *fallback;
fallback = g_new (MoveFileCopyFallback, 1);
fallback->file = file;
fallback->overwrite = overwrite;
if (position)
{
fallback->has_position = TRUE;
fallback->position = *position;
}
else
{
fallback->has_position = FALSE;
}
return fallback;
}
static GList *
get_files_from_fallbacks (GList *fallbacks)
{
MoveFileCopyFallback *fallback;
GList *res, *l;
res = NULL;
for (l = fallbacks; l != NULL; l = l->next)
{
fallback = l->data;
res = g_list_prepend (res, fallback->file);
}
return g_list_reverse (res);
}
static void
move_file_prepare (CopyMoveJob *move_job,
GFile *src,
GFile *dest_dir,
gboolean same_fs,
char **dest_fs_type,
GHashTable *debuting_files,
GdkPoint *position,
GList **fallback_files,
int files_left)
{
GFile *dest, *new_dest;
g_autofree gchar *dest_uri = NULL;
GError *error;
CommonJob *job;
gboolean overwrite;
char *primary, *secondary, *details;
int response;
GFileCopyFlags flags;
MoveFileCopyFallback *fallback;
gboolean handled_invalid_filename;
overwrite = FALSE;
handled_invalid_filename = *dest_fs_type != NULL;
job = (CommonJob *) move_job;
dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
/* Don't allow recursive move/copy into itself.
* (We would get a file system error if we proceeded but it is nicer to
* detect and report it at this level) */
if (test_dir_is_parent (dest_dir, src))
{
if (job->skip_all_error)
{
goto out;
}
/* the run_warning() frees all strings passed in automatically */
primary = move_job->is_move ? g_strdup (_("You cannot move a folder into itself."))
: g_strdup (_("You cannot copy a folder into itself."));
secondary = g_strdup (_("The destination folder is inside the source folder."));
response = run_warning (job,
primary,
secondary,
NULL,
files_left > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
goto out;
}
retry:
flags = G_FILE_COPY_NOFOLLOW_SYMLINKS | G_FILE_COPY_NO_FALLBACK_FOR_MOVE;
if (overwrite)
{
flags |= G_FILE_COPY_OVERWRITE;
}
error = NULL;
if (g_file_move (src, dest,
flags,
job->cancellable,
NULL,
NULL,
&error))
{
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (dest), GINT_TO_POINTER (TRUE));
}
nautilus_file_changes_queue_file_moved (src, dest);
dest_uri = g_file_get_uri (dest);
if (position)
{
nautilus_file_changes_queue_schedule_position_set (dest, *position, job->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
if (job->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (job->undo_info),
src, dest);
}
return;
}
if (IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
g_error_free (error);
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
*dest_fs_type = query_fs_type (dest_dir, job->cancellable);
new_dest = get_target_file (src, dest_dir, *dest_fs_type, same_fs);
if (!g_file_equal (dest, new_dest))
{
g_object_unref (dest);
dest = new_dest;
goto retry;
}
else
{
g_object_unref (new_dest);
}
}
/* Conflict */
else if (!overwrite &&
IS_IO_ERROR (error, EXISTS))
{
gboolean is_merge;
FileConflictResponse *response;
g_error_free (error);
is_merge = FALSE;
if (is_dir (dest) && is_dir (src))
{
is_merge = TRUE;
}
if ((is_merge && job->merge_all) ||
(!is_merge && job->replace_all))
{
overwrite = TRUE;
goto retry;
}
if (job->skip_all_conflict)
{
goto out;
}
response = handle_copy_move_conflict (job, src, dest, dest_dir);
if (response->id == GTK_RESPONSE_CANCEL ||
response->id == GTK_RESPONSE_DELETE_EVENT)
{
file_conflict_response_free (response);
abort_job (job);
}
else if (response->id == CONFLICT_RESPONSE_SKIP)
{
if (response->apply_to_all)
{
job->skip_all_conflict = TRUE;
}
file_conflict_response_free (response);
}
else if (response->id == CONFLICT_RESPONSE_REPLACE) /* merge/replace */
{
if (response->apply_to_all)
{
if (is_merge)
{
job->merge_all = TRUE;
}
else
{
job->replace_all = TRUE;
}
}
overwrite = TRUE;
file_conflict_response_free (response);
goto retry;
}
else if (response->id == CONFLICT_RESPONSE_RENAME)
{
g_object_unref (dest);
dest = get_target_file_for_display_name (dest_dir,
response->new_name);
file_conflict_response_free (response);
goto retry;
}
else
{
g_assert_not_reached ();
}
}
else if (IS_IO_ERROR (error, WOULD_RECURSE) ||
IS_IO_ERROR (error, WOULD_MERGE) ||
IS_IO_ERROR (error, NOT_SUPPORTED) ||
(overwrite && IS_IO_ERROR (error, IS_DIRECTORY)))
{
g_error_free (error);
fallback = move_copy_file_callback_new (src,
overwrite,
position);
*fallback_files = g_list_prepend (*fallback_files, fallback);
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else
{
if (job->skip_all_error)
{
g_error_free (error);
goto out;
}
primary = f (_("Error while moving “%B”."), src);
secondary = f (_("There was an error moving the file into %F."), dest_dir);
details = error->message;
response = run_warning (job,
primary,
secondary,
details,
files_left > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (job);
}
else if (response == 1) /* skip all */
{
job->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
out:
g_object_unref (dest);
}
static void
move_files_prepare (CopyMoveJob *job,
const char *dest_fs_id,
char **dest_fs_type,
GList **fallbacks)
{
CommonJob *common;
GList *l;
GFile *src;
gboolean same_fs;
int i;
GdkPoint *point;
int total, left;
common = &job->common;
total = left = g_list_length (job->files);
report_preparing_move_progress (job, total, left);
i = 0;
for (l = job->files;
l != NULL && !job_aborted (common);
l = l->next)
{
src = l->data;
if (i < job->n_icon_positions)
{
point = &job->icon_positions[i];
}
else
{
point = NULL;
}
same_fs = FALSE;
if (dest_fs_id)
{
same_fs = has_fs_id (src, dest_fs_id);
}
move_file_prepare (job, src, job->destination,
same_fs, dest_fs_type,
job->debuting_files,
point,
fallbacks,
left);
report_preparing_move_progress (job, total, --left);
i++;
}
*fallbacks = g_list_reverse (*fallbacks);
}
static void
move_files (CopyMoveJob *job,
GList *fallbacks,
const char *dest_fs_id,
char **dest_fs_type,
SourceInfo *source_info,
TransferInfo *transfer_info)
{
CommonJob *common;
GList *l;
GFile *src;
gboolean same_fs;
int i;
GdkPoint *point;
gboolean skipped_file;
MoveFileCopyFallback *fallback;
common = &job->common;
report_copy_progress (job, source_info, transfer_info);
i = 0;
for (l = fallbacks;
l != NULL && !job_aborted (common);
l = l->next)
{
fallback = l->data;
src = fallback->file;
if (fallback->has_position)
{
point = &fallback->position;
}
else
{
point = NULL;
}
same_fs = FALSE;
if (dest_fs_id)
{
same_fs = has_fs_id (src, dest_fs_id);
}
/* Set overwrite to true, as the user has
* selected overwrite on all toplevel items */
skipped_file = FALSE;
copy_move_file (job, src, job->destination,
same_fs, FALSE, dest_fs_type,
source_info, transfer_info,
job->debuting_files,
point, fallback->overwrite, &skipped_file, FALSE);
i++;
if (skipped_file)
{
transfer_add_file_to_count (src, common, transfer_info);
report_copy_progress (job, source_info, transfer_info);
}
}
}
static void
move_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CopyMoveJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->debuting_files,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_list_free_full (job->files, g_object_unref);
g_object_unref (job->destination);
g_hash_table_unref (job->debuting_files);
g_free (job->icon_positions);
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
move_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CopyMoveJob *job;
CommonJob *common;
GList *fallbacks;
SourceInfo source_info;
TransferInfo transfer_info;
char *dest_fs_id;
char *dest_fs_type;
GList *fallback_files;
job = task_data;
common = &job->common;
dest_fs_id = NULL;
dest_fs_type = NULL;
fallbacks = NULL;
nautilus_progress_info_start (job->common.progress);
verify_destination (&job->common,
job->destination,
&dest_fs_id,
-1);
if (job_aborted (common))
{
goto aborted;
}
/* This moves all files that we can do without copy + delete */
move_files_prepare (job, dest_fs_id, &dest_fs_type, &fallbacks);
if (job_aborted (common))
{
goto aborted;
}
/* The rest we need to do deep copy + delete behind on,
* so scan for size */
fallback_files = get_files_from_fallbacks (fallbacks);
scan_sources (fallback_files,
&source_info,
common,
OP_KIND_MOVE);
g_list_free (fallback_files);
if (job_aborted (common))
{
goto aborted;
}
verify_destination (&job->common,
job->destination,
NULL,
source_info.num_bytes);
if (job_aborted (common))
{
goto aborted;
}
memset (&transfer_info, 0, sizeof (transfer_info));
move_files (job,
fallbacks,
dest_fs_id, &dest_fs_type,
&source_info, &transfer_info);
aborted:
g_list_free_full (fallbacks, g_free);
g_free (dest_fs_id);
g_free (dest_fs_type);
}
void
nautilus_file_operations_move (GList *files,
GArray *relative_item_points,
GFile *target_dir,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->is_move = TRUE;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
inhibit_power_manager ((CommonJob *) job, _("Moving Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
if (g_file_has_uri_scheme (g_list_first (files)->data, "trash"))
{
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_RESTORE_FROM_TRASH,
g_list_length (files),
src_dir, target_dir);
}
else
{
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_MOVE,
g_list_length (files),
src_dir, target_dir);
}
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, move_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, move_task_thread_func);
g_object_unref (task);
}
static void
report_preparing_link_progress (CopyMoveJob *link_job,
int total,
int left)
{
CommonJob *job;
job = (CommonJob *) link_job;
nautilus_progress_info_take_status (job->progress,
f (_("Creating links in “%B”"),
link_job->destination));
nautilus_progress_info_take_details (job->progress,
f (ngettext ("Making link to %'d file",
"Making links to %'d files",
left), left));
nautilus_progress_info_set_progress (job->progress, left, total);
}
static char *
get_abs_path_for_symlink (GFile *file,
GFile *destination)
{
GFile *root, *parent;
char *relative, *abs;
if (g_file_is_native (file) || g_file_is_native (destination))
{
return g_file_get_path (file);
}
root = g_object_ref (file);
while ((parent = g_file_get_parent (root)) != NULL)
{
g_object_unref (root);
root = parent;
}
relative = g_file_get_relative_path (root, file);
g_object_unref (root);
abs = g_strconcat ("/", relative, NULL);
g_free (relative);
return abs;
}
static void
link_file (CopyMoveJob *job,
GFile *src,
GFile *dest_dir,
char **dest_fs_type,
GHashTable *debuting_files,
GdkPoint *position,
int files_left)
{
GFile *src_dir, *dest, *new_dest;
g_autofree gchar *dest_uri = NULL;
int count;
char *path;
gboolean not_local;
GError *error;
CommonJob *common;
char *primary, *secondary, *details;
int response;
gboolean handled_invalid_filename;
common = (CommonJob *) job;
count = 0;
src_dir = g_file_get_parent (src);
if (g_file_equal (src_dir, dest_dir))
{
count = 1;
}
g_object_unref (src_dir);
handled_invalid_filename = *dest_fs_type != NULL;
dest = get_target_file_for_link (src, dest_dir, *dest_fs_type, count);
retry:
error = NULL;
not_local = FALSE;
path = get_abs_path_for_symlink (src, dest);
if (path == NULL)
{
not_local = TRUE;
}
else if (g_file_make_symbolic_link (dest,
path,
common->cancellable,
&error))
{
if (common->undo_info != NULL)
{
nautilus_file_undo_info_ext_add_origin_target_pair (NAUTILUS_FILE_UNDO_INFO_EXT (common->undo_info),
src, dest);
}
g_free (path);
if (debuting_files)
{
g_hash_table_replace (debuting_files, g_object_ref (dest), GINT_TO_POINTER (TRUE));
}
nautilus_file_changes_queue_file_added (dest);
dest_uri = g_file_get_uri (dest);
if (position)
{
nautilus_file_changes_queue_schedule_position_set (dest, *position, common->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
g_object_unref (dest);
return;
}
g_free (path);
if (error != NULL &&
IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
handled_invalid_filename = TRUE;
g_assert (*dest_fs_type == NULL);
*dest_fs_type = query_fs_type (dest_dir, common->cancellable);
new_dest = get_target_file_for_link (src, dest_dir, *dest_fs_type, count);
if (!g_file_equal (dest, new_dest))
{
g_object_unref (dest);
dest = new_dest;
g_error_free (error);
goto retry;
}
else
{
g_object_unref (new_dest);
}
}
/* Conflict */
if (error != NULL && IS_IO_ERROR (error, EXISTS))
{
g_object_unref (dest);
dest = get_target_file_for_link (src, dest_dir, *dest_fs_type, count++);
g_error_free (error);
goto retry;
}
else if (error != NULL && IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else if (error != NULL)
{
if (common->skip_all_error)
{
goto out;
}
primary = f (_("Error while creating link to %B."), src);
if (not_local)
{
secondary = f (_("Symbolic links only supported for local files"));
details = NULL;
}
else if (IS_IO_ERROR (error, NOT_SUPPORTED))
{
secondary = f (_("The target doesn’t support symbolic links."));
details = NULL;
}
else
{
secondary = f (_("There was an error creating the symlink in %F."), dest_dir);
details = error->message;
}
response = run_warning (common,
primary,
secondary,
details,
files_left > 1,
CANCEL, SKIP_ALL, SKIP,
NULL);
if (error)
{
g_error_free (error);
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1) /* skip all */
{
common->skip_all_error = TRUE;
}
else if (response == 2) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
out:
g_object_unref (dest);
}
static void
link_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CopyMoveJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->debuting_files,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_list_free_full (job->files, g_object_unref);
g_object_unref (job->destination);
g_hash_table_unref (job->debuting_files);
g_free (job->icon_positions);
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
link_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CopyMoveJob *job;
CommonJob *common;
GFile *src;
GdkPoint *point;
char *dest_fs_type;
int total, left;
int i;
GList *l;
job = task_data;
common = &job->common;
dest_fs_type = NULL;
nautilus_progress_info_start (job->common.progress);
verify_destination (&job->common,
job->destination,
NULL,
-1);
if (job_aborted (common))
{
goto aborted;
}
total = left = g_list_length (job->files);
report_preparing_link_progress (job, total, left);
i = 0;
for (l = job->files;
l != NULL && !job_aborted (common);
l = l->next)
{
src = l->data;
if (i < job->n_icon_positions)
{
point = &job->icon_positions[i];
}
else
{
point = NULL;
}
link_file (job, src, job->destination,
&dest_fs_type, job->debuting_files,
point, left);
report_preparing_link_progress (job, total, --left);
i++;
}
aborted:
g_free (dest_fs_type);
}
void
nautilus_file_operations_link (GList *files,
GArray *relative_item_points,
GFile *target_dir,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
job = op_job_new (CopyMoveJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = g_object_ref (target_dir);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, target_dir);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
job->common.undo_info = nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_CREATE_LINK,
g_list_length (files),
src_dir, target_dir);
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, link_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, link_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_duplicate (GList *files,
GArray *relative_item_points,
GtkWindow *parent_window,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CopyMoveJob *job;
GFile *parent;
job = op_job_new (CopyMoveJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->files = g_list_copy_deep (files, (GCopyFunc) g_object_ref, NULL);
job->destination = NULL;
/* Duplicate files doesn't have a destination, since is the same as source.
* For that set as destination the source parent folder */
parent = g_file_get_parent (files->data);
/* Need to indicate the destination for the operation notification open
* button. */
nautilus_progress_info_set_destination (((CommonJob *) job)->progress, parent);
if (relative_item_points != NULL &&
relative_item_points->len > 0)
{
job->icon_positions =
g_memdup (relative_item_points->data,
sizeof (GdkPoint) * relative_item_points->len);
job->n_icon_positions = relative_item_points->len;
}
job->debuting_files = g_hash_table_new_full (g_file_hash, (GEqualFunc) g_file_equal, g_object_unref, NULL);
if (!nautilus_file_undo_manager_is_operating ())
{
GFile *src_dir;
src_dir = g_file_get_parent (files->data);
job->common.undo_info =
nautilus_file_undo_info_ext_new (NAUTILUS_FILE_UNDO_OP_DUPLICATE,
g_list_length (files),
src_dir, src_dir);
g_object_unref (src_dir);
}
task = g_task_new (NULL, job->common.cancellable, copy_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, copy_task_thread_func);
g_object_unref (task);
g_object_unref (parent);
}
static void
set_permissions_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
SetPermissionsJob *job;
job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
static void
set_permissions_file (SetPermissionsJob *job,
GFile *file,
GFileInfo *info)
{
CommonJob *common;
GFileInfo *child_info;
gboolean free_info;
guint32 current;
guint32 value;
guint32 mask;
GFileEnumerator *enumerator;
GFile *child;
common = (CommonJob *) job;
nautilus_progress_info_pulse_progress (common->progress);
free_info = FALSE;
if (info == NULL)
{
free_info = TRUE;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_UNIX_MODE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable,
NULL);
/* Ignore errors */
if (info == NULL)
{
return;
}
}
if (g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
value = job->dir_permissions;
mask = job->dir_mask;
}
else
{
value = job->file_permissions;
mask = job->file_mask;
}
if (!job_aborted (common) &&
g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_UNIX_MODE))
{
current = g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_MODE);
if (common->undo_info != NULL)
{
nautilus_file_undo_info_rec_permissions_add_file (NAUTILUS_FILE_UNDO_INFO_REC_PERMISSIONS (common->undo_info),
file, current);
}
current = (current & ~mask) | value;
g_file_set_attribute_uint32 (file, G_FILE_ATTRIBUTE_UNIX_MODE,
current, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable, NULL);
}
if (!job_aborted (common) &&
g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY)
{
enumerator = g_file_enumerate_children (file,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_UNIX_MODE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable,
NULL);
if (enumerator)
{
while (!job_aborted (common) &&
(child_info = g_file_enumerator_next_file (enumerator, common->cancellable, NULL)) != NULL)
{
child = g_file_get_child (file,
g_file_info_get_name (child_info));
set_permissions_file (job, child, child_info);
g_object_unref (child);
g_object_unref (child_info);
}
g_file_enumerator_close (enumerator, common->cancellable, NULL);
g_object_unref (enumerator);
}
}
if (free_info)
{
g_object_unref (info);
}
}
static void
set_permissions_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
SetPermissionsJob *job = task_data;
CommonJob *common;
common = (CommonJob *) job;
nautilus_progress_info_set_status (common->progress,
_("Setting permissions"));
nautilus_progress_info_start (job->common.progress);
set_permissions_file (job, job->file, NULL);
}
void
nautilus_file_set_permissions_recursive (const char *directory,
guint32 file_permissions,
guint32 file_mask,
guint32 dir_permissions,
guint32 dir_mask,
NautilusOpCallback callback,
gpointer callback_data)
{
GTask *task;
SetPermissionsJob *job;
job = op_job_new (SetPermissionsJob, NULL);
job->file = g_file_new_for_uri (directory);
job->file_permissions = file_permissions;
job->file_mask = file_mask;
job->dir_permissions = dir_permissions;
job->dir_mask = dir_mask;
job->done_callback = callback;
job->done_callback_data = callback_data;
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info =
nautilus_file_undo_info_rec_permissions_new (job->file,
file_permissions, file_mask,
dir_permissions, dir_mask);
}
task = g_task_new (NULL, NULL, set_permissions_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, set_permissions_thread_func);
g_object_unref (task);
}
static GList *
location_list_from_uri_list (const GList *uris)
{
const GList *l;
GList *files;
GFile *f;
files = NULL;
for (l = uris; l != NULL; l = l->next)
{
f = g_file_new_for_uri (l->data);
files = g_list_prepend (files, f);
}
return g_list_reverse (files);
}
typedef struct
{
NautilusCopyCallback real_callback;
gpointer real_data;
} MoveTrashCBData;
static void
callback_for_move_to_trash (GHashTable *debuting_uris,
gboolean user_cancelled,
MoveTrashCBData *data)
{
if (data->real_callback)
{
data->real_callback (debuting_uris, !user_cancelled, data->real_data);
}
g_slice_free (MoveTrashCBData, data);
}
void
nautilus_file_operations_copy_move (const GList *item_uris,
GArray *relative_item_points,
const char *target_dir,
GdkDragAction copy_action,
GtkWidget *parent_view,
NautilusCopyCallback done_callback,
gpointer done_callback_data)
{
GList *locations;
GList *p;
GFile *dest, *src_dir;
GtkWindow *parent_window;
gboolean target_is_mapping;
gboolean have_nonmapping_source;
dest = NULL;
target_is_mapping = FALSE;
have_nonmapping_source = FALSE;
if (target_dir)
{
dest = g_file_new_for_uri (target_dir);
if (g_file_has_uri_scheme (dest, "burn"))
{
target_is_mapping = TRUE;
}
}
locations = location_list_from_uri_list (item_uris);
for (p = locations; p != NULL; p = p->next)
{
if (!g_file_has_uri_scheme ((GFile * ) p->data, "burn"))
{
have_nonmapping_source = TRUE;
}
}
if (target_is_mapping && have_nonmapping_source && copy_action == GDK_ACTION_MOVE)
{
/* never move to "burn:///", but fall back to copy.
* This is a workaround, because otherwise the source files would be removed.
*/
copy_action = GDK_ACTION_COPY;
}
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
if (copy_action == GDK_ACTION_COPY)
{
src_dir = g_file_get_parent (locations->data);
if (target_dir == NULL ||
(src_dir != NULL &&
g_file_equal (src_dir, dest)))
{
nautilus_file_operations_duplicate (locations,
relative_item_points,
parent_window,
done_callback, done_callback_data);
}
else
{
nautilus_file_operations_copy (locations,
relative_item_points,
dest,
parent_window,
done_callback, done_callback_data);
}
if (src_dir)
{
g_object_unref (src_dir);
}
}
else if (copy_action == GDK_ACTION_MOVE)
{
if (g_file_has_uri_scheme (dest, "trash"))
{
MoveTrashCBData *cb_data;
cb_data = g_slice_new0 (MoveTrashCBData);
cb_data->real_callback = done_callback;
cb_data->real_data = done_callback_data;
nautilus_file_operations_trash_or_delete (locations,
parent_window,
(NautilusDeleteCallback) callback_for_move_to_trash,
cb_data);
}
else
{
nautilus_file_operations_move (locations,
relative_item_points,
dest,
parent_window,
done_callback, done_callback_data);
}
}
else
{
nautilus_file_operations_link (locations,
relative_item_points,
dest,
parent_window,
done_callback, done_callback_data);
}
g_list_free_full (locations, g_object_unref);
if (dest)
{
g_object_unref (dest);
}
}
static void
create_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CreateJob *job;
job = user_data;
if (job->done_callback)
{
job->done_callback (job->created_file,
!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
g_object_unref (job->dest_dir);
if (job->src)
{
g_object_unref (job->src);
}
g_free (job->src_data);
g_free (job->filename);
if (job->created_file)
{
g_object_unref (job->created_file);
}
finalize_common ((CommonJob *) job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
create_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CreateJob *job;
CommonJob *common;
int count;
GFile *dest;
g_autofree gchar *dest_uri = NULL;
char *basename;
char *filename, *filename2, *new_filename;
char *filename_base, *suffix;
char *dest_fs_type;
GError *error;
gboolean res;
gboolean filename_is_utf8;
char *primary, *secondary, *details;
int response;
char *data;
int length;
GFileOutputStream *out;
gboolean handled_invalid_filename;
int max_length, offset;
job = task_data;
common = &job->common;
nautilus_progress_info_start (job->common.progress);
handled_invalid_filename = FALSE;
dest_fs_type = NULL;
filename = NULL;
dest = NULL;
max_length = get_max_name_length (job->dest_dir);
verify_destination (common,
job->dest_dir,
NULL, -1);
if (job_aborted (common))
{
goto aborted;
}
filename = g_strdup (job->filename);
filename_is_utf8 = FALSE;
if (filename)
{
filename_is_utf8 = g_utf8_validate (filename, -1, NULL);
}
if (filename == NULL)
{
if (job->make_dir)
{
/* localizers: the initial name of a new folder */
filename = g_strdup (_("Untitled Folder"));
filename_is_utf8 = TRUE; /* Pass in utf8 */
}
else
{
if (job->src != NULL)
{
basename = g_file_get_basename (job->src);
/* localizers: the initial name of a new template document */
filename = g_strdup_printf ("%s", basename);
g_free (basename);
}
if (filename == NULL)
{
/* localizers: the initial name of a new empty document */
filename = g_strdup (_("Untitled Document"));
filename_is_utf8 = TRUE; /* Pass in utf8 */
}
}
}
make_file_name_valid_for_dest_fs (filename, dest_fs_type);
if (filename_is_utf8)
{
dest = g_file_get_child_for_display_name (job->dest_dir, filename, NULL);
}
if (dest == NULL)
{
dest = g_file_get_child (job->dest_dir, filename);
}
count = 1;
retry:
error = NULL;
if (job->make_dir)
{
res = g_file_make_directory (dest,
common->cancellable,
&error);
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (dest, common->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (dest);
dest = real;
}
}
if (res && common->undo_info != NULL)
{
nautilus_file_undo_info_create_set_data (NAUTILUS_FILE_UNDO_INFO_CREATE (common->undo_info),
dest, NULL, 0);
}
}
else
{
if (job->src)
{
res = g_file_copy (job->src,
dest,
G_FILE_COPY_NONE,
common->cancellable,
NULL, NULL,
&error);
if (res)
{
GFile *real;
real = map_possibly_volatile_file_to_real (dest, common->cancellable, &error);
if (real == NULL)
{
res = FALSE;
}
else
{
g_object_unref (dest);
dest = real;
}
}
if (res && common->undo_info != NULL)
{
gchar *uri;
uri = g_file_get_uri (job->src);
nautilus_file_undo_info_create_set_data (NAUTILUS_FILE_UNDO_INFO_CREATE (common->undo_info),
dest, uri, 0);
g_free (uri);
}
}
else
{
data = "";
length = 0;
if (job->src_data)
{
data = job->src_data;
length = job->length;
}
out = g_file_create (dest,
G_FILE_CREATE_NONE,
common->cancellable,
&error);
if (out)
{
GFile *real;
real = map_possibly_volatile_file_to_real_on_write (dest,
out,
common->cancellable,
&error);
if (real == NULL)
{
res = FALSE;
g_object_unref (out);
}
else
{
g_object_unref (dest);
dest = real;
res = g_output_stream_write_all (G_OUTPUT_STREAM (out),
data, length,
NULL,
common->cancellable,
&error);
if (res)
{
res = g_output_stream_close (G_OUTPUT_STREAM (out),
common->cancellable,
&error);
if (res && common->undo_info != NULL)
{
nautilus_file_undo_info_create_set_data (NAUTILUS_FILE_UNDO_INFO_CREATE (common->undo_info),
dest, data, length);
}
}
/* This will close if the write failed and we didn't close */
g_object_unref (out);
}
}
else
{
res = FALSE;
}
}
}
if (res)
{
job->created_file = g_object_ref (dest);
nautilus_file_changes_queue_file_added (dest);
dest_uri = g_file_get_uri (dest);
if (job->has_position)
{
nautilus_file_changes_queue_schedule_position_set (dest, job->position, common->screen_num);
}
else if (eel_uri_is_desktop (dest_uri))
{
nautilus_file_changes_queue_schedule_position_remove (dest);
}
}
else
{
g_assert (error != NULL);
if (IS_IO_ERROR (error, INVALID_FILENAME) &&
!handled_invalid_filename)
{
handled_invalid_filename = TRUE;
g_assert (dest_fs_type == NULL);
dest_fs_type = query_fs_type (job->dest_dir, common->cancellable);
if (count == 1)
{
new_filename = g_strdup (filename);
}
else
{
filename_base = eel_filename_strip_extension (filename);
offset = strlen (filename_base);
suffix = g_strdup (filename + offset);
filename2 = g_strdup_printf ("%s %d%s", filename_base, count, suffix);
new_filename = NULL;
if (max_length > 0 && strlen (filename2) > max_length)
{
new_filename = shorten_utf8_string (filename2, strlen (filename2) - max_length);
}
if (new_filename == NULL)
{
new_filename = g_strdup (filename2);
}
g_free (filename2);
g_free (suffix);
}
if (make_file_name_valid_for_dest_fs (new_filename, dest_fs_type))
{
g_object_unref (dest);
if (filename_is_utf8)
{
dest = g_file_get_child_for_display_name (job->dest_dir, new_filename, NULL);
}
if (dest == NULL)
{
dest = g_file_get_child (job->dest_dir, new_filename);
}
g_free (new_filename);
g_error_free (error);
goto retry;
}
g_free (new_filename);
}
if (IS_IO_ERROR (error, EXISTS))
{
g_object_unref (dest);
dest = NULL;
filename_base = eel_filename_strip_extension (filename);
offset = strlen (filename_base);
suffix = g_strdup (filename + offset);
filename2 = g_strdup_printf ("%s %d%s", filename_base, ++count, suffix);
if (max_length > 0 && strlen (filename2) > max_length)
{
new_filename = shorten_utf8_string (filename2, strlen (filename2) - max_length);
if (new_filename != NULL)
{
g_free (filename2);
filename2 = new_filename;
}
}
make_file_name_valid_for_dest_fs (filename2, dest_fs_type);
if (filename_is_utf8)
{
dest = g_file_get_child_for_display_name (job->dest_dir, filename2, NULL);
}
if (dest == NULL)
{
dest = g_file_get_child (job->dest_dir, filename2);
}
g_free (filename2);
g_free (suffix);
g_error_free (error);
goto retry;
}
else if (IS_IO_ERROR (error, CANCELLED))
{
g_error_free (error);
}
/* Other error */
else
{
if (job->make_dir)
{
primary = f (_("Error while creating directory %B."), dest);
}
else
{
primary = f (_("Error while creating file %B."), dest);
}
secondary = f (_("There was an error creating the directory in %F."), job->dest_dir);
details = error->message;
response = run_warning (common,
primary,
secondary,
details,
FALSE,
CANCEL, SKIP,
NULL);
g_error_free (error);
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1) /* skip */
{ /* do nothing */
}
else
{
g_assert_not_reached ();
}
}
}
aborted:
if (dest)
{
g_object_unref (dest);
}
g_free (filename);
g_free (dest_fs_type);
}
void
nautilus_file_operations_new_folder (GtkWidget *parent_view,
GdkPoint *target_point,
const char *parent_dir,
const char *folder_name,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CreateJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (CreateJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->dest_dir = g_file_new_for_uri (parent_dir);
job->filename = g_strdup (folder_name);
job->make_dir = TRUE;
if (target_point != NULL)
{
job->position = *target_point;
job->has_position = TRUE;
}
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info = nautilus_file_undo_info_create_new (NAUTILUS_FILE_UNDO_OP_CREATE_FOLDER);
}
task = g_task_new (NULL, job->common.cancellable, create_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, create_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_new_file_from_template (GtkWidget *parent_view,
GdkPoint *target_point,
const char *parent_dir,
const char *target_filename,
const char *template_uri,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CreateJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (CreateJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->dest_dir = g_file_new_for_uri (parent_dir);
if (target_point != NULL)
{
job->position = *target_point;
job->has_position = TRUE;
}
job->filename = g_strdup (target_filename);
if (template_uri)
{
job->src = g_file_new_for_uri (template_uri);
}
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info = nautilus_file_undo_info_create_new (NAUTILUS_FILE_UNDO_OP_CREATE_FILE_FROM_TEMPLATE);
}
task = g_task_new (NULL, job->common.cancellable, create_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, create_task_thread_func);
g_object_unref (task);
}
void
nautilus_file_operations_new_file (GtkWidget *parent_view,
GdkPoint *target_point,
const char *parent_dir,
const char *target_filename,
const char *initial_contents,
int length,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
CreateJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (CreateJob, parent_window);
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
job->dest_dir = g_file_new_for_uri (parent_dir);
if (target_point != NULL)
{
job->position = *target_point;
job->has_position = TRUE;
}
job->src_data = g_memdup (initial_contents, length);
job->length = length;
job->filename = g_strdup (target_filename);
if (!nautilus_file_undo_manager_is_operating ())
{
job->common.undo_info = nautilus_file_undo_info_create_new (NAUTILUS_FILE_UNDO_OP_CREATE_EMPTY_FILE);
}
task = g_task_new (NULL, job->common.cancellable, create_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, create_task_thread_func);
g_object_unref (task);
}
static void
delete_trash_file (CommonJob *job,
GFile *file,
gboolean del_file,
gboolean del_children)
{
GFileInfo *info;
GFile *child;
GFileEnumerator *enumerator;
if (job_aborted (job))
{
return;
}
if (del_children)
{
enumerator = g_file_enumerate_children (file,
G_FILE_ATTRIBUTE_STANDARD_NAME ","
G_FILE_ATTRIBUTE_STANDARD_TYPE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
job->cancellable,
NULL);
if (enumerator)
{
while (!job_aborted (job) &&
(info = g_file_enumerator_next_file (enumerator, job->cancellable, NULL)) != NULL)
{
child = g_file_get_child (file,
g_file_info_get_name (info));
delete_trash_file (job, child, TRUE,
g_file_info_get_file_type (info) == G_FILE_TYPE_DIRECTORY);
g_object_unref (child);
g_object_unref (info);
}
g_file_enumerator_close (enumerator, job->cancellable, NULL);
g_object_unref (enumerator);
}
}
if (!job_aborted (job) && del_file)
{
g_file_delete (file, job->cancellable, NULL);
}
}
static void
empty_trash_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
EmptyTrashJob *job;
job = user_data;
g_list_free_full (job->trash_dirs, g_object_unref);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
static void
empty_trash_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
EmptyTrashJob *job = task_data;
CommonJob *common;
GList *l;
gboolean confirmed;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
if (job->should_confirm)
{
confirmed = confirm_empty_trash (common);
}
else
{
confirmed = TRUE;
}
if (confirmed)
{
for (l = job->trash_dirs;
l != NULL && !job_aborted (common);
l = l->next)
{
delete_trash_file (common, l->data, FALSE, TRUE);
}
}
}
void
nautilus_file_operations_empty_trash (GtkWidget *parent_view)
{
GTask *task;
EmptyTrashJob *job;
GtkWindow *parent_window;
parent_window = NULL;
if (parent_view)
{
parent_window = (GtkWindow *) gtk_widget_get_ancestor (parent_view, GTK_TYPE_WINDOW);
}
job = op_job_new (EmptyTrashJob, parent_window);
job->trash_dirs = g_list_prepend (job->trash_dirs,
g_file_new_for_uri ("trash:"));
job->should_confirm = TRUE;
inhibit_power_manager ((CommonJob *) job, _("Emptying Trash"));
task = g_task_new (NULL, NULL, empty_trash_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, empty_trash_thread_func);
g_object_unref (task);
}
static void
mark_desktop_file_executable_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
#define TRUSTED_SHEBANG "#!/usr/bin/env xdg-open\n"
static void
mark_desktop_file_executable (CommonJob *common,
GCancellable *cancellable,
GFile *file,
gboolean interactive)
{
GError *error;
guint32 current_perms, new_perms;
int response;
GFileInfo *info;
retry:
error = NULL;
info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_TYPE ","
G_FILE_ATTRIBUTE_UNIX_MODE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable,
&error);
if (info == NULL)
{
if (interactive)
{
response = run_error (common,
g_strdup (_("Unable to mark launcher trusted (executable)")),
error->message,
NULL,
FALSE,
CANCEL, RETRY,
NULL);
}
else
{
response = 0;
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
goto out;
}
if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_UNIX_MODE))
{
current_perms = g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_MODE);
new_perms = current_perms | S_IXGRP | S_IXUSR | S_IXOTH;
if ((current_perms != new_perms) &&
!g_file_set_attribute_uint32 (file, G_FILE_ATTRIBUTE_UNIX_MODE,
new_perms, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
common->cancellable, &error))
{
g_object_unref (info);
if (interactive)
{
response = run_error (common,
g_strdup (_("Unable to mark launcher trusted (executable)")),
error->message,
NULL,
FALSE,
CANCEL, RETRY,
NULL);
}
else
{
response = 0;
}
if (response == 0 || response == GTK_RESPONSE_DELETE_EVENT)
{
abort_job (common);
}
else if (response == 1)
{
goto retry;
}
else
{
g_assert_not_reached ();
}
goto out;
}
}
g_object_unref (info);
out:
;
}
static void
mark_desktop_file_executable_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
MarkTrustedJob *job = task_data;
CommonJob *common;
common = (CommonJob *) job;
nautilus_progress_info_start (job->common.progress);
mark_desktop_file_executable (common,
cancellable,
job->file,
job->interactive);
}
void
nautilus_file_mark_desktop_file_executable (GFile *file,
GtkWindow *parent_window,
gboolean interactive,
NautilusOpCallback done_callback,
gpointer done_callback_data)
{
GTask *task;
MarkTrustedJob *job;
job = op_job_new (MarkTrustedJob, parent_window);
job->file = g_object_ref (file);
job->interactive = interactive;
job->done_callback = done_callback;
job->done_callback_data = done_callback_data;
task = g_task_new (NULL, NULL, mark_desktop_file_executable_task_done, job);
g_task_set_task_data (task, job, NULL);
g_task_run_in_thread (task, mark_desktop_file_executable_task_thread_func);
g_object_unref (task);
}
static void
extract_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
ExtractJob *extract_job;
extract_job = user_data;
if (extract_job->done_callback)
{
extract_job->done_callback (extract_job->output_files,
extract_job->done_callback_data);
}
g_list_free_full (extract_job->source_files, g_object_unref);
g_list_free_full (extract_job->output_files, g_object_unref);
g_object_unref (extract_job->destination_directory);
finalize_common ((CommonJob *) extract_job);
nautilus_file_changes_consume_changes (TRUE);
}
static GFile *
extract_job_on_decide_destination (AutoarExtractor *extractor,
GFile *destination,
GList *files,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
GFile *decided_destination;
g_autofree char *basename = NULL;
nautilus_progress_info_set_details (extract_job->common.progress,
_("Verifying destination"));
basename = g_file_get_basename (destination);
decided_destination = nautilus_generate_unique_file_in_directory (extract_job->destination_directory,
basename);
if (job_aborted ((CommonJob *) extract_job))
{
g_object_unref (decided_destination);
return NULL;
}
extract_job->output_files = g_list_prepend (extract_job->output_files,
decided_destination);
return g_object_ref (decided_destination);
}
static void
extract_job_on_progress (AutoarExtractor *extractor,
guint64 archive_current_decompressed_size,
guint archive_current_decompressed_files,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
CommonJob *common = user_data;
GFile *source_file;
char *details;
double elapsed;
double transfer_rate;
int remaining_time;
guint64 archive_total_decompressed_size;
gdouble archive_weight;
gdouble archive_decompress_progress;
guint64 job_completed_size;
gdouble job_progress;
source_file = autoar_extractor_get_source_file (extractor);
nautilus_progress_info_take_status (common->progress,
f (_("Extracting “%B”"), source_file));
archive_total_decompressed_size = autoar_extractor_get_total_size (extractor);
archive_decompress_progress = (gdouble) archive_current_decompressed_size /
(gdouble) archive_total_decompressed_size;
archive_weight = 0;
if (extract_job->total_compressed_size)
{
archive_weight = (gdouble) extract_job->archive_compressed_size /
(gdouble) extract_job->total_compressed_size;
}
job_progress = archive_decompress_progress * archive_weight + extract_job->base_progress;
elapsed = g_timer_elapsed (common->time, NULL);
transfer_rate = 0;
remaining_time = -1;
job_completed_size = job_progress * extract_job->total_compressed_size;
if (elapsed > 0)
{
transfer_rate = job_completed_size / elapsed;
}
if (transfer_rate > 0)
{
remaining_time = (extract_job->total_compressed_size - job_completed_size) /
transfer_rate;
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE ||
transfer_rate == 0)
{
/* To translators: %S will expand to a size like "2 bytes" or
* "3 MB", so something like "4 kb / 4 MB"
*/
details = f (_("%S / %S"), job_completed_size, extract_job->total_compressed_size);
}
else
{
/* To translators: %S will expand to a size like "2 bytes" or
* "3 MB", %T to a time duration like "2 minutes". So the whole
* thing will be something like
* "2 kb / 4 MB -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the
* remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%S / %S \xE2\x80\x94 %T left (%S/sec)",
"%S / %S \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
job_completed_size, extract_job->total_compressed_size,
remaining_time,
(goffset) transfer_rate);
}
nautilus_progress_info_take_details (common->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (common->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (common->progress,
elapsed);
}
nautilus_progress_info_set_progress (common->progress, job_progress, 1);
}
static void
extract_job_on_error (AutoarExtractor *extractor,
GError *error,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
GFile *source_file;
gint response_id;
source_file = autoar_extractor_get_source_file (extractor);
if (IS_IO_ERROR (error, NOT_SUPPORTED))
{
handle_unsupported_compressed_file (extract_job->common.parent_window,
source_file);
return;
}
nautilus_progress_info_take_status (extract_job->common.progress,
f (_("Error extracting “%B”"),
source_file));
response_id = run_warning ((CommonJob *) extract_job,
f (_("There was an error while extracting “%B”."),
source_file),
g_strdup (error->message),
NULL,
FALSE,
CANCEL,
SKIP,
NULL);
if (response_id == 0 || response_id == GTK_RESPONSE_DELETE_EVENT)
{
abort_job ((CommonJob *) extract_job);
}
}
static void
extract_job_on_completed (AutoarExtractor *extractor,
gpointer user_data)
{
ExtractJob *extract_job = user_data;
GFile *output_file;
output_file = G_FILE (extract_job->output_files->data);
nautilus_file_changes_queue_file_added (output_file);
}
static void
report_extract_final_progress (ExtractJob *extract_job,
gint total_files)
{
char *status;
nautilus_progress_info_set_destination (extract_job->common.progress,
extract_job->destination_directory);
if (total_files == 1)
{
GFile *source_file;
source_file = G_FILE (extract_job->source_files->data);
status = f (_("Extracted “%B” to “%B”"),
source_file,
extract_job->destination_directory);
}
else
{
status = f (ngettext ("Extracted %'d file to “%B”",
"Extracted %'d files to “%B”",
total_files),
total_files,
extract_job->destination_directory);
}
nautilus_progress_info_take_status (extract_job->common.progress,
status);
nautilus_progress_info_take_details (extract_job->common.progress,
f (_("%S / %S"),
extract_job->total_compressed_size,
extract_job->total_compressed_size));
}
static void
extract_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
ExtractJob *extract_job = task_data;
GList *l;
GList *existing_output_files = NULL;
gint total_files;
g_autofree guint64 *archive_compressed_sizes = NULL;
gint i;
g_timer_start (extract_job->common.time);
nautilus_progress_info_start (extract_job->common.progress);
nautilus_progress_info_set_details (extract_job->common.progress,
_("Preparing to extract"));
total_files = g_list_length (extract_job->source_files);
archive_compressed_sizes = g_malloc0_n (total_files, sizeof (guint64));
extract_job->total_compressed_size = 0;
for (l = extract_job->source_files, i = 0;
l != NULL && !job_aborted ((CommonJob *) extract_job);
l = l->next, i++)
{
GFile *source_file;
g_autoptr (GFileInfo) info = NULL;
source_file = G_FILE (l->data);
info = g_file_query_info (source_file,
G_FILE_ATTRIBUTE_STANDARD_SIZE,
G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS,
extract_job->common.cancellable,
NULL);
if (info)
{
archive_compressed_sizes[i] = g_file_info_get_size (info);
extract_job->total_compressed_size += archive_compressed_sizes[i];
}
}
extract_job->base_progress = 0;
for (l = extract_job->source_files, i = 0;
l != NULL && !job_aborted ((CommonJob *) extract_job);
l = l->next, i++)
{
g_autoptr (AutoarExtractor) extractor = NULL;
extractor = autoar_extractor_new (G_FILE (l->data),
extract_job->destination_directory);
autoar_extractor_set_notify_interval (extractor,
PROGRESS_NOTIFY_INTERVAL);
g_signal_connect (extractor, "error",
G_CALLBACK (extract_job_on_error),
extract_job);
g_signal_connect (extractor, "decide-destination",
G_CALLBACK (extract_job_on_decide_destination),
extract_job);
g_signal_connect (extractor, "progress",
G_CALLBACK (extract_job_on_progress),
extract_job);
g_signal_connect (extractor, "completed",
G_CALLBACK (extract_job_on_completed),
extract_job);
extract_job->archive_compressed_size = archive_compressed_sizes[i];
autoar_extractor_start (extractor,
extract_job->common.cancellable);
g_signal_handlers_disconnect_by_data (extractor,
extract_job);
extract_job->base_progress += (gdouble) extract_job->archive_compressed_size /
(gdouble) extract_job->total_compressed_size;
}
if (!job_aborted ((CommonJob *) extract_job))
{
report_extract_final_progress (extract_job, total_files);
}
for (l = extract_job->output_files; l != NULL; l = l->next)
{
GFile *output_file;
output_file = G_FILE (l->data);
if (g_file_query_exists (output_file, NULL))
{
existing_output_files = g_list_prepend (existing_output_files,
g_object_ref (output_file));
}
}
g_list_free_full (extract_job->output_files, g_object_unref);
extract_job->output_files = existing_output_files;
if (extract_job->common.undo_info)
{
if (extract_job->output_files)
{
NautilusFileUndoInfoExtract *undo_info;
undo_info = NAUTILUS_FILE_UNDO_INFO_EXTRACT (extract_job->common.undo_info);
nautilus_file_undo_info_extract_set_outputs (undo_info,
extract_job->output_files);
}
else
{
/* There is nothing to undo if there is no output */
g_clear_object (&extract_job->common.undo_info);
}
}
}
void
nautilus_file_operations_extract_files (GList *files,
GFile *destination_directory,
GtkWindow *parent_window,
NautilusExtractCallback done_callback,
gpointer done_callback_data)
{
ExtractJob *extract_job;
g_autoptr (GTask) task = NULL;
extract_job = op_job_new (ExtractJob, parent_window);
extract_job->source_files = g_list_copy_deep (files,
(GCopyFunc) g_object_ref,
NULL);
extract_job->destination_directory = g_object_ref (destination_directory);
extract_job->done_callback = done_callback;
extract_job->done_callback_data = done_callback_data;
inhibit_power_manager ((CommonJob *) extract_job, _("Extracting Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
extract_job->common.undo_info = nautilus_file_undo_info_extract_new (files,
destination_directory);
}
task = g_task_new (NULL, extract_job->common.cancellable,
extract_task_done, extract_job);
g_task_set_task_data (task, extract_job, NULL);
g_task_run_in_thread (task, extract_task_thread_func);
}
static void
compress_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
CompressJob *compress_job = user_data;
if (compress_job->done_callback)
{
compress_job->done_callback (compress_job->output_file,
compress_job->success,
compress_job->done_callback_data);
}
g_object_unref (compress_job->output_file);
g_list_free_full (compress_job->source_files, g_object_unref);
finalize_common ((CommonJob *) compress_job);
nautilus_file_changes_consume_changes (TRUE);
}
static void
compress_job_on_progress (AutoarCompressor *compressor,
guint64 completed_size,
guint completed_files,
gpointer user_data)
{
CompressJob *compress_job = user_data;
CommonJob *common = user_data;
char *status;
char *details;
int files_left;
double elapsed;
double transfer_rate;
int remaining_time;
files_left = compress_job->total_files - completed_files;
if (compress_job->total_files == 1)
{
status = f (_("Compressing “%B” into “%B”"),
G_FILE (compress_job->source_files->data),
compress_job->output_file);
}
else
{
status = f (ngettext ("Compressing %'d file into “%B”",
"Compressing %'d files into “%B”",
compress_job->total_files),
compress_job->total_files,
compress_job->output_file);
}
nautilus_progress_info_take_status (common->progress, status);
elapsed = g_timer_elapsed (common->time, NULL);
transfer_rate = 0;
remaining_time = -1;
if (elapsed > 0)
{
if (completed_size > 0)
{
transfer_rate = completed_size / elapsed;
remaining_time = (compress_job->total_size - completed_size) / transfer_rate;
}
else if (completed_files > 0)
{
transfer_rate = completed_files / elapsed;
remaining_time = (compress_job->total_files - completed_files) / transfer_rate;
}
}
if (elapsed < SECONDS_NEEDED_FOR_RELIABLE_TRANSFER_RATE ||
transfer_rate == 0)
{
if (compress_job->total_files == 1)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", so something like "4 kb / 4 MB" */
details = f (_("%S / %S"), completed_size, compress_job->total_size);
}
else
{
details = f (_("%'d / %'d"),
files_left > 0 ? completed_files + 1 : completed_files,
compress_job->total_files);
}
}
else
{
if (compress_job->total_files == 1)
{
if (files_left > 0)
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB", %T to a time duration like
* "2 minutes". So the whole thing will be something like "2 kb / 4 MB -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%S / %S \xE2\x80\x94 %T left (%S/sec)",
"%S / %S \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
completed_size, compress_job->total_size,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %S will expand to a size like "2 bytes" or "3 MB". */
details = f (_("%S / %S"),
completed_size,
compress_job->total_size);
}
}
else
{
if (files_left > 0)
{
/* To translators: %T will expand to a time duration like "2 minutes".
* So the whole thing will be something like "1 / 5 -- 2 hours left (4kb/sec)"
*
* The singular/plural form will be used depending on the remaining time (i.e. the %T argument).
*/
details = f (ngettext ("%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
"%'d / %'d \xE2\x80\x94 %T left (%S/sec)",
seconds_count_format_time_units (remaining_time)),
completed_files + 1, compress_job->total_files,
remaining_time,
(goffset) transfer_rate);
}
else
{
/* To translators: %'d is the number of files completed for the operation,
* so it will be something like 2/14. */
details = f (_("%'d / %'d"),
completed_files,
compress_job->total_files);
}
}
}
nautilus_progress_info_take_details (common->progress, details);
if (elapsed > SECONDS_NEEDED_FOR_APROXIMATE_TRANSFER_RATE)
{
nautilus_progress_info_set_remaining_time (common->progress,
remaining_time);
nautilus_progress_info_set_elapsed_time (common->progress,
elapsed);
}
nautilus_progress_info_set_progress (common->progress,
completed_size,
compress_job->total_size);
}
static void
compress_job_on_error (AutoarCompressor *compressor,
GError *error,
gpointer user_data)
{
CompressJob *compress_job = user_data;
char *status;
if (compress_job->total_files == 1)
{
status = f (_("Error compressing “%B” into “%B”"),
G_FILE (compress_job->source_files->data),
compress_job->output_file);
}
else
{
status = f (ngettext ("Error compressing %'d file into “%B”",
"Error compressing %'d files into “%B”",
compress_job->total_files),
compress_job->total_files,
compress_job->output_file);
}
nautilus_progress_info_take_status (compress_job->common.progress,
status);
run_error ((CommonJob *) compress_job,
g_strdup (_("There was an error while compressing files.")),
g_strdup (error->message),
NULL,
FALSE,
CANCEL,
NULL);
abort_job ((CommonJob *) compress_job);
}
static void
compress_job_on_completed (AutoarCompressor *compressor,
gpointer user_data)
{
CompressJob *compress_job = user_data;
g_autoptr (GFile) destination_directory = NULL;
char *status;
if (compress_job->total_files == 1)
{
status = f (_("Compressed “%B” into “%B”"),
G_FILE (compress_job->source_files->data),
compress_job->output_file);
}
else
{
status = f (ngettext ("Compressed %'d file into “%B”",
"Compressed %'d files into “%B”",
compress_job->total_files),
compress_job->total_files,
compress_job->output_file);
}
nautilus_progress_info_take_status (compress_job->common.progress,
status);
nautilus_file_changes_queue_file_added (compress_job->output_file);
destination_directory = g_file_get_parent (compress_job->output_file);
nautilus_progress_info_set_destination (compress_job->common.progress,
destination_directory);
}
static void
compress_task_thread_func (GTask *task,
gpointer source_object,
gpointer task_data,
GCancellable *cancellable)
{
CompressJob *compress_job = task_data;
SourceInfo source_info;
g_autoptr (AutoarCompressor) compressor = NULL;
g_timer_start (compress_job->common.time);
nautilus_progress_info_start (compress_job->common.progress);
scan_sources (compress_job->source_files,
&source_info,
(CommonJob *) compress_job,
OP_KIND_COMPRESS);
compress_job->total_files = source_info.num_files;
compress_job->total_size = source_info.num_bytes;
compressor = autoar_compressor_new (compress_job->source_files,
compress_job->output_file,
compress_job->format,
compress_job->filter,
FALSE);
autoar_compressor_set_output_is_dest (compressor, TRUE);
autoar_compressor_set_notify_interval (compressor,
PROGRESS_NOTIFY_INTERVAL);
g_signal_connect (compressor, "progress",
G_CALLBACK (compress_job_on_progress), compress_job);
g_signal_connect (compressor, "error",
G_CALLBACK (compress_job_on_error), compress_job);
g_signal_connect (compressor, "completed",
G_CALLBACK (compress_job_on_completed), compress_job);
autoar_compressor_start (compressor,
compress_job->common.cancellable);
compress_job->success = g_file_query_exists (compress_job->output_file,
NULL);
/* There is nothing to undo if the output was not created */
if (compress_job->common.undo_info != NULL && !compress_job->success)
{
g_clear_object (&compress_job->common.undo_info);
}
}
void
nautilus_file_operations_compress (GList *files,
GFile *output,
AutoarFormat format,
AutoarFilter filter,
GtkWindow *parent_window,
NautilusCreateCallback done_callback,
gpointer done_callback_data)
{
g_autoptr (GTask) task = NULL;
CompressJob *compress_job;
compress_job = op_job_new (CompressJob, parent_window);
compress_job->source_files = g_list_copy_deep (files,
(GCopyFunc) g_object_ref,
NULL);
compress_job->output_file = g_object_ref (output);
compress_job->format = format;
compress_job->filter = filter;
compress_job->done_callback = done_callback;
compress_job->done_callback_data = done_callback_data;
inhibit_power_manager ((CommonJob *) compress_job, _("Compressing Files"));
if (!nautilus_file_undo_manager_is_operating ())
{
compress_job->common.undo_info = nautilus_file_undo_info_compress_new (files,
output,
format,
filter);
}
task = g_task_new (NULL, compress_job->common.cancellable,
compress_task_done, compress_job);
g_task_set_task_data (task, compress_job, NULL);
g_task_run_in_thread (task, compress_task_thread_func);
}
#if !defined (NAUTILUS_OMIT_SELF_CHECK)
void
nautilus_self_check_file_operations (void)
{
setlocale (LC_MESSAGES, "C");
/* test the next duplicate name generator */
EEL_CHECK_STRING_RESULT (get_duplicate_name (" (copy)", 1, -1), " (another copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo", 1, -1), "foo (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name (".bashrc", 1, -1), ".bashrc (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name (".foo.txt", 1, -1), ".foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo", 1, -1), "foo foo (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo.txt", 1, -1), "foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo.txt", 1, -1), "foo foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo.txt txt", 1, -1), "foo foo (copy).txt txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo...txt", 1, -1), "foo.. (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo...", 1, -1), "foo... (copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo. (copy)", 1, -1), "foo. (another copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (copy)", 1, -1), "foo (another copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (copy).txt", 1, -1), "foo (another copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (another copy)", 1, -1), "foo (3rd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (another copy).txt", 1, -1), "foo (3rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (another copy).txt", 1, -1), "foo foo (3rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (13th copy)", 1, -1), "foo (14th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (13th copy).txt", 1, -1), "foo (14th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (21st copy)", 1, -1), "foo (22nd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (21st copy).txt", 1, -1), "foo (22nd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (22nd copy)", 1, -1), "foo (23rd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (22nd copy).txt", 1, -1), "foo (23rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (23rd copy)", 1, -1), "foo (24th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (23rd copy).txt", 1, -1), "foo (24th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (24th copy)", 1, -1), "foo (25th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (24th copy).txt", 1, -1), "foo (25th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (24th copy)", 1, -1), "foo foo (25th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (24th copy).txt", 1, -1), "foo foo (25th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo foo (100000000000000th copy).txt", 1, -1), "foo foo (copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (10th copy)", 1, -1), "foo (11th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (10th copy).txt", 1, -1), "foo (11th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (11th copy)", 1, -1), "foo (12th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (11th copy).txt", 1, -1), "foo (12th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (12th copy)", 1, -1), "foo (13th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (12th copy).txt", 1, -1), "foo (13th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (110th copy)", 1, -1), "foo (111th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (110th copy).txt", 1, -1), "foo (111th copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (122nd copy)", 1, -1), "foo (123rd copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (122nd copy).txt", 1, -1), "foo (123rd copy).txt");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (123rd copy)", 1, -1), "foo (124th copy)");
EEL_CHECK_STRING_RESULT (get_duplicate_name ("foo (123rd copy).txt", 1, -1), "foo (124th copy).txt");
setlocale (LC_MESSAGES, "");
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2802_1 |
crossvul-cpp_data_good_5115_0 | /*
* packet-pktap.c
* Routines for dissecting Apple's PKTAP header
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 2007 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <epan/packet.h>
#include <epan/expert.h>
#include <wsutil/pint.h>
#include "packet-frame.h"
#include "packet-eth.h"
#include "packet-pktap.h"
/* Needed for wtap_pcap_encap_to_wtap_encap(). */
#include <wiretap/pcap-encap.h>
void proto_register_pktap(void);
void proto_reg_handoff_pktap(void);
/*
* Apple's PKTAP header.
*/
/*
* Minimum header length.
*
* XXX - I'm assuming the header begins with a length field so that it
* can be transparently *extended*, not so that fields in the current
* header can be *omitted*.
*/
#define MIN_PKTAP_HDR_LEN 108
/*
* Record types.
*/
#define PKT_REC_NONE 0 /* nothing follows the header */
#define PKT_REC_PACKET 1 /* a packet follows the header */
/* Protocol */
static int proto_pktap = -1;
static int hf_pktap_hdrlen = -1;
static int hf_pktap_rectype = -1;
static int hf_pktap_dlt = -1;
static int hf_pktap_ifname = -1;
static int hf_pktap_flags = -1;
static int hf_pktap_pfamily = -1;
static int hf_pktap_llhdrlen = -1;
static int hf_pktap_lltrlrlen = -1;
static int hf_pktap_pid = -1;
static int hf_pktap_cmdname = -1;
static int hf_pktap_svc_class = -1;
static int hf_pktap_iftype = -1;
static int hf_pktap_ifunit = -1;
static int hf_pktap_epid = -1;
static int hf_pktap_ecmdname = -1;
static gint ett_pktap = -1;
static expert_field ei_pktap_hdrlen_too_short = EI_INIT;
static dissector_handle_t pktap_handle;
/*
* XXX - these are little-endian in the captures I've seen, but Apple
* no longer make any big-endian machines (Macs use x86, iOS machines
* use ARM and run it little-endian), so that might be by definition
* or they might be host-endian.
*
* If a big-endian PKTAP file ever shows up, and it comes from a
* big-endian machine, presumably these are host-endian, and we need
* to just fetch the fields in host byte order here but byte-swap them
* to host byte order in libwiretap.
*/
void
capture_pktap(const guchar *pd, int len, packet_counts *ld)
{
guint32 hdrlen, rectype, dlt;
hdrlen = pletoh32(pd);
if (hdrlen < MIN_PKTAP_HDR_LEN || !BYTES_ARE_IN_FRAME(0, len, hdrlen)) {
ld->other++;
return;
}
rectype = pletoh32(pd+4);
if (rectype != PKT_REC_PACKET) {
ld->other++;
return;
}
dlt = pletoh32(pd+4);
/* XXX - We should probably combine this with capture_info.c:capture_info_packet() */
switch (dlt) {
case 1: /* DLT_EN10MB */
capture_eth(pd, hdrlen, len, ld);
return;
default:
break;
}
ld->other++;
}
static void
dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *pktap_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint32 pkt_len, rectype, dlt;
int wtap_encap;
struct eth_phdr eth;
void *phdr;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP");
col_clear(pinfo->cinfo, COL_INFO);
pkt_len = tvb_get_letohl(tvb, offset);
col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len);
/* Dissect the packet */
ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA);
pktap_tree = proto_item_add_subtree(ti, ett_pktap);
proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
if (pkt_len < MIN_PKTAP_HDR_LEN) {
proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short,
tvb, offset, 4);
return;
}
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
rectype = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
dlt = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24,
ENC_ASCII|ENC_NA);
offset += 24;
proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
offset += 20;
proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
/*offset += 20;*/
if (rectype == PKT_REC_PACKET) {
next_tvb = tvb_new_subset_remaining(tvb, pkt_len);
wtap_encap = wtap_pcap_encap_to_wtap_encap(dlt);
switch (wtap_encap) {
case WTAP_ENCAP_ETHERNET:
eth.fcs_len = -1; /* Unknown whether we have an FCS */
phdr = ð
break;
default:
phdr = NULL;
break;
}
dissector_try_uint_new(wtap_encap_dissector_table,
wtap_encap, next_tvb, pinfo, tree, TRUE, phdr);
}
}
void
proto_register_pktap(void)
{
static hf_register_info hf[] = {
{ &hf_pktap_hdrlen,
{ "Header length", "pktap.hdrlen",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_rectype,
{ "Record type", "pktap.rectype",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_dlt,
{ "DLT", "pktap.dlt",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_ifname, /* fixed length *and* null-terminated */
{ "Interface name", "pktap.ifname",
FT_STRINGZ, BASE_NONE, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_flags,
{ "Flags", "pktap.flags",
FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_pfamily,
{ "Protocol family", "pktap.pfamily",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_llhdrlen,
{ "Link-layer header length", "pktap.llhdrlen",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_lltrlrlen,
{ "Link-layer trailer length", "pktap.lltrlrlen",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_pid,
{ "Process ID", "pktap.pid",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_cmdname, /* fixed length *and* null-terminated */
{ "Command name", "pktap.cmdname",
FT_STRINGZ, BASE_NONE, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_svc_class,
{ "Service class", "pktap.svc_class",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_iftype,
{ "Interface type", "pktap.iftype",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_ifunit,
{ "Interface unit", "pktap.ifunit",
FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_epid,
{ "Effective process ID", "pktap.epid",
FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } },
{ &hf_pktap_ecmdname, /* fixed length *and* null-terminated */
{ "Effective command name", "pktap.ecmdname",
FT_STRINGZ, BASE_NONE, NULL, 0x0, NULL, HFILL } },
};
static gint *ett[] = {
&ett_pktap,
};
static ei_register_info ei[] = {
{ &ei_pktap_hdrlen_too_short,
{ "pktap.hdrlen_too_short", PI_MALFORMED, PI_ERROR,
"Header length is too short", EXPFILL }},
};
expert_module_t* expert_pktap;
proto_pktap = proto_register_protocol("PKTAP packet header", "PKTAP",
"pktap");
proto_register_field_array(proto_pktap, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_pktap = expert_register_protocol(proto_pktap);
expert_register_field_array(expert_pktap, ei, array_length(ei));
pktap_handle = register_dissector("pktap", dissect_pktap, proto_pktap);
}
void
proto_reg_handoff_pktap(void)
{
dissector_add_uint("wtap_encap", WTAP_ENCAP_PKTAP, pktap_handle);
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5115_0 |
crossvul-cpp_data_good_2138_0 | /*-
* Copyright (c) 2008 Christos Zoulas
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Parse Composite Document Files, the format used in Microsoft Office
* document files before they switched to zipped XML.
* Info from: http://sc.openoffice.org/compdocfileformat.pdf
*
* N.B. This is the "Composite Document File" format, and not the
* "Compound Document Format", nor the "Channel Definition Format".
*/
#include "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: cdf.c,v 1.62 2014/06/04 17:26:07 christos Exp $")
#endif
#include <assert.h>
#ifdef CDF_DEBUG
#include <err.h>
#endif
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#ifndef EFTYPE
#define EFTYPE EINVAL
#endif
#include "cdf.h"
#ifdef CDF_DEBUG
#define DPRINTF(a) printf a, fflush(stdout)
#else
#define DPRINTF(a)
#endif
static union {
char s[4];
uint32_t u;
} cdf_bo;
#define NEED_SWAP (cdf_bo.u == (uint32_t)0x01020304)
#define CDF_TOLE8(x) ((uint64_t)(NEED_SWAP ? _cdf_tole8(x) : (uint64_t)(x)))
#define CDF_TOLE4(x) ((uint32_t)(NEED_SWAP ? _cdf_tole4(x) : (uint32_t)(x)))
#define CDF_TOLE2(x) ((uint16_t)(NEED_SWAP ? _cdf_tole2(x) : (uint16_t)(x)))
#define CDF_GETUINT32(x, y) cdf_getuint32(x, y)
/*
* swap a short
*/
static uint16_t
_cdf_tole2(uint16_t sv)
{
uint16_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[1];
d[1] = s[0];
return rv;
}
/*
* swap an int
*/
static uint32_t
_cdf_tole4(uint32_t sv)
{
uint32_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[3];
d[1] = s[2];
d[2] = s[1];
d[3] = s[0];
return rv;
}
/*
* swap a quad
*/
static uint64_t
_cdf_tole8(uint64_t sv)
{
uint64_t rv;
uint8_t *s = (uint8_t *)(void *)&sv;
uint8_t *d = (uint8_t *)(void *)&rv;
d[0] = s[7];
d[1] = s[6];
d[2] = s[5];
d[3] = s[4];
d[4] = s[3];
d[5] = s[2];
d[6] = s[1];
d[7] = s[0];
return rv;
}
/*
* grab a uint32_t from a possibly unaligned address, and return it in
* the native host order.
*/
static uint32_t
cdf_getuint32(const uint8_t *p, size_t offs)
{
uint32_t rv;
(void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv));
return CDF_TOLE4(rv);
}
#define CDF_UNPACK(a) \
(void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a)
#define CDF_UNPACKA(a) \
(void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a)
uint16_t
cdf_tole2(uint16_t sv)
{
return CDF_TOLE2(sv);
}
uint32_t
cdf_tole4(uint32_t sv)
{
return CDF_TOLE4(sv);
}
uint64_t
cdf_tole8(uint64_t sv)
{
return CDF_TOLE8(sv);
}
void
cdf_swap_header(cdf_header_t *h)
{
size_t i;
h->h_magic = CDF_TOLE8(h->h_magic);
h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]);
h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]);
h->h_revision = CDF_TOLE2(h->h_revision);
h->h_version = CDF_TOLE2(h->h_version);
h->h_byte_order = CDF_TOLE2(h->h_byte_order);
h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2);
h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2);
h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat);
h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory);
h->h_min_size_standard_stream =
CDF_TOLE4(h->h_min_size_standard_stream);
h->h_secid_first_sector_in_short_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_short_sat);
h->h_num_sectors_in_short_sat =
CDF_TOLE4(h->h_num_sectors_in_short_sat);
h->h_secid_first_sector_in_master_sat =
CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_master_sat);
h->h_num_sectors_in_master_sat =
CDF_TOLE4(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
h->h_master_sat[i] = CDF_TOLE4((uint32_t)h->h_master_sat[i]);
}
void
cdf_unpack_header(cdf_header_t *h, char *buf)
{
size_t i;
size_t len = 0;
CDF_UNPACK(h->h_magic);
CDF_UNPACKA(h->h_uuid);
CDF_UNPACK(h->h_revision);
CDF_UNPACK(h->h_version);
CDF_UNPACK(h->h_byte_order);
CDF_UNPACK(h->h_sec_size_p2);
CDF_UNPACK(h->h_short_sec_size_p2);
CDF_UNPACKA(h->h_unused0);
CDF_UNPACK(h->h_num_sectors_in_sat);
CDF_UNPACK(h->h_secid_first_directory);
CDF_UNPACKA(h->h_unused1);
CDF_UNPACK(h->h_min_size_standard_stream);
CDF_UNPACK(h->h_secid_first_sector_in_short_sat);
CDF_UNPACK(h->h_num_sectors_in_short_sat);
CDF_UNPACK(h->h_secid_first_sector_in_master_sat);
CDF_UNPACK(h->h_num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++)
CDF_UNPACK(h->h_master_sat[i]);
}
void
cdf_swap_dir(cdf_directory_t *d)
{
d->d_namelen = CDF_TOLE2(d->d_namelen);
d->d_left_child = CDF_TOLE4((uint32_t)d->d_left_child);
d->d_right_child = CDF_TOLE4((uint32_t)d->d_right_child);
d->d_storage = CDF_TOLE4((uint32_t)d->d_storage);
d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]);
d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]);
d->d_flags = CDF_TOLE4(d->d_flags);
d->d_created = CDF_TOLE8((uint64_t)d->d_created);
d->d_modified = CDF_TOLE8((uint64_t)d->d_modified);
d->d_stream_first_sector = CDF_TOLE4((uint32_t)d->d_stream_first_sector);
d->d_size = CDF_TOLE4(d->d_size);
}
void
cdf_swap_class(cdf_classid_t *d)
{
d->cl_dword = CDF_TOLE4(d->cl_dword);
d->cl_word[0] = CDF_TOLE2(d->cl_word[0]);
d->cl_word[1] = CDF_TOLE2(d->cl_word[1]);
}
void
cdf_unpack_dir(cdf_directory_t *d, char *buf)
{
size_t len = 0;
CDF_UNPACKA(d->d_name);
CDF_UNPACK(d->d_namelen);
CDF_UNPACK(d->d_type);
CDF_UNPACK(d->d_color);
CDF_UNPACK(d->d_left_child);
CDF_UNPACK(d->d_right_child);
CDF_UNPACK(d->d_storage);
CDF_UNPACKA(d->d_storage_uuid);
CDF_UNPACK(d->d_flags);
CDF_UNPACK(d->d_created);
CDF_UNPACK(d->d_modified);
CDF_UNPACK(d->d_stream_first_sector);
CDF_UNPACK(d->d_size);
CDF_UNPACK(d->d_unused0);
}
static int
cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
const void *p, size_t tail, int line)
{
const char *b = (const char *)sst->sst_tab;
const char *e = ((const char *)p) + tail;
size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ?
CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h);
(void)&line;
if (e >= b && (size_t)(e - b) <= ss * sst->sst_len)
return 0;
DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
" > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
ss * sst->sst_len, ss, sst->sst_len));
errno = EFTYPE;
return -1;
}
static ssize_t
cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len)
{
size_t siz = (size_t)off + len;
if ((off_t)(off + len) != (off_t)siz) {
errno = EINVAL;
return -1;
}
if (info->i_buf != NULL && info->i_len >= siz) {
(void)memcpy(buf, &info->i_buf[off], len);
return (ssize_t)len;
}
if (info->i_fd == -1)
return -1;
if (pread(info->i_fd, buf, len, off) != (ssize_t)len)
return -1;
return (ssize_t)len;
}
int
cdf_read_header(const cdf_info_t *info, cdf_header_t *h)
{
char buf[512];
(void)memcpy(cdf_bo.s, "\01\02\03\04", 4);
if (cdf_read(info, (off_t)0, buf, sizeof(buf)) == -1)
return -1;
cdf_unpack_header(h, buf);
cdf_swap_header(h);
if (h->h_magic != CDF_MAGIC) {
DPRINTF(("Bad magic 0x%" INT64_T_FORMAT "x != 0x%"
INT64_T_FORMAT "x\n",
(unsigned long long)h->h_magic,
(unsigned long long)CDF_MAGIC));
goto out;
}
if (h->h_sec_size_p2 > 20) {
DPRINTF(("Bad sector size 0x%u\n", h->h_sec_size_p2));
goto out;
}
if (h->h_short_sec_size_p2 > 20) {
DPRINTF(("Bad short sector size 0x%u\n",
h->h_short_sec_size_p2));
goto out;
}
return 0;
out:
errno = EFTYPE;
return -1;
}
ssize_t
cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SEC_SIZE(h);
size_t pos = CDF_SEC_POS(h, id);
assert(ss == len);
return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len);
}
ssize_t
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,
size_t len, const cdf_header_t *h, cdf_secid_t id)
{
size_t ss = CDF_SHORT_SEC_SIZE(h);
size_t pos = CDF_SHORT_SEC_POS(h, id);
assert(ss == len);
if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) {
DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
SIZE_T_FORMAT "u\n",
pos + len, CDF_SEC_SIZE(h) * sst->sst_len));
return -1;
}
(void)memcpy(((char *)buf) + offs,
((const char *)sst->sst_tab) + pos, len);
return len;
}
/*
* Read the sector allocation table.
*/
int
cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat)
{
size_t i, j, k;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t *msa, mid, sec;
size_t nsatpersec = (ss / sizeof(mid)) - 1;
for (i = 0; i < __arraycount(h->h_master_sat); i++)
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
#define CDF_SEC_LIMIT (UINT32_MAX / (4 * ss))
if ((nsatpersec > 0 &&
h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) ||
i > CDF_SEC_LIMIT) {
DPRINTF(("Number of sectors in master SAT too big %u %"
SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i));
errno = EFTYPE;
return -1;
}
sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i;
DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n",
sat->sat_len, ss));
if ((sat->sat_tab = CAST(cdf_secid_t *, calloc(sat->sat_len, ss)))
== NULL)
return -1;
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] < 0)
break;
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
h->h_master_sat[i]) != (ssize_t)ss) {
DPRINTF(("Reading sector %d", h->h_master_sat[i]));
goto out1;
}
}
if ((msa = CAST(cdf_secid_t *, calloc(1, ss))) == NULL)
goto out1;
mid = h->h_secid_first_sector_in_master_sat;
for (j = 0; j < h->h_num_sectors_in_master_sat; j++) {
if (mid < 0)
goto out;
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Reading master sector loop limit"));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, msa, 0, ss, h, mid) != (ssize_t)ss) {
DPRINTF(("Reading master sector %d", mid));
goto out2;
}
for (k = 0; k < nsatpersec; k++, i++) {
sec = CDF_TOLE4((uint32_t)msa[k]);
if (sec < 0)
goto out;
if (i >= sat->sat_len) {
DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT
"u >= %" SIZE_T_FORMAT "u", i, sat->sat_len));
errno = EFTYPE;
goto out2;
}
if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
sec) != (ssize_t)ss) {
DPRINTF(("Reading sector %d",
CDF_TOLE4(msa[k])));
goto out2;
}
}
mid = CDF_TOLE4((uint32_t)msa[nsatpersec]);
}
out:
sat->sat_len = i;
free(msa);
return 0;
out2:
free(msa);
out1:
free(sat->sat_tab);
return -1;
}
size_t
cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)
{
size_t i, j;
cdf_secid_t maxsector = (cdf_secid_t)((sat->sat_len * size)
/ sizeof(maxsector));
DPRINTF(("Chain:"));
for (j = i = 0; sid >= 0; i++, j++) {
DPRINTF((" %d", sid));
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Counting chain loop limit"));
errno = EFTYPE;
return (size_t)-1;
}
if (sid >= maxsector) {
DPRINTF(("Sector %d >= %d\n", sid, maxsector));
errno = EFTYPE;
return (size_t)-1;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (i == 0) {
DPRINTF((" none, sid: %d\n", sid));
return (size_t)-1;
}
DPRINTF(("\n"));
return i;
}
int
cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SEC_SIZE(h), i, j;
ssize_t nr;
scn->sst_len = cdf_count_chain(sat, sid, ss);
scn->sst_dirlen = len;
if (scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read long sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading long sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
scn->sst_len));
errno = EFTYPE;
goto out;
}
if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h,
sid)) != (ssize_t)ss) {
if (i == scn->sst_len - 1 && nr > 0) {
/* Last sector might be truncated */
return 0;
}
DPRINTF(("Reading long sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_short_sector_chain(const cdf_header_t *h,
const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
size_t ss = CDF_SHORT_SEC_SIZE(h), i, j;
scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
scn->sst_dirlen = len;
if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1)
return -1;
scn->sst_tab = calloc(scn->sst_len, ss);
if (scn->sst_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sector chain loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= scn->sst_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
i, scn->sst_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
sid) != (ssize_t)ss) {
DPRINTF(("Reading short sector chain %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
}
return 0;
out:
free(scn->sst_tab);
return -1;
}
int
cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
cdf_secid_t sid, size_t len, cdf_stream_t *scn)
{
if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL)
return cdf_read_short_sector_chain(h, ssat, sst, sid, len,
scn);
else
return cdf_read_long_sector_chain(info, h, sat, sid, len, scn);
}
int
cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_dir_t *dir)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h), ns, nd;
char *buf;
cdf_secid_t sid = h->h_secid_first_directory;
ns = cdf_count_chain(sat, sid, ss);
if (ns == (size_t)-1)
return -1;
nd = ss / CDF_DIRECTORY_SIZE;
dir->dir_len = ns * nd;
dir->dir_tab = CAST(cdf_directory_t *,
calloc(dir->dir_len, sizeof(dir->dir_tab[0])));
if (dir->dir_tab == NULL)
return -1;
if ((buf = CAST(char *, malloc(ss))) == NULL) {
free(dir->dir_tab);
return -1;
}
for (j = i = 0; i < ns; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read dir loop limit"));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, buf, 0, ss, h, sid) != (ssize_t)ss) {
DPRINTF(("Reading directory sector %d", sid));
goto out;
}
for (j = 0; j < nd; j++) {
cdf_unpack_dir(&dir->dir_tab[i * nd + j],
&buf[j * CDF_DIRECTORY_SIZE]);
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
if (NEED_SWAP)
for (i = 0; i < dir->dir_len; i++)
cdf_swap_dir(&dir->dir_tab[i]);
free(buf);
return 0;
out:
free(dir->dir_tab);
free(buf);
return -1;
}
int
cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, cdf_sat_t *ssat)
{
size_t i, j;
size_t ss = CDF_SEC_SIZE(h);
cdf_secid_t sid = h->h_secid_first_sector_in_short_sat;
ssat->sat_len = cdf_count_chain(sat, sid, CDF_SEC_SIZE(h));
if (ssat->sat_len == (size_t)-1)
return -1;
ssat->sat_tab = CAST(cdf_secid_t *, calloc(ssat->sat_len, ss));
if (ssat->sat_tab == NULL)
return -1;
for (j = i = 0; sid >= 0; i++, j++) {
if (j >= CDF_LOOP_LIMIT) {
DPRINTF(("Read short sat sector loop limit"));
errno = EFTYPE;
goto out;
}
if (i >= ssat->sat_len) {
DPRINTF(("Out of bounds reading short sector chain "
"%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
ssat->sat_len));
errno = EFTYPE;
goto out;
}
if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) !=
(ssize_t)ss) {
DPRINTF(("Reading short sat sector %d", sid));
goto out;
}
sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
}
return 0;
out:
free(ssat->sat_tab);
return -1;
}
int
cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
const cdf_directory_t **root)
{
size_t i;
const cdf_directory_t *d;
*root = NULL;
for (i = 0; i < dir->dir_len; i++)
if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
break;
/* If the it is not there, just fake it; some docs don't have it */
if (i == dir->dir_len)
goto out;
d = &dir->dir_tab[i];
*root = d;
/* If the it is not there, just fake it; some docs don't have it */
if (d->d_stream_first_sector < 0)
goto out;
return cdf_read_long_sector_chain(info, h, sat,
d->d_stream_first_sector, d->d_size, scn);
out:
scn->sst_tab = NULL;
scn->sst_len = 0;
scn->sst_dirlen = 0;
return 0;
}
static int
cdf_namecmp(const char *d, const uint16_t *s, size_t l)
{
for (; l--; d++, s++)
if (*d != CDF_TOLE2(*s))
return (unsigned char)*d - CDF_TOLE2(*s);
return 0;
}
int
cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir, cdf_stream_t *scn)
{
return cdf_read_user_stream(info, h, sat, ssat, sst, dir,
"\05SummaryInformation", scn);
}
int
cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir, const char *name, cdf_stream_t *scn)
{
size_t i;
const cdf_directory_t *d;
size_t name_len = strlen(name) + 1;
for (i = dir->dir_len; i > 0; i--)
if (dir->dir_tab[i - 1].d_type == CDF_DIR_TYPE_USER_STREAM &&
cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len)
== 0)
break;
if (i == 0) {
DPRINTF(("Cannot find user stream `%s'\n", name));
errno = ESRCH;
return -1;
}
d = &dir->dir_tab[i - 1];
return cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, scn);
}
int
cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
{
const cdf_section_header_t *shp;
cdf_section_header_t sh;
const uint8_t *p, *q, *e;
int16_t s16;
int32_t s32;
uint32_t u32;
int64_t s64;
uint64_t u64;
cdf_timestamp_t tp;
size_t i, o, o4, nelements, j;
cdf_property_info_t *inp;
if (offs > UINT32_MAX / 4) {
errno = EFTYPE;
goto out;
}
shp = CAST(const cdf_section_header_t *, (const void *)
((const char *)sst->sst_tab + offs));
if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
goto out;
sh.sh_len = CDF_TOLE4(shp->sh_len);
#define CDF_SHLEN_LIMIT (UINT32_MAX / 8)
if (sh.sh_len > CDF_SHLEN_LIMIT) {
errno = EFTYPE;
goto out;
}
sh.sh_properties = CDF_TOLE4(shp->sh_properties);
#define CDF_PROP_LIMIT (UINT32_MAX / (4 * sizeof(*inp)))
if (sh.sh_properties > CDF_PROP_LIMIT)
goto out;
DPRINTF(("section len: %u properties %u\n", sh.sh_len,
sh.sh_properties));
if (*maxcount) {
if (*maxcount > CDF_PROP_LIMIT)
goto out;
*maxcount += sh.sh_properties;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
} else {
*maxcount = sh.sh_properties;
inp = CAST(cdf_property_info_t *,
malloc(*maxcount * sizeof(*inp)));
}
if (inp == NULL)
goto out;
*info = inp;
inp += *count;
*count += sh.sh_properties;
p = CAST(const uint8_t *, (const void *)
((const char *)(const void *)sst->sst_tab +
offs + sizeof(sh)));
e = CAST(const uint8_t *, (const void *)
(((const char *)(const void *)shp) + sh.sh_len));
if (cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
goto out;
for (i = 0; i < sh.sh_properties; i++) {
size_t tail = (i << 1) + 1;
if (cdf_check_stream_offset(sst, h, p, tail * sizeof(uint32_t),
__LINE__) == -1)
goto out;
size_t ofs = CDF_GETUINT32(p, tail);
q = (const uint8_t *)(const void *)
((const char *)(const void *)p + ofs
- 2 * sizeof(uint32_t));
if (q > e) {
DPRINTF(("Ran of the end %p > %p\n", q, e));
goto out;
}
inp[i].pi_id = CDF_GETUINT32(p, i << 1);
inp[i].pi_type = CDF_GETUINT32(q, 0);
DPRINTF(("%" SIZE_T_FORMAT "u) id=%x type=%x offs=0x%tx,0x%x\n",
i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
if (inp[i].pi_type & CDF_VECTOR) {
nelements = CDF_GETUINT32(q, 1);
if (nelements == 0) {
DPRINTF(("CDF_VECTOR with nelements == 0\n"));
goto out;
}
o = 2;
} else {
nelements = 1;
o = 1;
}
o4 = o * sizeof(uint32_t);
if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
goto unknown;
switch (inp[i].pi_type & CDF_TYPEMASK) {
case CDF_NULL:
case CDF_EMPTY:
break;
case CDF_SIGNED16:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s16, &q[o4], sizeof(s16));
inp[i].pi_s16 = CDF_TOLE2(s16);
break;
case CDF_SIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s32, &q[o4], sizeof(s32));
inp[i].pi_s32 = CDF_TOLE4((uint32_t)s32);
break;
case CDF_BOOL:
case CDF_UNSIGNED32:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
inp[i].pi_u32 = CDF_TOLE4(u32);
break;
case CDF_SIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&s64, &q[o4], sizeof(s64));
inp[i].pi_s64 = CDF_TOLE8((uint64_t)s64);
break;
case CDF_UNSIGNED64:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
inp[i].pi_u64 = CDF_TOLE8((uint64_t)u64);
break;
case CDF_FLOAT:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u32, &q[o4], sizeof(u32));
u32 = CDF_TOLE4(u32);
memcpy(&inp[i].pi_f, &u32, sizeof(inp[i].pi_f));
break;
case CDF_DOUBLE:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&u64, &q[o4], sizeof(u64));
u64 = CDF_TOLE8((uint64_t)u64);
memcpy(&inp[i].pi_d, &u64, sizeof(inp[i].pi_d));
break;
case CDF_LENGTH32_STRING:
case CDF_LENGTH32_WSTRING:
if (nelements > 1) {
size_t nelem = inp - *info;
if (*maxcount > CDF_PROP_LIMIT
|| nelements > CDF_PROP_LIMIT)
goto out;
*maxcount += nelements;
inp = CAST(cdf_property_info_t *,
realloc(*info, *maxcount * sizeof(*inp)));
if (inp == NULL)
goto out;
*info = inp;
inp = *info + nelem;
}
DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
nelements));
for (j = 0; j < nelements && i < sh.sh_properties;
j++, i++)
{
uint32_t l = CDF_GETUINT32(q, o);
inp[i].pi_str.s_len = l;
inp[i].pi_str.s_buf = (const char *)
(const void *)(&q[o4 + sizeof(l)]);
DPRINTF(("l = %d, r = %" SIZE_T_FORMAT
"u, s = %s\n", l,
CDF_ROUND(l, sizeof(l)),
inp[i].pi_str.s_buf));
if (l & 1)
l++;
o += l >> 1;
if (q + o >= e)
goto out;
o4 = o * sizeof(uint32_t);
}
i--;
break;
case CDF_FILETIME:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
(void)memcpy(&tp, &q[o4], sizeof(tp));
inp[i].pi_tp = CDF_TOLE8((uint64_t)tp);
break;
case CDF_CLIPBOARD:
if (inp[i].pi_type & CDF_VECTOR)
goto unknown;
break;
default:
unknown:
DPRINTF(("Don't know how to deal with %x\n",
inp[i].pi_type));
break;
}
}
return 0;
out:
free(*info);
return -1;
}
int
cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,
cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)
{
size_t maxcount;
const cdf_summary_info_header_t *si =
CAST(const cdf_summary_info_header_t *, sst->sst_tab);
const cdf_section_declaration_t *sd =
CAST(const cdf_section_declaration_t *, (const void *)
((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET));
if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 ||
cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1)
return -1;
ssi->si_byte_order = CDF_TOLE2(si->si_byte_order);
ssi->si_os_version = CDF_TOLE2(si->si_os_version);
ssi->si_os = CDF_TOLE2(si->si_os);
ssi->si_class = si->si_class;
cdf_swap_class(&ssi->si_class);
ssi->si_count = CDF_TOLE4(si->si_count);
*count = 0;
maxcount = 0;
*info = NULL;
if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info,
count, &maxcount) == -1)
return -1;
return 0;
}
int
cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id)
{
return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-"
"%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0],
id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0],
id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4],
id->cl_six[5]);
}
static const struct {
uint32_t v;
const char *n;
} vn[] = {
{ CDF_PROPERTY_CODE_PAGE, "Code page" },
{ CDF_PROPERTY_TITLE, "Title" },
{ CDF_PROPERTY_SUBJECT, "Subject" },
{ CDF_PROPERTY_AUTHOR, "Author" },
{ CDF_PROPERTY_KEYWORDS, "Keywords" },
{ CDF_PROPERTY_COMMENTS, "Comments" },
{ CDF_PROPERTY_TEMPLATE, "Template" },
{ CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" },
{ CDF_PROPERTY_REVISION_NUMBER, "Revision Number" },
{ CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" },
{ CDF_PROPERTY_LAST_PRINTED, "Last Printed" },
{ CDF_PROPERTY_CREATE_TIME, "Create Time/Date" },
{ CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" },
{ CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" },
{ CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" },
{ CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" },
{ CDF_PROPERTY_THUMBNAIL, "Thumbnail" },
{ CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" },
{ CDF_PROPERTY_SECURITY, "Security" },
{ CDF_PROPERTY_LOCALE_ID, "Locale ID" },
};
int
cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p)
{
size_t i;
for (i = 0; i < __arraycount(vn); i++)
if (vn[i].v == p)
return snprintf(buf, bufsiz, "%s", vn[i].n);
return snprintf(buf, bufsiz, "0x%x", p);
}
int
cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts)
{
int len = 0;
int days, hours, mins, secs;
ts /= CDF_TIME_PREC;
secs = (int)(ts % 60);
ts /= 60;
mins = (int)(ts % 60);
ts /= 60;
hours = (int)(ts % 24);
ts /= 24;
days = (int)ts;
if (days) {
len += snprintf(buf + len, bufsiz - len, "%dd+", days);
if ((size_t)len >= bufsiz)
return len;
}
if (days || hours) {
len += snprintf(buf + len, bufsiz - len, "%.2d:", hours);
if ((size_t)len >= bufsiz)
return len;
}
len += snprintf(buf + len, bufsiz - len, "%.2d:", mins);
if ((size_t)len >= bufsiz)
return len;
len += snprintf(buf + len, bufsiz - len, "%.2d", secs);
return len;
}
#ifdef CDF_DEBUG
void
cdf_dump_header(const cdf_header_t *h)
{
size_t i;
#define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b)
#define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \
h->h_ ## b, 1 << h->h_ ## b)
DUMP("%d", revision);
DUMP("%d", version);
DUMP("0x%x", byte_order);
DUMP2("%d", sec_size_p2);
DUMP2("%d", short_sec_size_p2);
DUMP("%d", num_sectors_in_sat);
DUMP("%d", secid_first_directory);
DUMP("%d", min_size_standard_stream);
DUMP("%d", secid_first_sector_in_short_sat);
DUMP("%d", num_sectors_in_short_sat);
DUMP("%d", secid_first_sector_in_master_sat);
DUMP("%d", num_sectors_in_master_sat);
for (i = 0; i < __arraycount(h->h_master_sat); i++) {
if (h->h_master_sat[i] == CDF_SECID_FREE)
break;
(void)fprintf(stderr, "%35.35s[%.3zu] = %d\n",
"master_sat", i, h->h_master_sat[i]);
}
}
void
cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size)
{
size_t i, j, s = size / sizeof(cdf_secid_t);
for (i = 0; i < sat->sat_len; i++) {
(void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6"
SIZE_T_FORMAT "u: ", prefix, i, i * s);
for (j = 0; j < s; j++) {
(void)fprintf(stderr, "%5d, ",
CDF_TOLE4(sat->sat_tab[s * i + j]));
if ((j + 1) % 10 == 0)
(void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT
"u: ", i * s + j + 1);
}
(void)fprintf(stderr, "\n");
}
}
void
cdf_dump(void *v, size_t len)
{
size_t i, j;
unsigned char *p = v;
char abuf[16];
(void)fprintf(stderr, "%.4x: ", 0);
for (i = 0, j = 0; i < len; i++, p++) {
(void)fprintf(stderr, "%.2x ", *p);
abuf[j++] = isprint(*p) ? *p : '.';
if (j == 16) {
j = 0;
abuf[15] = '\0';
(void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ",
abuf, i + 1);
}
}
(void)fprintf(stderr, "\n");
}
void
cdf_dump_stream(const cdf_header_t *h, const cdf_stream_t *sst)
{
size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ?
CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h);
cdf_dump(sst->sst_tab, ss * sst->sst_len);
}
void
cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h,
const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
const cdf_dir_t *dir)
{
size_t i, j;
cdf_directory_t *d;
char name[__arraycount(d->d_name)];
cdf_stream_t scn;
struct timespec ts;
static const char *types[] = { "empty", "user storage",
"user stream", "lockbytes", "property", "root storage" };
for (i = 0; i < dir->dir_len; i++) {
char buf[26];
d = &dir->dir_tab[i];
for (j = 0; j < sizeof(name); j++)
name[j] = (char)CDF_TOLE2(d->d_name[j]);
(void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n",
i, name);
if (d->d_type < __arraycount(types))
(void)fprintf(stderr, "Type: %s\n", types[d->d_type]);
else
(void)fprintf(stderr, "Type: %d\n", d->d_type);
(void)fprintf(stderr, "Color: %s\n",
d->d_color ? "black" : "red");
(void)fprintf(stderr, "Left child: %d\n", d->d_left_child);
(void)fprintf(stderr, "Right child: %d\n", d->d_right_child);
(void)fprintf(stderr, "Flags: 0x%x\n", d->d_flags);
cdf_timestamp_to_timespec(&ts, d->d_created);
(void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf));
cdf_timestamp_to_timespec(&ts, d->d_modified);
(void)fprintf(stderr, "Modified %s",
cdf_ctime(&ts.tv_sec, buf));
(void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector);
(void)fprintf(stderr, "Size %d\n", d->d_size);
switch (d->d_type) {
case CDF_DIR_TYPE_USER_STORAGE:
(void)fprintf(stderr, "Storage: %d\n", d->d_storage);
break;
case CDF_DIR_TYPE_USER_STREAM:
if (sst == NULL)
break;
if (cdf_read_sector_chain(info, h, sat, ssat, sst,
d->d_stream_first_sector, d->d_size, &scn) == -1) {
warn("Can't read stream for %s at %d len %d",
name, d->d_stream_first_sector, d->d_size);
break;
}
cdf_dump_stream(h, &scn);
free(scn.sst_tab);
break;
default:
break;
}
}
}
void
cdf_dump_property_info(const cdf_property_info_t *info, size_t count)
{
cdf_timestamp_t tp;
struct timespec ts;
char buf[64];
size_t i, j;
for (i = 0; i < count; i++) {
cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
(void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf);
switch (info[i].pi_type) {
case CDF_NULL:
break;
case CDF_SIGNED16:
(void)fprintf(stderr, "signed 16 [%hd]\n",
info[i].pi_s16);
break;
case CDF_SIGNED32:
(void)fprintf(stderr, "signed 32 [%d]\n",
info[i].pi_s32);
break;
case CDF_UNSIGNED32:
(void)fprintf(stderr, "unsigned 32 [%u]\n",
info[i].pi_u32);
break;
case CDF_FLOAT:
(void)fprintf(stderr, "float [%g]\n",
info[i].pi_f);
break;
case CDF_DOUBLE:
(void)fprintf(stderr, "double [%g]\n",
info[i].pi_d);
break;
case CDF_LENGTH32_STRING:
(void)fprintf(stderr, "string %u [%.*s]\n",
info[i].pi_str.s_len,
info[i].pi_str.s_len, info[i].pi_str.s_buf);
break;
case CDF_LENGTH32_WSTRING:
(void)fprintf(stderr, "string %u [",
info[i].pi_str.s_len);
for (j = 0; j < info[i].pi_str.s_len - 1; j++)
(void)fputc(info[i].pi_str.s_buf[j << 1], stderr);
(void)fprintf(stderr, "]\n");
break;
case CDF_FILETIME:
tp = info[i].pi_tp;
if (tp < 1000000000000000LL) {
cdf_print_elapsed_time(buf, sizeof(buf), tp);
(void)fprintf(stderr, "timestamp %s\n", buf);
} else {
char buf[26];
cdf_timestamp_to_timespec(&ts, tp);
(void)fprintf(stderr, "timestamp %s",
cdf_ctime(&ts.tv_sec, buf));
}
break;
case CDF_CLIPBOARD:
(void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32);
break;
default:
DPRINTF(("Don't know how to deal with %x\n",
info[i].pi_type));
break;
}
}
}
void
cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst)
{
char buf[128];
cdf_summary_info_header_t ssi;
cdf_property_info_t *info;
size_t count;
(void)&h;
if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1)
return;
(void)fprintf(stderr, "Endian: %x\n", ssi.si_byte_order);
(void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff,
ssi.si_os_version >> 8);
(void)fprintf(stderr, "Os %d\n", ssi.si_os);
cdf_print_classid(buf, sizeof(buf), &ssi.si_class);
(void)fprintf(stderr, "Class %s\n", buf);
(void)fprintf(stderr, "Count %d\n", ssi.si_count);
cdf_dump_property_info(info, count);
free(info);
}
#endif
#ifdef TEST
int
main(int argc, char *argv[])
{
int i;
cdf_header_t h;
cdf_sat_t sat, ssat;
cdf_stream_t sst, scn;
cdf_dir_t dir;
cdf_info_t info;
if (argc < 2) {
(void)fprintf(stderr, "Usage: %s <filename>\n", getprogname());
return -1;
}
info.i_buf = NULL;
info.i_len = 0;
for (i = 1; i < argc; i++) {
if ((info.i_fd = open(argv[1], O_RDONLY)) == -1)
err(1, "Cannot open `%s'", argv[1]);
if (cdf_read_header(&info, &h) == -1)
err(1, "Cannot read header");
#ifdef CDF_DEBUG
cdf_dump_header(&h);
#endif
if (cdf_read_sat(&info, &h, &sat) == -1)
err(1, "Cannot read sat");
#ifdef CDF_DEBUG
cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
#endif
if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1)
err(1, "Cannot read ssat");
#ifdef CDF_DEBUG
cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
#endif
if (cdf_read_dir(&info, &h, &sat, &dir) == -1)
err(1, "Cannot read dir");
if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst) == -1)
err(1, "Cannot read short stream");
#ifdef CDF_DEBUG
cdf_dump_stream(&h, &sst);
#endif
#ifdef CDF_DEBUG
cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
#endif
if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
&scn) == -1)
err(1, "Cannot read summary info");
#ifdef CDF_DEBUG
cdf_dump_summary_info(&h, &scn);
#endif
(void)close(info.i_fd);
}
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2138_0 |
crossvul-cpp_data_good_76_0 | /*
* linux/kernel/exit.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/sched/autogroup.h>
#include <linux/sched/mm.h>
#include <linux/sched/stat.h>
#include <linux/sched/task.h>
#include <linux/sched/task_stack.h>
#include <linux/sched/cputime.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/completion.h>
#include <linux/personality.h>
#include <linux/tty.h>
#include <linux/iocontext.h>
#include <linux/key.h>
#include <linux/cpu.h>
#include <linux/acct.h>
#include <linux/tsacct_kern.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/freezer.h>
#include <linux/binfmts.h>
#include <linux/nsproxy.h>
#include <linux/pid_namespace.h>
#include <linux/ptrace.h>
#include <linux/profile.h>
#include <linux/mount.h>
#include <linux/proc_fs.h>
#include <linux/kthread.h>
#include <linux/mempolicy.h>
#include <linux/taskstats_kern.h>
#include <linux/delayacct.h>
#include <linux/cgroup.h>
#include <linux/syscalls.h>
#include <linux/signal.h>
#include <linux/posix-timers.h>
#include <linux/cn_proc.h>
#include <linux/mutex.h>
#include <linux/futex.h>
#include <linux/pipe_fs_i.h>
#include <linux/audit.h> /* for audit_free() */
#include <linux/resource.h>
#include <linux/blkdev.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/tracehook.h>
#include <linux/fs_struct.h>
#include <linux/init_task.h>
#include <linux/perf_event.h>
#include <trace/events/sched.h>
#include <linux/hw_breakpoint.h>
#include <linux/oom.h>
#include <linux/writeback.h>
#include <linux/shm.h>
#include <linux/kcov.h>
#include <linux/random.h>
#include <linux/rcuwait.h>
#include <linux/compat.h>
#include <linux/uaccess.h>
#include <asm/unistd.h>
#include <asm/pgtable.h>
#include <asm/mmu_context.h>
static void __unhash_process(struct task_struct *p, bool group_dead)
{
nr_threads--;
detach_pid(p, PIDTYPE_PID);
if (group_dead) {
detach_pid(p, PIDTYPE_PGID);
detach_pid(p, PIDTYPE_SID);
list_del_rcu(&p->tasks);
list_del_init(&p->sibling);
__this_cpu_dec(process_counts);
}
list_del_rcu(&p->thread_group);
list_del_rcu(&p->thread_node);
}
/*
* This function expects the tasklist_lock write-locked.
*/
static void __exit_signal(struct task_struct *tsk)
{
struct signal_struct *sig = tsk->signal;
bool group_dead = thread_group_leader(tsk);
struct sighand_struct *sighand;
struct tty_struct *uninitialized_var(tty);
u64 utime, stime;
sighand = rcu_dereference_check(tsk->sighand,
lockdep_tasklist_lock_is_held());
spin_lock(&sighand->siglock);
#ifdef CONFIG_POSIX_TIMERS
posix_cpu_timers_exit(tsk);
if (group_dead) {
posix_cpu_timers_exit_group(tsk);
} else {
/*
* This can only happen if the caller is de_thread().
* FIXME: this is the temporary hack, we should teach
* posix-cpu-timers to handle this case correctly.
*/
if (unlikely(has_group_leader_pid(tsk)))
posix_cpu_timers_exit_group(tsk);
}
#endif
if (group_dead) {
tty = sig->tty;
sig->tty = NULL;
} else {
/*
* If there is any task waiting for the group exit
* then notify it:
*/
if (sig->notify_count > 0 && !--sig->notify_count)
wake_up_process(sig->group_exit_task);
if (tsk == sig->curr_target)
sig->curr_target = next_thread(tsk);
}
add_device_randomness((const void*) &tsk->se.sum_exec_runtime,
sizeof(unsigned long long));
/*
* Accumulate here the counters for all threads as they die. We could
* skip the group leader because it is the last user of signal_struct,
* but we want to avoid the race with thread_group_cputime() which can
* see the empty ->thread_head list.
*/
task_cputime(tsk, &utime, &stime);
write_seqlock(&sig->stats_lock);
sig->utime += utime;
sig->stime += stime;
sig->gtime += task_gtime(tsk);
sig->min_flt += tsk->min_flt;
sig->maj_flt += tsk->maj_flt;
sig->nvcsw += tsk->nvcsw;
sig->nivcsw += tsk->nivcsw;
sig->inblock += task_io_get_inblock(tsk);
sig->oublock += task_io_get_oublock(tsk);
task_io_accounting_add(&sig->ioac, &tsk->ioac);
sig->sum_sched_runtime += tsk->se.sum_exec_runtime;
sig->nr_threads--;
__unhash_process(tsk, group_dead);
write_sequnlock(&sig->stats_lock);
/*
* Do this under ->siglock, we can race with another thread
* doing sigqueue_free() if we have SIGQUEUE_PREALLOC signals.
*/
flush_sigqueue(&tsk->pending);
tsk->sighand = NULL;
spin_unlock(&sighand->siglock);
__cleanup_sighand(sighand);
clear_tsk_thread_flag(tsk, TIF_SIGPENDING);
if (group_dead) {
flush_sigqueue(&sig->shared_pending);
tty_kref_put(tty);
}
}
static void delayed_put_task_struct(struct rcu_head *rhp)
{
struct task_struct *tsk = container_of(rhp, struct task_struct, rcu);
perf_event_delayed_put(tsk);
trace_sched_process_free(tsk);
put_task_struct(tsk);
}
void release_task(struct task_struct *p)
{
struct task_struct *leader;
int zap_leader;
repeat:
/* don't need to get the RCU readlock here - the process is dead and
* can't be modifying its own credentials. But shut RCU-lockdep up */
rcu_read_lock();
atomic_dec(&__task_cred(p)->user->processes);
rcu_read_unlock();
proc_flush_task(p);
write_lock_irq(&tasklist_lock);
ptrace_release_task(p);
__exit_signal(p);
/*
* If we are the last non-leader member of the thread
* group, and the leader is zombie, then notify the
* group leader's parent process. (if it wants notification.)
*/
zap_leader = 0;
leader = p->group_leader;
if (leader != p && thread_group_empty(leader)
&& leader->exit_state == EXIT_ZOMBIE) {
/*
* If we were the last child thread and the leader has
* exited already, and the leader's parent ignores SIGCHLD,
* then we are the one who should release the leader.
*/
zap_leader = do_notify_parent(leader, leader->exit_signal);
if (zap_leader)
leader->exit_state = EXIT_DEAD;
}
write_unlock_irq(&tasklist_lock);
release_thread(p);
call_rcu(&p->rcu, delayed_put_task_struct);
p = leader;
if (unlikely(zap_leader))
goto repeat;
}
/*
* Note that if this function returns a valid task_struct pointer (!NULL)
* task->usage must remain >0 for the duration of the RCU critical section.
*/
struct task_struct *task_rcu_dereference(struct task_struct **ptask)
{
struct sighand_struct *sighand;
struct task_struct *task;
/*
* We need to verify that release_task() was not called and thus
* delayed_put_task_struct() can't run and drop the last reference
* before rcu_read_unlock(). We check task->sighand != NULL,
* but we can read the already freed and reused memory.
*/
retry:
task = rcu_dereference(*ptask);
if (!task)
return NULL;
probe_kernel_address(&task->sighand, sighand);
/*
* Pairs with atomic_dec_and_test() in put_task_struct(). If this task
* was already freed we can not miss the preceding update of this
* pointer.
*/
smp_rmb();
if (unlikely(task != READ_ONCE(*ptask)))
goto retry;
/*
* We've re-checked that "task == *ptask", now we have two different
* cases:
*
* 1. This is actually the same task/task_struct. In this case
* sighand != NULL tells us it is still alive.
*
* 2. This is another task which got the same memory for task_struct.
* We can't know this of course, and we can not trust
* sighand != NULL.
*
* In this case we actually return a random value, but this is
* correct.
*
* If we return NULL - we can pretend that we actually noticed that
* *ptask was updated when the previous task has exited. Or pretend
* that probe_slab_address(&sighand) reads NULL.
*
* If we return the new task (because sighand is not NULL for any
* reason) - this is fine too. This (new) task can't go away before
* another gp pass.
*
* And note: We could even eliminate the false positive if re-read
* task->sighand once again to avoid the falsely NULL. But this case
* is very unlikely so we don't care.
*/
if (!sighand)
return NULL;
return task;
}
void rcuwait_wake_up(struct rcuwait *w)
{
struct task_struct *task;
rcu_read_lock();
/*
* Order condition vs @task, such that everything prior to the load
* of @task is visible. This is the condition as to why the user called
* rcuwait_trywake() in the first place. Pairs with set_current_state()
* barrier (A) in rcuwait_wait_event().
*
* WAIT WAKE
* [S] tsk = current [S] cond = true
* MB (A) MB (B)
* [L] cond [L] tsk
*/
smp_rmb(); /* (B) */
/*
* Avoid using task_rcu_dereference() magic as long as we are careful,
* see comment in rcuwait_wait_event() regarding ->exit_state.
*/
task = rcu_dereference(w->task);
if (task)
wake_up_process(task);
rcu_read_unlock();
}
/*
* Determine if a process group is "orphaned", according to the POSIX
* definition in 2.2.2.52. Orphaned process groups are not to be affected
* by terminal-generated stop signals. Newly orphaned process groups are
* to receive a SIGHUP and a SIGCONT.
*
* "I ask you, have you ever known what it is to be an orphan?"
*/
static int will_become_orphaned_pgrp(struct pid *pgrp,
struct task_struct *ignored_task)
{
struct task_struct *p;
do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
if ((p == ignored_task) ||
(p->exit_state && thread_group_empty(p)) ||
is_global_init(p->real_parent))
continue;
if (task_pgrp(p->real_parent) != pgrp &&
task_session(p->real_parent) == task_session(p))
return 0;
} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
return 1;
}
int is_current_pgrp_orphaned(void)
{
int retval;
read_lock(&tasklist_lock);
retval = will_become_orphaned_pgrp(task_pgrp(current), NULL);
read_unlock(&tasklist_lock);
return retval;
}
static bool has_stopped_jobs(struct pid *pgrp)
{
struct task_struct *p;
do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
if (p->signal->flags & SIGNAL_STOP_STOPPED)
return true;
} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
return false;
}
/*
* Check to see if any process groups have become orphaned as
* a result of our exiting, and if they have any stopped jobs,
* send them a SIGHUP and then a SIGCONT. (POSIX 3.2.2.2)
*/
static void
kill_orphaned_pgrp(struct task_struct *tsk, struct task_struct *parent)
{
struct pid *pgrp = task_pgrp(tsk);
struct task_struct *ignored_task = tsk;
if (!parent)
/* exit: our father is in a different pgrp than
* we are and we were the only connection outside.
*/
parent = tsk->real_parent;
else
/* reparent: our child is in a different pgrp than
* we are, and it was the only connection outside.
*/
ignored_task = NULL;
if (task_pgrp(parent) != pgrp &&
task_session(parent) == task_session(tsk) &&
will_become_orphaned_pgrp(pgrp, ignored_task) &&
has_stopped_jobs(pgrp)) {
__kill_pgrp_info(SIGHUP, SEND_SIG_PRIV, pgrp);
__kill_pgrp_info(SIGCONT, SEND_SIG_PRIV, pgrp);
}
}
#ifdef CONFIG_MEMCG
/*
* A task is exiting. If it owned this mm, find a new owner for the mm.
*/
void mm_update_next_owner(struct mm_struct *mm)
{
struct task_struct *c, *g, *p = current;
retry:
/*
* If the exiting or execing task is not the owner, it's
* someone else's problem.
*/
if (mm->owner != p)
return;
/*
* The current owner is exiting/execing and there are no other
* candidates. Do not leave the mm pointing to a possibly
* freed task structure.
*/
if (atomic_read(&mm->mm_users) <= 1) {
mm->owner = NULL;
return;
}
read_lock(&tasklist_lock);
/*
* Search in the children
*/
list_for_each_entry(c, &p->children, sibling) {
if (c->mm == mm)
goto assign_new_owner;
}
/*
* Search in the siblings
*/
list_for_each_entry(c, &p->real_parent->children, sibling) {
if (c->mm == mm)
goto assign_new_owner;
}
/*
* Search through everything else, we should not get here often.
*/
for_each_process(g) {
if (g->flags & PF_KTHREAD)
continue;
for_each_thread(g, c) {
if (c->mm == mm)
goto assign_new_owner;
if (c->mm)
break;
}
}
read_unlock(&tasklist_lock);
/*
* We found no owner yet mm_users > 1: this implies that we are
* most likely racing with swapoff (try_to_unuse()) or /proc or
* ptrace or page migration (get_task_mm()). Mark owner as NULL.
*/
mm->owner = NULL;
return;
assign_new_owner:
BUG_ON(c == p);
get_task_struct(c);
/*
* The task_lock protects c->mm from changing.
* We always want mm->owner->mm == mm
*/
task_lock(c);
/*
* Delay read_unlock() till we have the task_lock()
* to ensure that c does not slip away underneath us
*/
read_unlock(&tasklist_lock);
if (c->mm != mm) {
task_unlock(c);
put_task_struct(c);
goto retry;
}
mm->owner = c;
task_unlock(c);
put_task_struct(c);
}
#endif /* CONFIG_MEMCG */
/*
* Turn us into a lazy TLB process if we
* aren't already..
*/
static void exit_mm(void)
{
struct mm_struct *mm = current->mm;
struct core_state *core_state;
mm_release(current, mm);
if (!mm)
return;
sync_mm_rss(mm);
/*
* Serialize with any possible pending coredump.
* We must hold mmap_sem around checking core_state
* and clearing tsk->mm. The core-inducing thread
* will increment ->nr_threads for each thread in the
* group with ->mm != NULL.
*/
down_read(&mm->mmap_sem);
core_state = mm->core_state;
if (core_state) {
struct core_thread self;
up_read(&mm->mmap_sem);
self.task = current;
self.next = xchg(&core_state->dumper.next, &self);
/*
* Implies mb(), the result of xchg() must be visible
* to core_state->dumper.
*/
if (atomic_dec_and_test(&core_state->nr_threads))
complete(&core_state->startup);
for (;;) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (!self.task) /* see coredump_finish() */
break;
freezable_schedule();
}
__set_current_state(TASK_RUNNING);
down_read(&mm->mmap_sem);
}
mmgrab(mm);
BUG_ON(mm != current->active_mm);
/* more a memory barrier than a real lock */
task_lock(current);
current->mm = NULL;
up_read(&mm->mmap_sem);
enter_lazy_tlb(mm, current);
task_unlock(current);
mm_update_next_owner(mm);
mmput(mm);
if (test_thread_flag(TIF_MEMDIE))
exit_oom_victim();
}
static struct task_struct *find_alive_thread(struct task_struct *p)
{
struct task_struct *t;
for_each_thread(p, t) {
if (!(t->flags & PF_EXITING))
return t;
}
return NULL;
}
static struct task_struct *find_child_reaper(struct task_struct *father)
__releases(&tasklist_lock)
__acquires(&tasklist_lock)
{
struct pid_namespace *pid_ns = task_active_pid_ns(father);
struct task_struct *reaper = pid_ns->child_reaper;
if (likely(reaper != father))
return reaper;
reaper = find_alive_thread(father);
if (reaper) {
pid_ns->child_reaper = reaper;
return reaper;
}
write_unlock_irq(&tasklist_lock);
if (unlikely(pid_ns == &init_pid_ns)) {
panic("Attempted to kill init! exitcode=0x%08x\n",
father->signal->group_exit_code ?: father->exit_code);
}
zap_pid_ns_processes(pid_ns);
write_lock_irq(&tasklist_lock);
return father;
}
/*
* When we die, we re-parent all our children, and try to:
* 1. give them to another thread in our thread group, if such a member exists
* 2. give it to the first ancestor process which prctl'd itself as a
* child_subreaper for its children (like a service manager)
* 3. give it to the init process (PID 1) in our pid namespace
*/
static struct task_struct *find_new_reaper(struct task_struct *father,
struct task_struct *child_reaper)
{
struct task_struct *thread, *reaper;
thread = find_alive_thread(father);
if (thread)
return thread;
if (father->signal->has_child_subreaper) {
unsigned int ns_level = task_pid(father)->level;
/*
* Find the first ->is_child_subreaper ancestor in our pid_ns.
* We can't check reaper != child_reaper to ensure we do not
* cross the namespaces, the exiting parent could be injected
* by setns() + fork().
* We check pid->level, this is slightly more efficient than
* task_active_pid_ns(reaper) != task_active_pid_ns(father).
*/
for (reaper = father->real_parent;
task_pid(reaper)->level == ns_level;
reaper = reaper->real_parent) {
if (reaper == &init_task)
break;
if (!reaper->signal->is_child_subreaper)
continue;
thread = find_alive_thread(reaper);
if (thread)
return thread;
}
}
return child_reaper;
}
/*
* Any that need to be release_task'd are put on the @dead list.
*/
static void reparent_leader(struct task_struct *father, struct task_struct *p,
struct list_head *dead)
{
if (unlikely(p->exit_state == EXIT_DEAD))
return;
/* We don't want people slaying init. */
p->exit_signal = SIGCHLD;
/* If it has exited notify the new parent about this child's death. */
if (!p->ptrace &&
p->exit_state == EXIT_ZOMBIE && thread_group_empty(p)) {
if (do_notify_parent(p, p->exit_signal)) {
p->exit_state = EXIT_DEAD;
list_add(&p->ptrace_entry, dead);
}
}
kill_orphaned_pgrp(p, father);
}
/*
* This does two things:
*
* A. Make init inherit all the child processes
* B. Check to see if any process groups have become orphaned
* as a result of our exiting, and if they have any stopped
* jobs, send them a SIGHUP and then a SIGCONT. (POSIX 3.2.2.2)
*/
static void forget_original_parent(struct task_struct *father,
struct list_head *dead)
{
struct task_struct *p, *t, *reaper;
if (unlikely(!list_empty(&father->ptraced)))
exit_ptrace(father, dead);
/* Can drop and reacquire tasklist_lock */
reaper = find_child_reaper(father);
if (list_empty(&father->children))
return;
reaper = find_new_reaper(father, reaper);
list_for_each_entry(p, &father->children, sibling) {
for_each_thread(p, t) {
t->real_parent = reaper;
BUG_ON((!t->ptrace) != (t->parent == father));
if (likely(!t->ptrace))
t->parent = t->real_parent;
if (t->pdeath_signal)
group_send_sig_info(t->pdeath_signal,
SEND_SIG_NOINFO, t);
}
/*
* If this is a threaded reparent there is no need to
* notify anyone anything has happened.
*/
if (!same_thread_group(reaper, father))
reparent_leader(father, p, dead);
}
list_splice_tail_init(&father->children, &reaper->children);
}
/*
* Send signals to all our closest relatives so that they know
* to properly mourn us..
*/
static void exit_notify(struct task_struct *tsk, int group_dead)
{
bool autoreap;
struct task_struct *p, *n;
LIST_HEAD(dead);
write_lock_irq(&tasklist_lock);
forget_original_parent(tsk, &dead);
if (group_dead)
kill_orphaned_pgrp(tsk->group_leader, NULL);
if (unlikely(tsk->ptrace)) {
int sig = thread_group_leader(tsk) &&
thread_group_empty(tsk) &&
!ptrace_reparented(tsk) ?
tsk->exit_signal : SIGCHLD;
autoreap = do_notify_parent(tsk, sig);
} else if (thread_group_leader(tsk)) {
autoreap = thread_group_empty(tsk) &&
do_notify_parent(tsk, tsk->exit_signal);
} else {
autoreap = true;
}
tsk->exit_state = autoreap ? EXIT_DEAD : EXIT_ZOMBIE;
if (tsk->exit_state == EXIT_DEAD)
list_add(&tsk->ptrace_entry, &dead);
/* mt-exec, de_thread() is waiting for group leader */
if (unlikely(tsk->signal->notify_count < 0))
wake_up_process(tsk->signal->group_exit_task);
write_unlock_irq(&tasklist_lock);
list_for_each_entry_safe(p, n, &dead, ptrace_entry) {
list_del_init(&p->ptrace_entry);
release_task(p);
}
}
#ifdef CONFIG_DEBUG_STACK_USAGE
static void check_stack_usage(void)
{
static DEFINE_SPINLOCK(low_water_lock);
static int lowest_to_date = THREAD_SIZE;
unsigned long free;
free = stack_not_used(current);
if (free >= lowest_to_date)
return;
spin_lock(&low_water_lock);
if (free < lowest_to_date) {
pr_info("%s (%d) used greatest stack depth: %lu bytes left\n",
current->comm, task_pid_nr(current), free);
lowest_to_date = free;
}
spin_unlock(&low_water_lock);
}
#else
static inline void check_stack_usage(void) {}
#endif
void __noreturn do_exit(long code)
{
struct task_struct *tsk = current;
int group_dead;
TASKS_RCU(int tasks_rcu_i);
profile_task_exit(tsk);
kcov_task_exit(tsk);
WARN_ON(blk_needs_flush_plug(tsk));
if (unlikely(in_interrupt()))
panic("Aiee, killing interrupt handler!");
if (unlikely(!tsk->pid))
panic("Attempted to kill the idle task!");
/*
* If do_exit is called because this processes oopsed, it's possible
* that get_fs() was left as KERNEL_DS, so reset it to USER_DS before
* continuing. Amongst other possible reasons, this is to prevent
* mm_release()->clear_child_tid() from writing to a user-controlled
* kernel address.
*/
set_fs(USER_DS);
ptrace_event(PTRACE_EVENT_EXIT, code);
validate_creds_for_do_exit(tsk);
/*
* We're taking recursive faults here in do_exit. Safest is to just
* leave this task alone and wait for reboot.
*/
if (unlikely(tsk->flags & PF_EXITING)) {
pr_alert("Fixing recursive fault but reboot is needed!\n");
/*
* We can do this unlocked here. The futex code uses
* this flag just to verify whether the pi state
* cleanup has been done or not. In the worst case it
* loops once more. We pretend that the cleanup was
* done as there is no way to return. Either the
* OWNER_DIED bit is set by now or we push the blocked
* task into the wait for ever nirwana as well.
*/
tsk->flags |= PF_EXITPIDONE;
set_current_state(TASK_UNINTERRUPTIBLE);
schedule();
}
exit_signals(tsk); /* sets PF_EXITING */
/*
* Ensure that all new tsk->pi_lock acquisitions must observe
* PF_EXITING. Serializes against futex.c:attach_to_pi_owner().
*/
smp_mb();
/*
* Ensure that we must observe the pi_state in exit_mm() ->
* mm_release() -> exit_pi_state_list().
*/
raw_spin_unlock_wait(&tsk->pi_lock);
if (unlikely(in_atomic())) {
pr_info("note: %s[%d] exited with preempt_count %d\n",
current->comm, task_pid_nr(current),
preempt_count());
preempt_count_set(PREEMPT_ENABLED);
}
/* sync mm's RSS info before statistics gathering */
if (tsk->mm)
sync_mm_rss(tsk->mm);
acct_update_integrals(tsk);
group_dead = atomic_dec_and_test(&tsk->signal->live);
if (group_dead) {
#ifdef CONFIG_POSIX_TIMERS
hrtimer_cancel(&tsk->signal->real_timer);
exit_itimers(tsk->signal);
#endif
if (tsk->mm)
setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm);
}
acct_collect(code, group_dead);
if (group_dead)
tty_audit_exit();
audit_free(tsk);
tsk->exit_code = code;
taskstats_exit(tsk, group_dead);
exit_mm();
if (group_dead)
acct_process();
trace_sched_process_exit(tsk);
exit_sem(tsk);
exit_shm(tsk);
exit_files(tsk);
exit_fs(tsk);
if (group_dead)
disassociate_ctty(1);
exit_task_namespaces(tsk);
exit_task_work(tsk);
exit_thread(tsk);
/*
* Flush inherited counters to the parent - before the parent
* gets woken up by child-exit notifications.
*
* because of cgroup mode, must be called before cgroup_exit()
*/
perf_event_exit_task(tsk);
sched_autogroup_exit_task(tsk);
cgroup_exit(tsk);
/*
* FIXME: do that only when needed, using sched_exit tracepoint
*/
flush_ptrace_hw_breakpoint(tsk);
TASKS_RCU(preempt_disable());
TASKS_RCU(tasks_rcu_i = __srcu_read_lock(&tasks_rcu_exit_srcu));
TASKS_RCU(preempt_enable());
exit_notify(tsk, group_dead);
proc_exit_connector(tsk);
mpol_put_task_policy(tsk);
#ifdef CONFIG_FUTEX
if (unlikely(current->pi_state_cache))
kfree(current->pi_state_cache);
#endif
/*
* Make sure we are holding no locks:
*/
debug_check_no_locks_held();
/*
* We can do this unlocked here. The futex code uses this flag
* just to verify whether the pi state cleanup has been done
* or not. In the worst case it loops once more.
*/
tsk->flags |= PF_EXITPIDONE;
if (tsk->io_context)
exit_io_context(tsk);
if (tsk->splice_pipe)
free_pipe_info(tsk->splice_pipe);
if (tsk->task_frag.page)
put_page(tsk->task_frag.page);
validate_creds_for_do_exit(tsk);
check_stack_usage();
preempt_disable();
if (tsk->nr_dirtied)
__this_cpu_add(dirty_throttle_leaks, tsk->nr_dirtied);
exit_rcu();
TASKS_RCU(__srcu_read_unlock(&tasks_rcu_exit_srcu, tasks_rcu_i));
do_task_dead();
}
EXPORT_SYMBOL_GPL(do_exit);
void complete_and_exit(struct completion *comp, long code)
{
if (comp)
complete(comp);
do_exit(code);
}
EXPORT_SYMBOL(complete_and_exit);
SYSCALL_DEFINE1(exit, int, error_code)
{
do_exit((error_code&0xff)<<8);
}
/*
* Take down every thread in the group. This is called by fatal signals
* as well as by sys_exit_group (below).
*/
void
do_group_exit(int exit_code)
{
struct signal_struct *sig = current->signal;
BUG_ON(exit_code & 0x80); /* core dumps don't get here */
if (signal_group_exit(sig))
exit_code = sig->group_exit_code;
else if (!thread_group_empty(current)) {
struct sighand_struct *const sighand = current->sighand;
spin_lock_irq(&sighand->siglock);
if (signal_group_exit(sig))
/* Another thread got here before we took the lock. */
exit_code = sig->group_exit_code;
else {
sig->group_exit_code = exit_code;
sig->flags = SIGNAL_GROUP_EXIT;
zap_other_threads(current);
}
spin_unlock_irq(&sighand->siglock);
}
do_exit(exit_code);
/* NOTREACHED */
}
/*
* this kills every thread in the thread group. Note that any externally
* wait4()-ing process will get the correct exit code - even if this
* thread is not the thread group leader.
*/
SYSCALL_DEFINE1(exit_group, int, error_code)
{
do_group_exit((error_code & 0xff) << 8);
/* NOTREACHED */
return 0;
}
struct waitid_info {
pid_t pid;
uid_t uid;
int status;
int cause;
};
struct wait_opts {
enum pid_type wo_type;
int wo_flags;
struct pid *wo_pid;
struct waitid_info *wo_info;
int wo_stat;
struct rusage *wo_rusage;
wait_queue_entry_t child_wait;
int notask_error;
};
static inline
struct pid *task_pid_type(struct task_struct *task, enum pid_type type)
{
if (type != PIDTYPE_PID)
task = task->group_leader;
return task->pids[type].pid;
}
static int eligible_pid(struct wait_opts *wo, struct task_struct *p)
{
return wo->wo_type == PIDTYPE_MAX ||
task_pid_type(p, wo->wo_type) == wo->wo_pid;
}
static int
eligible_child(struct wait_opts *wo, bool ptrace, struct task_struct *p)
{
if (!eligible_pid(wo, p))
return 0;
/*
* Wait for all children (clone and not) if __WALL is set or
* if it is traced by us.
*/
if (ptrace || (wo->wo_flags & __WALL))
return 1;
/*
* Otherwise, wait for clone children *only* if __WCLONE is set;
* otherwise, wait for non-clone children *only*.
*
* Note: a "clone" child here is one that reports to its parent
* using a signal other than SIGCHLD, or a non-leader thread which
* we can only see if it is traced by us.
*/
if ((p->exit_signal != SIGCHLD) ^ !!(wo->wo_flags & __WCLONE))
return 0;
return 1;
}
/*
* Handle sys_wait4 work for one task in state EXIT_ZOMBIE. We hold
* read_lock(&tasklist_lock) on entry. If we return zero, we still hold
* the lock and this task is uninteresting. If we return nonzero, we have
* released the lock and the system call should return.
*/
static int wait_task_zombie(struct wait_opts *wo, struct task_struct *p)
{
int state, status;
pid_t pid = task_pid_vnr(p);
uid_t uid = from_kuid_munged(current_user_ns(), task_uid(p));
struct waitid_info *infop;
if (!likely(wo->wo_flags & WEXITED))
return 0;
if (unlikely(wo->wo_flags & WNOWAIT)) {
status = p->exit_code;
get_task_struct(p);
read_unlock(&tasklist_lock);
sched_annotate_sleep();
if (wo->wo_rusage)
getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
put_task_struct(p);
goto out_info;
}
/*
* Move the task's state to DEAD/TRACE, only one thread can do this.
*/
state = (ptrace_reparented(p) && thread_group_leader(p)) ?
EXIT_TRACE : EXIT_DEAD;
if (cmpxchg(&p->exit_state, EXIT_ZOMBIE, state) != EXIT_ZOMBIE)
return 0;
/*
* We own this thread, nobody else can reap it.
*/
read_unlock(&tasklist_lock);
sched_annotate_sleep();
/*
* Check thread_group_leader() to exclude the traced sub-threads.
*/
if (state == EXIT_DEAD && thread_group_leader(p)) {
struct signal_struct *sig = p->signal;
struct signal_struct *psig = current->signal;
unsigned long maxrss;
u64 tgutime, tgstime;
/*
* The resource counters for the group leader are in its
* own task_struct. Those for dead threads in the group
* are in its signal_struct, as are those for the child
* processes it has previously reaped. All these
* accumulate in the parent's signal_struct c* fields.
*
* We don't bother to take a lock here to protect these
* p->signal fields because the whole thread group is dead
* and nobody can change them.
*
* psig->stats_lock also protects us from our sub-theads
* which can reap other children at the same time. Until
* we change k_getrusage()-like users to rely on this lock
* we have to take ->siglock as well.
*
* We use thread_group_cputime_adjusted() to get times for
* the thread group, which consolidates times for all threads
* in the group including the group leader.
*/
thread_group_cputime_adjusted(p, &tgutime, &tgstime);
spin_lock_irq(¤t->sighand->siglock);
write_seqlock(&psig->stats_lock);
psig->cutime += tgutime + sig->cutime;
psig->cstime += tgstime + sig->cstime;
psig->cgtime += task_gtime(p) + sig->gtime + sig->cgtime;
psig->cmin_flt +=
p->min_flt + sig->min_flt + sig->cmin_flt;
psig->cmaj_flt +=
p->maj_flt + sig->maj_flt + sig->cmaj_flt;
psig->cnvcsw +=
p->nvcsw + sig->nvcsw + sig->cnvcsw;
psig->cnivcsw +=
p->nivcsw + sig->nivcsw + sig->cnivcsw;
psig->cinblock +=
task_io_get_inblock(p) +
sig->inblock + sig->cinblock;
psig->coublock +=
task_io_get_oublock(p) +
sig->oublock + sig->coublock;
maxrss = max(sig->maxrss, sig->cmaxrss);
if (psig->cmaxrss < maxrss)
psig->cmaxrss = maxrss;
task_io_accounting_add(&psig->ioac, &p->ioac);
task_io_accounting_add(&psig->ioac, &sig->ioac);
write_sequnlock(&psig->stats_lock);
spin_unlock_irq(¤t->sighand->siglock);
}
if (wo->wo_rusage)
getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
status = (p->signal->flags & SIGNAL_GROUP_EXIT)
? p->signal->group_exit_code : p->exit_code;
wo->wo_stat = status;
if (state == EXIT_TRACE) {
write_lock_irq(&tasklist_lock);
/* We dropped tasklist, ptracer could die and untrace */
ptrace_unlink(p);
/* If parent wants a zombie, don't release it now */
state = EXIT_ZOMBIE;
if (do_notify_parent(p, p->exit_signal))
state = EXIT_DEAD;
p->exit_state = state;
write_unlock_irq(&tasklist_lock);
}
if (state == EXIT_DEAD)
release_task(p);
out_info:
infop = wo->wo_info;
if (infop) {
if ((status & 0x7f) == 0) {
infop->cause = CLD_EXITED;
infop->status = status >> 8;
} else {
infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED;
infop->status = status & 0x7f;
}
infop->pid = pid;
infop->uid = uid;
}
return pid;
}
static int *task_stopped_code(struct task_struct *p, bool ptrace)
{
if (ptrace) {
if (task_is_traced(p) && !(p->jobctl & JOBCTL_LISTENING))
return &p->exit_code;
} else {
if (p->signal->flags & SIGNAL_STOP_STOPPED)
return &p->signal->group_exit_code;
}
return NULL;
}
/**
* wait_task_stopped - Wait for %TASK_STOPPED or %TASK_TRACED
* @wo: wait options
* @ptrace: is the wait for ptrace
* @p: task to wait for
*
* Handle sys_wait4() work for %p in state %TASK_STOPPED or %TASK_TRACED.
*
* CONTEXT:
* read_lock(&tasklist_lock), which is released if return value is
* non-zero. Also, grabs and releases @p->sighand->siglock.
*
* RETURNS:
* 0 if wait condition didn't exist and search for other wait conditions
* should continue. Non-zero return, -errno on failure and @p's pid on
* success, implies that tasklist_lock is released and wait condition
* search should terminate.
*/
static int wait_task_stopped(struct wait_opts *wo,
int ptrace, struct task_struct *p)
{
struct waitid_info *infop;
int exit_code, *p_code, why;
uid_t uid = 0; /* unneeded, required by compiler */
pid_t pid;
/*
* Traditionally we see ptrace'd stopped tasks regardless of options.
*/
if (!ptrace && !(wo->wo_flags & WUNTRACED))
return 0;
if (!task_stopped_code(p, ptrace))
return 0;
exit_code = 0;
spin_lock_irq(&p->sighand->siglock);
p_code = task_stopped_code(p, ptrace);
if (unlikely(!p_code))
goto unlock_sig;
exit_code = *p_code;
if (!exit_code)
goto unlock_sig;
if (!unlikely(wo->wo_flags & WNOWAIT))
*p_code = 0;
uid = from_kuid_munged(current_user_ns(), task_uid(p));
unlock_sig:
spin_unlock_irq(&p->sighand->siglock);
if (!exit_code)
return 0;
/*
* Now we are pretty sure this task is interesting.
* Make sure it doesn't get reaped out from under us while we
* give up the lock and then examine it below. We don't want to
* keep holding onto the tasklist_lock while we call getrusage and
* possibly take page faults for user memory.
*/
get_task_struct(p);
pid = task_pid_vnr(p);
why = ptrace ? CLD_TRAPPED : CLD_STOPPED;
read_unlock(&tasklist_lock);
sched_annotate_sleep();
if (wo->wo_rusage)
getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
put_task_struct(p);
if (likely(!(wo->wo_flags & WNOWAIT)))
wo->wo_stat = (exit_code << 8) | 0x7f;
infop = wo->wo_info;
if (infop) {
infop->cause = why;
infop->status = exit_code;
infop->pid = pid;
infop->uid = uid;
}
return pid;
}
/*
* Handle do_wait work for one task in a live, non-stopped state.
* read_lock(&tasklist_lock) on entry. If we return zero, we still hold
* the lock and this task is uninteresting. If we return nonzero, we have
* released the lock and the system call should return.
*/
static int wait_task_continued(struct wait_opts *wo, struct task_struct *p)
{
struct waitid_info *infop;
pid_t pid;
uid_t uid;
if (!unlikely(wo->wo_flags & WCONTINUED))
return 0;
if (!(p->signal->flags & SIGNAL_STOP_CONTINUED))
return 0;
spin_lock_irq(&p->sighand->siglock);
/* Re-check with the lock held. */
if (!(p->signal->flags & SIGNAL_STOP_CONTINUED)) {
spin_unlock_irq(&p->sighand->siglock);
return 0;
}
if (!unlikely(wo->wo_flags & WNOWAIT))
p->signal->flags &= ~SIGNAL_STOP_CONTINUED;
uid = from_kuid_munged(current_user_ns(), task_uid(p));
spin_unlock_irq(&p->sighand->siglock);
pid = task_pid_vnr(p);
get_task_struct(p);
read_unlock(&tasklist_lock);
sched_annotate_sleep();
if (wo->wo_rusage)
getrusage(p, RUSAGE_BOTH, wo->wo_rusage);
put_task_struct(p);
infop = wo->wo_info;
if (!infop) {
wo->wo_stat = 0xffff;
} else {
infop->cause = CLD_CONTINUED;
infop->pid = pid;
infop->uid = uid;
infop->status = SIGCONT;
}
return pid;
}
/*
* Consider @p for a wait by @parent.
*
* -ECHILD should be in ->notask_error before the first call.
* Returns nonzero for a final return, when we have unlocked tasklist_lock.
* Returns zero if the search for a child should continue;
* then ->notask_error is 0 if @p is an eligible child,
* or still -ECHILD.
*/
static int wait_consider_task(struct wait_opts *wo, int ptrace,
struct task_struct *p)
{
/*
* We can race with wait_task_zombie() from another thread.
* Ensure that EXIT_ZOMBIE -> EXIT_DEAD/EXIT_TRACE transition
* can't confuse the checks below.
*/
int exit_state = ACCESS_ONCE(p->exit_state);
int ret;
if (unlikely(exit_state == EXIT_DEAD))
return 0;
ret = eligible_child(wo, ptrace, p);
if (!ret)
return ret;
if (unlikely(exit_state == EXIT_TRACE)) {
/*
* ptrace == 0 means we are the natural parent. In this case
* we should clear notask_error, debugger will notify us.
*/
if (likely(!ptrace))
wo->notask_error = 0;
return 0;
}
if (likely(!ptrace) && unlikely(p->ptrace)) {
/*
* If it is traced by its real parent's group, just pretend
* the caller is ptrace_do_wait() and reap this child if it
* is zombie.
*
* This also hides group stop state from real parent; otherwise
* a single stop can be reported twice as group and ptrace stop.
* If a ptracer wants to distinguish these two events for its
* own children it should create a separate process which takes
* the role of real parent.
*/
if (!ptrace_reparented(p))
ptrace = 1;
}
/* slay zombie? */
if (exit_state == EXIT_ZOMBIE) {
/* we don't reap group leaders with subthreads */
if (!delay_group_leader(p)) {
/*
* A zombie ptracee is only visible to its ptracer.
* Notification and reaping will be cascaded to the
* real parent when the ptracer detaches.
*/
if (unlikely(ptrace) || likely(!p->ptrace))
return wait_task_zombie(wo, p);
}
/*
* Allow access to stopped/continued state via zombie by
* falling through. Clearing of notask_error is complex.
*
* When !@ptrace:
*
* If WEXITED is set, notask_error should naturally be
* cleared. If not, subset of WSTOPPED|WCONTINUED is set,
* so, if there are live subthreads, there are events to
* wait for. If all subthreads are dead, it's still safe
* to clear - this function will be called again in finite
* amount time once all the subthreads are released and
* will then return without clearing.
*
* When @ptrace:
*
* Stopped state is per-task and thus can't change once the
* target task dies. Only continued and exited can happen.
* Clear notask_error if WCONTINUED | WEXITED.
*/
if (likely(!ptrace) || (wo->wo_flags & (WCONTINUED | WEXITED)))
wo->notask_error = 0;
} else {
/*
* @p is alive and it's gonna stop, continue or exit, so
* there always is something to wait for.
*/
wo->notask_error = 0;
}
/*
* Wait for stopped. Depending on @ptrace, different stopped state
* is used and the two don't interact with each other.
*/
ret = wait_task_stopped(wo, ptrace, p);
if (ret)
return ret;
/*
* Wait for continued. There's only one continued state and the
* ptracer can consume it which can confuse the real parent. Don't
* use WCONTINUED from ptracer. You don't need or want it.
*/
return wait_task_continued(wo, p);
}
/*
* Do the work of do_wait() for one thread in the group, @tsk.
*
* -ECHILD should be in ->notask_error before the first call.
* Returns nonzero for a final return, when we have unlocked tasklist_lock.
* Returns zero if the search for a child should continue; then
* ->notask_error is 0 if there were any eligible children,
* or still -ECHILD.
*/
static int do_wait_thread(struct wait_opts *wo, struct task_struct *tsk)
{
struct task_struct *p;
list_for_each_entry(p, &tsk->children, sibling) {
int ret = wait_consider_task(wo, 0, p);
if (ret)
return ret;
}
return 0;
}
static int ptrace_do_wait(struct wait_opts *wo, struct task_struct *tsk)
{
struct task_struct *p;
list_for_each_entry(p, &tsk->ptraced, ptrace_entry) {
int ret = wait_consider_task(wo, 1, p);
if (ret)
return ret;
}
return 0;
}
static int child_wait_callback(wait_queue_entry_t *wait, unsigned mode,
int sync, void *key)
{
struct wait_opts *wo = container_of(wait, struct wait_opts,
child_wait);
struct task_struct *p = key;
if (!eligible_pid(wo, p))
return 0;
if ((wo->wo_flags & __WNOTHREAD) && wait->private != p->parent)
return 0;
return default_wake_function(wait, mode, sync, key);
}
void __wake_up_parent(struct task_struct *p, struct task_struct *parent)
{
__wake_up_sync_key(&parent->signal->wait_chldexit,
TASK_INTERRUPTIBLE, 1, p);
}
static long do_wait(struct wait_opts *wo)
{
struct task_struct *tsk;
int retval;
trace_sched_process_wait(wo->wo_pid);
init_waitqueue_func_entry(&wo->child_wait, child_wait_callback);
wo->child_wait.private = current;
add_wait_queue(¤t->signal->wait_chldexit, &wo->child_wait);
repeat:
/*
* If there is nothing that can match our criteria, just get out.
* We will clear ->notask_error to zero if we see any child that
* might later match our criteria, even if we are not able to reap
* it yet.
*/
wo->notask_error = -ECHILD;
if ((wo->wo_type < PIDTYPE_MAX) &&
(!wo->wo_pid || hlist_empty(&wo->wo_pid->tasks[wo->wo_type])))
goto notask;
set_current_state(TASK_INTERRUPTIBLE);
read_lock(&tasklist_lock);
tsk = current;
do {
retval = do_wait_thread(wo, tsk);
if (retval)
goto end;
retval = ptrace_do_wait(wo, tsk);
if (retval)
goto end;
if (wo->wo_flags & __WNOTHREAD)
break;
} while_each_thread(current, tsk);
read_unlock(&tasklist_lock);
notask:
retval = wo->notask_error;
if (!retval && !(wo->wo_flags & WNOHANG)) {
retval = -ERESTARTSYS;
if (!signal_pending(current)) {
schedule();
goto repeat;
}
}
end:
__set_current_state(TASK_RUNNING);
remove_wait_queue(¤t->signal->wait_chldexit, &wo->child_wait);
return retval;
}
static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop,
int options, struct rusage *ru)
{
struct wait_opts wo;
struct pid *pid = NULL;
enum pid_type type;
long ret;
if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED|
__WNOTHREAD|__WCLONE|__WALL))
return -EINVAL;
if (!(options & (WEXITED|WSTOPPED|WCONTINUED)))
return -EINVAL;
switch (which) {
case P_ALL:
type = PIDTYPE_MAX;
break;
case P_PID:
type = PIDTYPE_PID;
if (upid <= 0)
return -EINVAL;
break;
case P_PGID:
type = PIDTYPE_PGID;
if (upid <= 0)
return -EINVAL;
break;
default:
return -EINVAL;
}
if (type < PIDTYPE_MAX)
pid = find_get_pid(upid);
wo.wo_type = type;
wo.wo_pid = pid;
wo.wo_flags = options;
wo.wo_info = infop;
wo.wo_rusage = ru;
ret = do_wait(&wo);
put_pid(pid);
return ret;
}
SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *,
infop, int, options, struct rusage __user *, ru)
{
struct rusage r;
struct waitid_info info = {.status = 0};
long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL);
int signo = 0;
if (err > 0) {
signo = SIGCHLD;
err = 0;
}
if (!err) {
if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
return -EFAULT;
}
if (!infop)
return err;
user_access_begin();
unsafe_put_user(signo, &infop->si_signo, Efault);
unsafe_put_user(0, &infop->si_errno, Efault);
unsafe_put_user((short)info.cause, &infop->si_code, Efault);
unsafe_put_user(info.pid, &infop->si_pid, Efault);
unsafe_put_user(info.uid, &infop->si_uid, Efault);
unsafe_put_user(info.status, &infop->si_status, Efault);
user_access_end();
return err;
Efault:
user_access_end();
return -EFAULT;
}
long kernel_wait4(pid_t upid, int __user *stat_addr, int options,
struct rusage *ru)
{
struct wait_opts wo;
struct pid *pid = NULL;
enum pid_type type;
long ret;
if (options & ~(WNOHANG|WUNTRACED|WCONTINUED|
__WNOTHREAD|__WCLONE|__WALL))
return -EINVAL;
/* -INT_MIN is not defined */
if (upid == INT_MIN)
return -ESRCH;
if (upid == -1)
type = PIDTYPE_MAX;
else if (upid < 0) {
type = PIDTYPE_PGID;
pid = find_get_pid(-upid);
} else if (upid == 0) {
type = PIDTYPE_PGID;
pid = get_task_pid(current, PIDTYPE_PGID);
} else /* upid > 0 */ {
type = PIDTYPE_PID;
pid = find_get_pid(upid);
}
wo.wo_type = type;
wo.wo_pid = pid;
wo.wo_flags = options | WEXITED;
wo.wo_info = NULL;
wo.wo_stat = 0;
wo.wo_rusage = ru;
ret = do_wait(&wo);
put_pid(pid);
if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr))
ret = -EFAULT;
return ret;
}
SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr,
int, options, struct rusage __user *, ru)
{
struct rusage r;
long err = kernel_wait4(upid, stat_addr, options, ru ? &r : NULL);
if (err > 0) {
if (ru && copy_to_user(ru, &r, sizeof(struct rusage)))
return -EFAULT;
}
return err;
}
#ifdef __ARCH_WANT_SYS_WAITPID
/*
* sys_waitpid() remains for compatibility. waitpid() should be
* implemented by calling sys_wait4() from libc.a.
*/
SYSCALL_DEFINE3(waitpid, pid_t, pid, int __user *, stat_addr, int, options)
{
return sys_wait4(pid, stat_addr, options, NULL);
}
#endif
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(wait4,
compat_pid_t, pid,
compat_uint_t __user *, stat_addr,
int, options,
struct compat_rusage __user *, ru)
{
struct rusage r;
long err = kernel_wait4(pid, stat_addr, options, ru ? &r : NULL);
if (err > 0) {
if (ru && put_compat_rusage(&r, ru))
return -EFAULT;
}
return err;
}
COMPAT_SYSCALL_DEFINE5(waitid,
int, which, compat_pid_t, pid,
struct compat_siginfo __user *, infop, int, options,
struct compat_rusage __user *, uru)
{
struct rusage ru;
struct waitid_info info = {.status = 0};
long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL);
int signo = 0;
if (err > 0) {
signo = SIGCHLD;
err = 0;
}
if (!err && uru) {
/* kernel_waitid() overwrites everything in ru */
if (COMPAT_USE_64BIT_TIME)
err = copy_to_user(uru, &ru, sizeof(ru));
else
err = put_compat_rusage(&ru, uru);
if (err)
return -EFAULT;
}
if (!infop)
return err;
user_access_begin();
unsafe_put_user(signo, &infop->si_signo, Efault);
unsafe_put_user(0, &infop->si_errno, Efault);
unsafe_put_user((short)info.cause, &infop->si_code, Efault);
unsafe_put_user(info.pid, &infop->si_pid, Efault);
unsafe_put_user(info.uid, &infop->si_uid, Efault);
unsafe_put_user(info.status, &infop->si_status, Efault);
user_access_end();
return err;
Efault:
user_access_end();
return -EFAULT;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_76_0 |
crossvul-cpp_data_bad_2441_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#include "k5-int.h"
#include <kadm5/admin.h>
#include <syslog.h>
#include <adm_proto.h> /* krb5_klog_syslog */
#include <stdio.h>
#include <errno.h>
#include "kadm5/server_internal.h" /* XXX for kadm5_server_handle_t */
#include "misc.h"
#ifndef GETSOCKNAME_ARG3_TYPE
#define GETSOCKNAME_ARG3_TYPE int
#endif
#define RFC3244_VERSION 0xff80
static krb5_error_code
process_chpw_request(krb5_context context, void *server_handle, char *realm,
krb5_keytab keytab, const krb5_fulladdr *local_faddr,
const krb5_fulladdr *remote_faddr, krb5_data *req,
krb5_data *rep)
{
krb5_error_code ret;
char *ptr;
unsigned int plen, vno;
krb5_data ap_req, ap_rep = empty_data();
krb5_data cipher = empty_data(), clear = empty_data();
krb5_auth_context auth_context = NULL;
krb5_principal changepw = NULL;
krb5_principal client, target = NULL;
krb5_ticket *ticket = NULL;
krb5_replay_data replay;
krb5_error krberror;
int numresult;
char strresult[1024];
char *clientstr = NULL, *targetstr = NULL;
const char *errmsg = NULL;
size_t clen;
char *cdots;
struct sockaddr_storage ss;
socklen_t salen;
char addrbuf[100];
krb5_address *addr = remote_faddr->address;
*rep = empty_data();
if (req->length < 4) {
/* either this, or the server is printing bad messages,
or the caller passed in garbage */
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request was truncated", sizeof(strresult));
goto chpwfail;
}
ptr = req->data;
/* verify length */
plen = (*ptr++ & 0xff);
plen = (plen<<8) | (*ptr++ & 0xff);
if (plen != req->length) {
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request length was inconsistent",
sizeof(strresult));
goto chpwfail;
}
/* verify version number */
vno = (*ptr++ & 0xff) ;
vno = (vno<<8) | (*ptr++ & 0xff);
if (vno != 1 && vno != RFC3244_VERSION) {
ret = KRB5KDC_ERR_BAD_PVNO;
numresult = KRB5_KPASSWD_BAD_VERSION;
snprintf(strresult, sizeof(strresult),
"Request contained unknown protocol version number %d", vno);
goto chpwfail;
}
/* read, check ap-req length */
ap_req.length = (*ptr++ & 0xff);
ap_req.length = (ap_req.length<<8) | (*ptr++ & 0xff);
if (ptr + ap_req.length >= req->data + req->length) {
ret = KRB5KRB_AP_ERR_MODIFIED;
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Request was truncated in AP-REQ",
sizeof(strresult));
goto chpwfail;
}
/* verify ap_req */
ap_req.data = ptr;
ptr += ap_req.length;
ret = krb5_auth_con_init(context, &auth_context);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed initializing auth context",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_auth_con_setflags(context, auth_context,
KRB5_AUTH_CONTEXT_DO_SEQUENCE);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed initializing auth context",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_build_principal(context, &changepw, strlen(realm), realm,
"kadmin", "changepw", NULL);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed building kadmin/changepw principal",
sizeof(strresult));
goto chpwfail;
}
ret = krb5_rd_req(context, &auth_context, &ap_req, changepw, keytab,
NULL, &ticket);
if (ret) {
numresult = KRB5_KPASSWD_AUTHERROR;
strlcpy(strresult, "Failed reading application request",
sizeof(strresult));
goto chpwfail;
}
/* construct the ap-rep */
ret = krb5_mk_rep(context, auth_context, &ap_rep);
if (ret) {
numresult = KRB5_KPASSWD_AUTHERROR;
strlcpy(strresult, "Failed replying to application request",
sizeof(strresult));
goto chpwfail;
}
/* decrypt the ChangePasswdData */
cipher.length = (req->data + req->length) - ptr;
cipher.data = ptr;
/*
* Don't set a remote address in auth_context before calling krb5_rd_priv,
* so that we can work against clients behind a NAT. Reflection attacks
* aren't a concern since we use sequence numbers and since our requests
* don't look anything like our responses. Also don't set a local address,
* since we don't know what interface the request was received on.
*/
ret = krb5_rd_priv(context, auth_context, &cipher, &clear, &replay);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed decrypting request", sizeof(strresult));
goto chpwfail;
}
client = ticket->enc_part2->client;
/* decode ChangePasswdData for setpw requests */
if (vno == RFC3244_VERSION) {
krb5_data *clear_data;
ret = decode_krb5_setpw_req(&clear, &clear_data, &target);
if (ret != 0) {
numresult = KRB5_KPASSWD_MALFORMED;
strlcpy(strresult, "Failed decoding ChangePasswdData",
sizeof(strresult));
goto chpwfail;
}
zapfree(clear.data, clear.length);
clear = *clear_data;
free(clear_data);
if (target != NULL) {
ret = krb5_unparse_name(context, target, &targetstr);
if (ret != 0) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed unparsing target name for log",
sizeof(strresult));
goto chpwfail;
}
}
}
ret = krb5_unparse_name(context, client, &clientstr);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed unparsing client name for log",
sizeof(strresult));
goto chpwfail;
}
/* for cpw, verify that this is an AS_REQ ticket */
if (vno == 1 &&
(ticket->enc_part2->flags & TKT_FLG_INITIAL) == 0) {
numresult = KRB5_KPASSWD_INITIAL_FLAG_NEEDED;
strlcpy(strresult, "Ticket must be derived from a password",
sizeof(strresult));
goto chpwfail;
}
/* change the password */
ptr = k5memdup0(clear.data, clear.length, &ret);
ret = schpw_util_wrapper(server_handle, client, target,
(ticket->enc_part2->flags & TKT_FLG_INITIAL) != 0,
ptr, NULL, strresult, sizeof(strresult));
if (ret)
errmsg = krb5_get_error_message(context, ret);
/* zap the password */
zapfree(clear.data, clear.length);
zapfree(ptr, clear.length);
clear = empty_data();
clen = strlen(clientstr);
trunc_name(&clen, &cdots);
switch (addr->addrtype) {
case ADDRTYPE_INET: {
struct sockaddr_in *sin = ss2sin(&ss);
sin->sin_family = AF_INET;
memcpy(&sin->sin_addr, addr->contents, addr->length);
sin->sin_port = htons(remote_faddr->port);
salen = sizeof(*sin);
break;
}
case ADDRTYPE_INET6: {
struct sockaddr_in6 *sin6 = ss2sin6(&ss);
sin6->sin6_family = AF_INET6;
memcpy(&sin6->sin6_addr, addr->contents, addr->length);
sin6->sin6_port = htons(remote_faddr->port);
salen = sizeof(*sin6);
break;
}
default: {
struct sockaddr *sa = ss2sa(&ss);
sa->sa_family = AF_UNSPEC;
salen = sizeof(*sa);
break;
}
}
if (getnameinfo(ss2sa(&ss), salen,
addrbuf, sizeof(addrbuf), NULL, 0,
NI_NUMERICHOST | NI_NUMERICSERV) != 0)
strlcpy(addrbuf, "<unprintable>", sizeof(addrbuf));
if (vno == RFC3244_VERSION) {
size_t tlen;
char *tdots;
const char *targetp;
if (target == NULL) {
tlen = clen;
tdots = cdots;
targetp = targetstr;
} else {
tlen = strlen(targetstr);
trunc_name(&tlen, &tdots);
targetp = clientstr;
}
krb5_klog_syslog(LOG_NOTICE, _("setpw request from %s by %.*s%s for "
"%.*s%s: %s"), addrbuf, (int) clen,
clientstr, cdots, (int) tlen, targetp, tdots,
errmsg ? errmsg : "success");
} else {
krb5_klog_syslog(LOG_NOTICE, _("chpw request from %s for %.*s%s: %s"),
addrbuf, (int) clen, clientstr, cdots,
errmsg ? errmsg : "success");
}
switch (ret) {
case KADM5_AUTH_CHANGEPW:
numresult = KRB5_KPASSWD_ACCESSDENIED;
break;
case KADM5_PASS_Q_TOOSHORT:
case KADM5_PASS_REUSE:
case KADM5_PASS_Q_CLASS:
case KADM5_PASS_Q_DICT:
case KADM5_PASS_Q_GENERIC:
case KADM5_PASS_TOOSOON:
numresult = KRB5_KPASSWD_SOFTERROR;
break;
case 0:
numresult = KRB5_KPASSWD_SUCCESS;
strlcpy(strresult, "", sizeof(strresult));
break;
default:
numresult = KRB5_KPASSWD_HARDERROR;
break;
}
chpwfail:
clear.length = 2 + strlen(strresult);
clear.data = (char *) malloc(clear.length);
ptr = clear.data;
*ptr++ = (numresult>>8) & 0xff;
*ptr++ = numresult & 0xff;
memcpy(ptr, strresult, strlen(strresult));
cipher = empty_data();
if (ap_rep.length) {
ret = krb5_auth_con_setaddrs(context, auth_context,
local_faddr->address, NULL);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult,
"Failed storing client and server internet addresses",
sizeof(strresult));
} else {
ret = krb5_mk_priv(context, auth_context, &clear, &cipher,
&replay);
if (ret) {
numresult = KRB5_KPASSWD_HARDERROR;
strlcpy(strresult, "Failed encrypting reply",
sizeof(strresult));
}
}
}
/* if no KRB-PRIV was constructed, then we need a KRB-ERROR.
if this fails, just bail. there's nothing else we can do. */
if (cipher.length == 0) {
/* clear out ap_rep now, so that it won't be inserted in the
reply */
if (ap_rep.length) {
free(ap_rep.data);
ap_rep = empty_data();
}
krberror.ctime = 0;
krberror.cusec = 0;
krberror.susec = 0;
ret = krb5_timeofday(context, &krberror.stime);
if (ret)
goto bailout;
/* this is really icky. but it's what all the other callers
to mk_error do. */
krberror.error = ret;
krberror.error -= ERROR_TABLE_BASE_krb5;
if (krberror.error < 0 || krberror.error > 128)
krberror.error = KRB_ERR_GENERIC;
krberror.client = NULL;
ret = krb5_build_principal(context, &krberror.server,
strlen(realm), realm,
"kadmin", "changepw", NULL);
if (ret)
goto bailout;
krberror.text.length = 0;
krberror.e_data = clear;
ret = krb5_mk_error(context, &krberror, &cipher);
krb5_free_principal(context, krberror.server);
if (ret)
goto bailout;
}
/* construct the reply */
ret = alloc_data(rep, 6 + ap_rep.length + cipher.length);
if (ret)
goto bailout;
ptr = rep->data;
/* length */
*ptr++ = (rep->length>>8) & 0xff;
*ptr++ = rep->length & 0xff;
/* version == 0x0001 big-endian */
*ptr++ = 0;
*ptr++ = 1;
/* ap_rep length, big-endian */
*ptr++ = (ap_rep.length>>8) & 0xff;
*ptr++ = ap_rep.length & 0xff;
/* ap-rep data */
if (ap_rep.length) {
memcpy(ptr, ap_rep.data, ap_rep.length);
ptr += ap_rep.length;
}
/* krb-priv or krb-error */
memcpy(ptr, cipher.data, cipher.length);
bailout:
krb5_auth_con_free(context, auth_context);
krb5_free_principal(context, changepw);
krb5_free_ticket(context, ticket);
free(ap_rep.data);
free(clear.data);
free(cipher.data);
krb5_free_principal(context, target);
krb5_free_unparsed_name(context, targetstr);
krb5_free_unparsed_name(context, clientstr);
krb5_free_error_message(context, errmsg);
return ret;
}
/* Dispatch routine for set/change password */
void
dispatch(void *handle, struct sockaddr *local_saddr,
const krb5_fulladdr *remote_faddr, krb5_data *request, int is_tcp,
verto_ctx *vctx, loop_respond_fn respond, void *arg)
{
krb5_error_code ret;
krb5_keytab kt = NULL;
kadm5_server_handle_t server_handle = (kadm5_server_handle_t)handle;
krb5_fulladdr local_faddr;
krb5_address **local_kaddrs = NULL, local_kaddr_buf;
krb5_data *response = NULL;
if (local_saddr == NULL) {
ret = krb5_os_localaddr(server_handle->context, &local_kaddrs);
if (ret != 0)
goto egress;
local_faddr.address = local_kaddrs[0];
local_faddr.port = 0;
} else {
local_faddr.address = &local_kaddr_buf;
init_addr(&local_faddr, local_saddr);
}
ret = krb5_kt_resolve(server_handle->context, "KDB:", &kt);
if (ret != 0) {
krb5_klog_syslog(LOG_ERR, _("chpw: Couldn't open admin keytab %s"),
krb5_get_error_message(server_handle->context, ret));
goto egress;
}
response = k5alloc(sizeof(krb5_data), &ret);
if (response == NULL)
goto egress;
ret = process_chpw_request(server_handle->context,
handle,
server_handle->params.realm,
kt,
&local_faddr,
remote_faddr,
request,
response);
egress:
if (ret)
krb5_free_data(server_handle->context, response);
krb5_free_addresses(server_handle->context, local_kaddrs);
krb5_kt_close(server_handle->context, kt);
(*respond)(arg, ret, ret == 0 ? response : NULL);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2441_0 |
crossvul-cpp_data_bad_4904_0 | /*-
* Copyright (c) 2004-2013 Tim Kientzle
* Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
* Copyright (c) 2013 Konrad Kleine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "archive_platform.h"
__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_zip.c 201102 2009-12-28 03:11:36Z kientzle $");
/*
* The definitive documentation of the Zip file format is:
* http://www.pkware.com/documents/casestudies/APPNOTE.TXT
*
* The Info-Zip project has pioneered various extensions to better
* support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
* "Ux", and 0x7875 "ux" extensions for time and ownership
* information.
*
* History of this code: The streaming Zip reader was first added to
* libarchive in January 2005. Support for seekable input sources was
* added in Nov 2011. Zip64 support (including a significant code
* refactoring) was added in 2014.
*/
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
#include "archive.h"
#include "archive_digest_private.h"
#include "archive_cryptor_private.h"
#include "archive_endian.h"
#include "archive_entry.h"
#include "archive_entry_locale.h"
#include "archive_hmac_private.h"
#include "archive_private.h"
#include "archive_rb.h"
#include "archive_read_private.h"
#ifndef HAVE_ZLIB_H
#include "archive_crc32.h"
#endif
struct zip_entry {
struct archive_rb_node node;
struct zip_entry *next;
int64_t local_header_offset;
int64_t compressed_size;
int64_t uncompressed_size;
int64_t gid;
int64_t uid;
struct archive_string rsrcname;
time_t mtime;
time_t atime;
time_t ctime;
uint32_t crc32;
uint16_t mode;
uint16_t zip_flags; /* From GP Flags Field */
unsigned char compression;
unsigned char system; /* From "version written by" */
unsigned char flags; /* Our extra markers. */
unsigned char decdat;/* Used for Decryption check */
/* WinZip AES encryption extra field should be available
* when compression is 99. */
struct {
/* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
unsigned vendor;
#define AES_VENDOR_AE_1 0x0001
#define AES_VENDOR_AE_2 0x0002
/* AES encryption strength:
* 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
unsigned strength;
/* Actual compression method. */
unsigned char compression;
} aes_extra;
};
struct trad_enc_ctx {
uint32_t keys[3];
};
/* Bits used in zip_flags. */
#define ZIP_ENCRYPTED (1 << 0)
#define ZIP_LENGTH_AT_END (1 << 3)
#define ZIP_STRONG_ENCRYPTED (1 << 6)
#define ZIP_UTF8_NAME (1 << 11)
/* See "7.2 Single Password Symmetric Encryption Method"
in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
#define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
/* Bits used in flags. */
#define LA_USED_ZIP64 (1 << 0)
#define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
/*
* See "WinZip - AES Encryption Information"
* http://www.winzip.com/aes_info.htm
*/
/* Value used in compression method. */
#define WINZIP_AES_ENCRYPTION 99
/* Authentication code size. */
#define AUTH_CODE_SIZE 10
/**/
#define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
struct zip {
/* Structural information about the archive. */
struct archive_string format_name;
int64_t central_directory_offset;
size_t central_directory_entries_total;
size_t central_directory_entries_on_this_disk;
int has_encrypted_entries;
/* List of entries (seekable Zip only) */
struct zip_entry *zip_entries;
struct archive_rb_tree tree;
struct archive_rb_tree tree_rsrc;
/* Bytes read but not yet consumed via __archive_read_consume() */
size_t unconsumed;
/* Information about entry we're currently reading. */
struct zip_entry *entry;
int64_t entry_bytes_remaining;
/* These count the number of bytes actually read for the entry. */
int64_t entry_compressed_bytes_read;
int64_t entry_uncompressed_bytes_read;
/* Running CRC32 of the decompressed data */
unsigned long entry_crc32;
unsigned long (*crc32func)(unsigned long, const void *,
size_t);
char ignore_crc32;
/* Flags to mark progress of decompression. */
char decompress_init;
char end_of_entry;
#ifdef HAVE_ZLIB_H
unsigned char *uncompressed_buffer;
size_t uncompressed_buffer_size;
z_stream stream;
char stream_valid;
#endif
struct archive_string_conv *sconv;
struct archive_string_conv *sconv_default;
struct archive_string_conv *sconv_utf8;
int init_default_conversion;
int process_mac_extensions;
char init_decryption;
/* Decryption buffer. */
unsigned char *decrypted_buffer;
unsigned char *decrypted_ptr;
size_t decrypted_buffer_size;
size_t decrypted_bytes_remaining;
size_t decrypted_unconsumed_bytes;
/* Traditional PKWARE decryption. */
struct trad_enc_ctx tctx;
char tctx_valid;
/* WinZip AES decyption. */
/* Contexts used for AES decryption. */
archive_crypto_ctx cctx;
char cctx_valid;
archive_hmac_sha1_ctx hctx;
char hctx_valid;
/* Strong encryption's decryption header information. */
unsigned iv_size;
unsigned alg_id;
unsigned bit_len;
unsigned flags;
unsigned erd_size;
unsigned v_size;
unsigned v_crc32;
uint8_t *iv;
uint8_t *erd;
uint8_t *v_data;
};
/* Many systems define min or MIN, but not all. */
#define zipmin(a,b) ((a) < (b) ? (a) : (b))
/* ------------------------------------------------------------------------ */
/*
Traditional PKWARE Decryption functions.
*/
static void
trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
{
uint8_t t;
#define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
ctx->keys[0] = CRC32(ctx->keys[0], c);
ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
t = (ctx->keys[1] >> 24) & 0xff;
ctx->keys[2] = CRC32(ctx->keys[2], t);
#undef CRC32
}
static uint8_t
trad_enc_decypt_byte(struct trad_enc_ctx *ctx)
{
unsigned temp = ctx->keys[2] | 2;
return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
}
static void
trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
size_t in_len, uint8_t *out, size_t out_len)
{
unsigned i, max;
max = (unsigned)((in_len < out_len)? in_len: out_len);
for (i = 0; i < max; i++) {
uint8_t t = in[i] ^ trad_enc_decypt_byte(ctx);
out[i] = t;
trad_enc_update_keys(ctx, t);
}
}
static int
trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
const uint8_t *key, size_t key_len, uint8_t *crcchk)
{
uint8_t header[12];
if (key_len < 12) {
*crcchk = 0xff;
return -1;
}
ctx->keys[0] = 305419896L;
ctx->keys[1] = 591751049L;
ctx->keys[2] = 878082192L;
for (;pw_len; --pw_len)
trad_enc_update_keys(ctx, *pw++);
trad_enc_decrypt_update(ctx, key, 12, header, 12);
/* Return the last byte for CRC check. */
*crcchk = header[11];
return 0;
}
#if 0
static void
crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
int key_size)
{
#define MD_SIZE 20
archive_sha1_ctx ctx;
unsigned char md1[MD_SIZE];
unsigned char md2[MD_SIZE * 2];
unsigned char mkb[64];
int i;
archive_sha1_init(&ctx);
archive_sha1_update(&ctx, p, size);
archive_sha1_final(&ctx, md1);
memset(mkb, 0x36, sizeof(mkb));
for (i = 0; i < MD_SIZE; i++)
mkb[i] ^= md1[i];
archive_sha1_init(&ctx);
archive_sha1_update(&ctx, mkb, sizeof(mkb));
archive_sha1_final(&ctx, md2);
memset(mkb, 0x5C, sizeof(mkb));
for (i = 0; i < MD_SIZE; i++)
mkb[i] ^= md1[i];
archive_sha1_init(&ctx);
archive_sha1_update(&ctx, mkb, sizeof(mkb));
archive_sha1_final(&ctx, md2 + MD_SIZE);
if (key_size > 32)
key_size = 32;
memcpy(key, md2, key_size);
#undef MD_SIZE
}
#endif
/*
* Common code for streaming or seeking modes.
*
* Includes code to read local file headers, decompress data
* from entry bodies, and common API.
*/
static unsigned long
real_crc32(unsigned long crc, const void *buff, size_t len)
{
return crc32(crc, buff, (unsigned int)len);
}
/* Used by "ignorecrc32" option to speed up tests. */
static unsigned long
fake_crc32(unsigned long crc, const void *buff, size_t len)
{
(void)crc; /* UNUSED */
(void)buff; /* UNUSED */
(void)len; /* UNUSED */
return 0;
}
static struct {
int id;
const char * name;
} compression_methods[] = {
{0, "uncompressed"}, /* The file is stored (no compression) */
{1, "shrinking"}, /* The file is Shrunk */
{2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
{3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
{4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
{5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
{6, "imploded"}, /* The file is Imploded */
{7, "reserved"}, /* Reserved for Tokenizing compression algorithm */
{8, "deflation"}, /* The file is Deflated */
{9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
{10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
* (old IBM TERSE) */
{11, "reserved"}, /* Reserved by PKWARE */
{12, "bzip"}, /* File is compressed using BZIP2 algorithm */
{13, "reserved"}, /* Reserved by PKWARE */
{14, "lzma"}, /* LZMA (EFS) */
{15, "reserved"}, /* Reserved by PKWARE */
{16, "reserved"}, /* Reserved by PKWARE */
{17, "reserved"}, /* Reserved by PKWARE */
{18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
{19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
{97, "wav-pack"}, /* WavPack compressed data */
{98, "ppmd-1"}, /* PPMd version I, Rev 1 */
{99, "aes"} /* WinZip AES encryption */
};
static const char *
compression_name(const int compression)
{
static const int num_compression_methods =
sizeof(compression_methods)/sizeof(compression_methods[0]);
int i=0;
while(compression >= 0 && i < num_compression_methods) {
if (compression_methods[i].id == compression)
return compression_methods[i].name;
i++;
}
return "??";
}
/* Convert an MSDOS-style date/time into Unix-style time. */
static time_t
zip_time(const char *p)
{
int msTime, msDate;
struct tm ts;
msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
memset(&ts, 0, sizeof(ts));
ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
ts.tm_mday = msDate & 0x1f; /* Day of month. */
ts.tm_hour = (msTime >> 11) & 0x1f;
ts.tm_min = (msTime >> 5) & 0x3f;
ts.tm_sec = (msTime << 1) & 0x3e;
ts.tm_isdst = -1;
return mktime(&ts);
}
/*
* The extra data is stored as a list of
* id1+size1+data1 + id2+size2+data2 ...
* triplets. id and size are 2 bytes each.
*/
static void
process_extra(const char *p, size_t extra_length, struct zip_entry* zip_entry)
{
unsigned offset = 0;
while (offset < extra_length - 4) {
unsigned short headerid = archive_le16dec(p + offset);
unsigned short datasize = archive_le16dec(p + offset + 2);
offset += 4;
if (offset + datasize > extra_length) {
break;
}
#ifdef DEBUG
fprintf(stderr, "Header id 0x%04x, length %d\n",
headerid, datasize);
#endif
switch (headerid) {
case 0x0001:
/* Zip64 extended information extra field. */
zip_entry->flags |= LA_USED_ZIP64;
if (zip_entry->uncompressed_size == 0xffffffff) {
if (datasize < 8)
break;
zip_entry->uncompressed_size =
archive_le64dec(p + offset);
offset += 8;
datasize -= 8;
}
if (zip_entry->compressed_size == 0xffffffff) {
if (datasize < 8)
break;
zip_entry->compressed_size =
archive_le64dec(p + offset);
offset += 8;
datasize -= 8;
}
if (zip_entry->local_header_offset == 0xffffffff) {
if (datasize < 8)
break;
zip_entry->local_header_offset =
archive_le64dec(p + offset);
offset += 8;
datasize -= 8;
}
/* archive_le32dec(p + offset) gives disk
* on which file starts, but we don't handle
* multi-volume Zip files. */
break;
#ifdef DEBUG
case 0x0017:
{
/* Strong encryption field. */
if (archive_le16dec(p + offset) == 2) {
unsigned algId =
archive_le16dec(p + offset + 2);
unsigned bitLen =
archive_le16dec(p + offset + 4);
int flags =
archive_le16dec(p + offset + 6);
fprintf(stderr, "algId=0x%04x, bitLen=%u, "
"flgas=%d\n", algId, bitLen,flags);
}
break;
}
#endif
case 0x5455:
{
/* Extended time field "UT". */
int flags = p[offset];
offset++;
datasize--;
/* Flag bits indicate which dates are present. */
if (flags & 0x01)
{
#ifdef DEBUG
fprintf(stderr, "mtime: %lld -> %d\n",
(long long)zip_entry->mtime,
archive_le32dec(p + offset));
#endif
if (datasize < 4)
break;
zip_entry->mtime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
if (flags & 0x02)
{
if (datasize < 4)
break;
zip_entry->atime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
if (flags & 0x04)
{
if (datasize < 4)
break;
zip_entry->ctime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
break;
}
case 0x5855:
{
/* Info-ZIP Unix Extra Field (old version) "UX". */
if (datasize >= 8) {
zip_entry->atime = archive_le32dec(p + offset);
zip_entry->mtime =
archive_le32dec(p + offset + 4);
}
if (datasize >= 12) {
zip_entry->uid =
archive_le16dec(p + offset + 8);
zip_entry->gid =
archive_le16dec(p + offset + 10);
}
break;
}
case 0x6c78:
{
/* Experimental 'xl' field */
/*
* Introduced Dec 2013 to provide a way to
* include external file attributes (and other
* fields that ordinarily appear only in
* central directory) in local file header.
* This provides file type and permission
* information necessary to support full
* streaming extraction. Currently being
* discussed with other Zip developers
* ... subject to change.
*
* Format:
* The field starts with a bitmap that specifies
* which additional fields are included. The
* bitmap is variable length and can be extended in
* the future.
*
* n bytes - feature bitmap: first byte has low-order
* 7 bits. If high-order bit is set, a subsequent
* byte holds the next 7 bits, etc.
*
* if bitmap & 1, 2 byte "version made by"
* if bitmap & 2, 2 byte "internal file attributes"
* if bitmap & 4, 4 byte "external file attributes"
* if bitmap & 8, 2 byte comment length + n byte comment
*/
int bitmap, bitmap_last;
if (datasize < 1)
break;
bitmap_last = bitmap = 0xff & p[offset];
offset += 1;
datasize -= 1;
/* We only support first 7 bits of bitmap; skip rest. */
while ((bitmap_last & 0x80) != 0
&& datasize >= 1) {
bitmap_last = p[offset];
offset += 1;
datasize -= 1;
}
if (bitmap & 1) {
/* 2 byte "version made by" */
if (datasize < 2)
break;
zip_entry->system
= archive_le16dec(p + offset) >> 8;
offset += 2;
datasize -= 2;
}
if (bitmap & 2) {
/* 2 byte "internal file attributes" */
uint32_t internal_attributes;
if (datasize < 2)
break;
internal_attributes
= archive_le16dec(p + offset);
/* Not used by libarchive at present. */
(void)internal_attributes; /* UNUSED */
offset += 2;
datasize -= 2;
}
if (bitmap & 4) {
/* 4 byte "external file attributes" */
uint32_t external_attributes;
if (datasize < 4)
break;
external_attributes
= archive_le32dec(p + offset);
if (zip_entry->system == 3) {
zip_entry->mode
= external_attributes >> 16;
} else if (zip_entry->system == 0) {
// Interpret MSDOS directory bit
if (0x10 == (external_attributes & 0x10)) {
zip_entry->mode = AE_IFDIR | 0775;
} else {
zip_entry->mode = AE_IFREG | 0664;
}
if (0x01 == (external_attributes & 0x01)) {
// Read-only bit; strip write permissions
zip_entry->mode &= 0555;
}
} else {
zip_entry->mode = 0;
}
offset += 4;
datasize -= 4;
}
if (bitmap & 8) {
/* 2 byte comment length + comment */
uint32_t comment_length;
if (datasize < 2)
break;
comment_length
= archive_le16dec(p + offset);
offset += 2;
datasize -= 2;
if (datasize < comment_length)
break;
/* Comment is not supported by libarchive */
offset += comment_length;
datasize -= comment_length;
}
break;
}
case 0x7855:
/* Info-ZIP Unix Extra Field (type 2) "Ux". */
#ifdef DEBUG
fprintf(stderr, "uid %d gid %d\n",
archive_le16dec(p + offset),
archive_le16dec(p + offset + 2));
#endif
if (datasize >= 2)
zip_entry->uid = archive_le16dec(p + offset);
if (datasize >= 4)
zip_entry->gid =
archive_le16dec(p + offset + 2);
break;
case 0x7875:
{
/* Info-Zip Unix Extra Field (type 3) "ux". */
int uidsize = 0, gidsize = 0;
/* TODO: support arbitrary uidsize/gidsize. */
if (datasize >= 1 && p[offset] == 1) {/* version=1 */
if (datasize >= 4) {
/* get a uid size. */
uidsize = 0xff & (int)p[offset+1];
if (uidsize == 2)
zip_entry->uid =
archive_le16dec(
p + offset + 2);
else if (uidsize == 4 && datasize >= 6)
zip_entry->uid =
archive_le32dec(
p + offset + 2);
}
if (datasize >= (2 + uidsize + 3)) {
/* get a gid size. */
gidsize = 0xff & (int)p[offset+2+uidsize];
if (gidsize == 2)
zip_entry->gid =
archive_le16dec(
p+offset+2+uidsize+1);
else if (gidsize == 4 &&
datasize >= (2 + uidsize + 5))
zip_entry->gid =
archive_le32dec(
p+offset+2+uidsize+1);
}
}
break;
}
case 0x9901:
/* WinZIp AES extra data field. */
if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
/* Vendor version. */
zip_entry->aes_extra.vendor =
archive_le16dec(p + offset);
/* AES encryption strength. */
zip_entry->aes_extra.strength = p[offset + 4];
/* Actual compression method. */
zip_entry->aes_extra.compression =
p[offset + 5];
}
break;
default:
break;
}
offset += datasize;
}
#ifdef DEBUG
if (offset != extra_length)
{
fprintf(stderr,
"Extra data field contents do not match reported size!\n");
}
#endif
}
/*
* Assumes file pointer is at beginning of local file header.
*/
static int
zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
struct zip *zip)
{
const char *p;
const void *h;
const wchar_t *wp;
const char *cp;
size_t len, filename_length, extra_length;
struct archive_string_conv *sconv;
struct zip_entry *zip_entry = zip->entry;
struct zip_entry zip_entry_central_dir;
int ret = ARCHIVE_OK;
char version;
/* Save a copy of the original for consistency checks. */
zip_entry_central_dir = *zip_entry;
zip->decompress_init = 0;
zip->end_of_entry = 0;
zip->entry_uncompressed_bytes_read = 0;
zip->entry_compressed_bytes_read = 0;
zip->entry_crc32 = zip->crc32func(0, NULL, 0);
/* Setup default conversion. */
if (zip->sconv == NULL && !zip->init_default_conversion) {
zip->sconv_default =
archive_string_default_conversion_for_read(&(a->archive));
zip->init_default_conversion = 1;
}
if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_FATAL);
}
if (memcmp(p, "PK\003\004", 4) != 0) {
archive_set_error(&a->archive, -1, "Damaged Zip archive");
return ARCHIVE_FATAL;
}
version = p[4];
zip_entry->system = p[5];
zip_entry->zip_flags = archive_le16dec(p + 6);
if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
zip->has_encrypted_entries = 1;
archive_entry_set_is_data_encrypted(entry, 1);
if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
zip_entry->zip_flags & ZIP_ENCRYPTED &&
zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
archive_entry_set_is_metadata_encrypted(entry, 1);
return ARCHIVE_FATAL;
}
}
zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
zip_entry->compression = (char)archive_le16dec(p + 8);
zip_entry->mtime = zip_time(p + 10);
zip_entry->crc32 = archive_le32dec(p + 14);
if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
zip_entry->decdat = p[11];
else
zip_entry->decdat = p[17];
zip_entry->compressed_size = archive_le32dec(p + 18);
zip_entry->uncompressed_size = archive_le32dec(p + 22);
filename_length = archive_le16dec(p + 26);
extra_length = archive_le16dec(p + 28);
__archive_read_consume(a, 30);
/* Read the filename. */
if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_FATAL);
}
if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
/* The filename is stored to be UTF-8. */
if (zip->sconv_utf8 == NULL) {
zip->sconv_utf8 =
archive_string_conversion_from_charset(
&a->archive, "UTF-8", 1);
if (zip->sconv_utf8 == NULL)
return (ARCHIVE_FATAL);
}
sconv = zip->sconv_utf8;
} else if (zip->sconv != NULL)
sconv = zip->sconv;
else
sconv = zip->sconv_default;
if (archive_entry_copy_pathname_l(entry,
h, filename_length, sconv) != 0) {
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Pathname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Pathname cannot be converted "
"from %s to current locale.",
archive_string_conversion_charset_name(sconv));
ret = ARCHIVE_WARN;
}
__archive_read_consume(a, filename_length);
/* Read the extra data. */
if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_FATAL);
}
process_extra(h, extra_length, zip_entry);
__archive_read_consume(a, extra_length);
/* Work around a bug in Info-Zip: When reading from a pipe, it
* stats the pipe instead of synthesizing a file entry. */
if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
zip_entry->mode &= ~ AE_IFMT;
zip_entry->mode |= AE_IFREG;
}
if ((zip_entry->mode & AE_IFMT) == 0) {
/* Especially in streaming mode, we can end up
here without having seen proper mode information.
Guess from the filename. */
wp = archive_entry_pathname_w(entry);
if (wp != NULL) {
len = wcslen(wp);
if (len > 0 && wp[len - 1] == L'/')
zip_entry->mode |= AE_IFDIR;
else
zip_entry->mode |= AE_IFREG;
} else {
cp = archive_entry_pathname(entry);
len = (cp != NULL)?strlen(cp):0;
if (len > 0 && cp[len - 1] == '/')
zip_entry->mode |= AE_IFDIR;
else
zip_entry->mode |= AE_IFREG;
}
if (zip_entry->mode == AE_IFDIR) {
zip_entry->mode |= 0775;
} else if (zip_entry->mode == AE_IFREG) {
zip_entry->mode |= 0664;
}
}
/* Make sure directories end in '/' */
if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
wp = archive_entry_pathname_w(entry);
if (wp != NULL) {
len = wcslen(wp);
if (len > 0 && wp[len - 1] != L'/') {
struct archive_wstring s;
archive_string_init(&s);
archive_wstrcat(&s, wp);
archive_wstrappend_wchar(&s, L'/');
archive_entry_copy_pathname_w(entry, s.s);
}
} else {
cp = archive_entry_pathname(entry);
len = (cp != NULL)?strlen(cp):0;
if (len > 0 && cp[len - 1] != '/') {
struct archive_string s;
archive_string_init(&s);
archive_strcat(&s, cp);
archive_strappend_char(&s, '/');
archive_entry_set_pathname(entry, s.s);
}
}
}
if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
/* If this came from the central dir, it's size info
* is definitive, so ignore the length-at-end flag. */
zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
/* If local header is missing a value, use the one from
the central directory. If both have it, warn about
mismatches. */
if (zip_entry->crc32 == 0) {
zip_entry->crc32 = zip_entry_central_dir.crc32;
} else if (!zip->ignore_crc32
&& zip_entry->crc32 != zip_entry_central_dir.crc32) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Inconsistent CRC32 values");
ret = ARCHIVE_WARN;
}
if (zip_entry->compressed_size == 0) {
zip_entry->compressed_size
= zip_entry_central_dir.compressed_size;
} else if (zip_entry->compressed_size
!= zip_entry_central_dir.compressed_size) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Inconsistent compressed size: "
"%jd in central directory, %jd in local header",
(intmax_t)zip_entry_central_dir.compressed_size,
(intmax_t)zip_entry->compressed_size);
ret = ARCHIVE_WARN;
}
if (zip_entry->uncompressed_size == 0) {
zip_entry->uncompressed_size
= zip_entry_central_dir.uncompressed_size;
} else if (zip_entry->uncompressed_size
!= zip_entry_central_dir.uncompressed_size) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Inconsistent uncompressed size: "
"%jd in central directory, %jd in local header",
(intmax_t)zip_entry_central_dir.uncompressed_size,
(intmax_t)zip_entry->uncompressed_size);
ret = ARCHIVE_WARN;
}
}
/* Populate some additional entry fields: */
archive_entry_set_mode(entry, zip_entry->mode);
archive_entry_set_uid(entry, zip_entry->uid);
archive_entry_set_gid(entry, zip_entry->gid);
archive_entry_set_mtime(entry, zip_entry->mtime, 0);
archive_entry_set_ctime(entry, zip_entry->ctime, 0);
archive_entry_set_atime(entry, zip_entry->atime, 0);
if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
size_t linkname_length;
if (zip_entry->compressed_size > 64 * 1024) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Zip file with oversized link entry");
return ARCHIVE_FATAL;
}
linkname_length = (size_t)zip_entry->compressed_size;
archive_entry_set_size(entry, 0);
p = __archive_read_ahead(a, linkname_length, NULL);
if (p == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Truncated Zip file");
return ARCHIVE_FATAL;
}
sconv = zip->sconv;
if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
sconv = zip->sconv_utf8;
if (sconv == NULL)
sconv = zip->sconv_default;
if (archive_entry_copy_symlink_l(entry, p, linkname_length,
sconv) != 0) {
if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
(zip->entry->zip_flags & ZIP_UTF8_NAME))
archive_entry_copy_symlink_l(entry, p,
linkname_length, NULL);
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Symlink");
return (ARCHIVE_FATAL);
}
/*
* Since there is no character-set regulation for
* symlink name, do not report the conversion error
* in an automatic conversion.
*/
if (sconv != zip->sconv_utf8 ||
(zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Symlink cannot be converted "
"from %s to current locale.",
archive_string_conversion_charset_name(
sconv));
ret = ARCHIVE_WARN;
}
}
zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
if (__archive_read_consume(a, linkname_length) < 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Read error skipping symlink target name");
return ARCHIVE_FATAL;
}
} else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
|| zip_entry->uncompressed_size > 0) {
/* Set the size only if it's meaningful. */
archive_entry_set_size(entry, zip_entry->uncompressed_size);
}
zip->entry_bytes_remaining = zip_entry->compressed_size;
/* If there's no body, force read_data() to return EOF immediately. */
if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
&& zip->entry_bytes_remaining < 1)
zip->end_of_entry = 1;
/* Set up a more descriptive format name. */
archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
version / 10, version % 10,
compression_name(zip->entry->compression));
a->archive.archive_format_name = zip->format_name.s;
return (ret);
}
static int
check_authentication_code(struct archive_read *a, const void *_p)
{
struct zip *zip = (struct zip *)(a->format->data);
/* Check authentication code. */
if (zip->hctx_valid) {
const void *p;
uint8_t hmac[20];
size_t hmac_len = 20;
int cmp;
archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
if (_p == NULL) {
/* Read authentication code. */
p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
if (p == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
} else {
p = _p;
}
cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
__archive_read_consume(a, AUTH_CODE_SIZE);
if (cmp != 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"ZIP bad Authentication code");
return (ARCHIVE_WARN);
}
}
return (ARCHIVE_OK);
}
/*
* Read "uncompressed" data. There are three cases:
* 1) We know the size of the data. This is always true for the
* seeking reader (we've examined the Central Directory already).
* 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
* Info-ZIP seems to do this; we know the size but have to grab
* the CRC from the data descriptor afterwards.
* 3) We're streaming and ZIP_LENGTH_AT_END was specified and
* we have no size information. In this case, we can do pretty
* well by watching for the data descriptor record. The data
* descriptor is 16 bytes and includes a computed CRC that should
* provide a strong check.
*
* TODO: Technically, the PK\007\010 signature is optional.
* In the original spec, the data descriptor contained CRC
* and size fields but had no leading signature. In practice,
* newer writers seem to provide the signature pretty consistently.
*
* For uncompressed data, the PK\007\010 marker seems essential
* to be sure we've actually seen the end of the entry.
*
* Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
* zip->end_of_entry if it consumes all of the data.
*/
static int
zip_read_data_none(struct archive_read *a, const void **_buff,
size_t *size, int64_t *offset)
{
struct zip *zip;
const char *buff;
ssize_t bytes_avail;
int r;
(void)offset; /* UNUSED */
zip = (struct zip *)(a->format->data);
if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
const char *p;
ssize_t grabbing_bytes = 24;
if (zip->hctx_valid)
grabbing_bytes += AUTH_CODE_SIZE;
/* Grab at least 24 bytes. */
buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
if (bytes_avail < grabbing_bytes) {
/* Zip archives have end-of-archive markers
that are longer than this, so a failure to get at
least 24 bytes really does indicate a truncated
file. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
/* Check for a complete PK\007\010 signature, followed
* by the correct 4-byte CRC. */
p = buff;
if (zip->hctx_valid)
p += AUTH_CODE_SIZE;
if (p[0] == 'P' && p[1] == 'K'
&& p[2] == '\007' && p[3] == '\010'
&& (archive_le32dec(p + 4) == zip->entry_crc32
|| zip->ignore_crc32
|| (zip->hctx_valid
&& zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
if (zip->entry->flags & LA_USED_ZIP64) {
zip->entry->crc32 = archive_le32dec(p + 4);
zip->entry->compressed_size =
archive_le64dec(p + 8);
zip->entry->uncompressed_size =
archive_le64dec(p + 16);
zip->unconsumed = 24;
} else {
zip->entry->crc32 = archive_le32dec(p + 4);
zip->entry->compressed_size =
archive_le32dec(p + 8);
zip->entry->uncompressed_size =
archive_le32dec(p + 12);
zip->unconsumed = 16;
}
if (zip->hctx_valid) {
r = check_authentication_code(a, buff);
if (r != ARCHIVE_OK)
return (r);
}
zip->end_of_entry = 1;
return (ARCHIVE_OK);
}
/* If not at EOF, ensure we consume at least one byte. */
++p;
/* Scan forward until we see where a PK\007\010 signature
* might be. */
/* Return bytes up until that point. On the next call,
* the code above will verify the data descriptor. */
while (p < buff + bytes_avail - 4) {
if (p[3] == 'P') { p += 3; }
else if (p[3] == 'K') { p += 2; }
else if (p[3] == '\007') { p += 1; }
else if (p[3] == '\010' && p[2] == '\007'
&& p[1] == 'K' && p[0] == 'P') {
if (zip->hctx_valid)
p -= AUTH_CODE_SIZE;
break;
} else { p += 4; }
}
bytes_avail = p - buff;
} else {
if (zip->entry_bytes_remaining == 0) {
zip->end_of_entry = 1;
if (zip->hctx_valid) {
r = check_authentication_code(a, NULL);
if (r != ARCHIVE_OK)
return (r);
}
return (ARCHIVE_OK);
}
/* Grab a bunch of bytes. */
buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
if (bytes_avail > zip->entry_bytes_remaining)
bytes_avail = (ssize_t)zip->entry_bytes_remaining;
}
if (zip->tctx_valid || zip->cctx_valid) {
size_t dec_size = bytes_avail;
if (dec_size > zip->decrypted_buffer_size)
dec_size = zip->decrypted_buffer_size;
if (zip->tctx_valid) {
trad_enc_decrypt_update(&zip->tctx,
(const uint8_t *)buff, dec_size,
zip->decrypted_buffer, dec_size);
} else {
size_t dsize = dec_size;
archive_hmac_sha1_update(&zip->hctx,
(const uint8_t *)buff, dec_size);
archive_decrypto_aes_ctr_update(&zip->cctx,
(const uint8_t *)buff, dec_size,
zip->decrypted_buffer, &dsize);
}
bytes_avail = dec_size;
buff = (const char *)zip->decrypted_buffer;
}
*size = bytes_avail;
zip->entry_bytes_remaining -= bytes_avail;
zip->entry_uncompressed_bytes_read += bytes_avail;
zip->entry_compressed_bytes_read += bytes_avail;
zip->unconsumed += bytes_avail;
*_buff = buff;
return (ARCHIVE_OK);
}
#ifdef HAVE_ZLIB_H
static int
zip_deflate_init(struct archive_read *a, struct zip *zip)
{
int r;
/* If we haven't yet read any data, initialize the decompressor. */
if (!zip->decompress_init) {
if (zip->stream_valid)
r = inflateReset(&zip->stream);
else
r = inflateInit2(&zip->stream,
-15 /* Don't check for zlib header */);
if (r != Z_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Can't initialize ZIP decompression.");
return (ARCHIVE_FATAL);
}
/* Stream structure has been set up. */
zip->stream_valid = 1;
/* We've initialized decompression for this stream. */
zip->decompress_init = 1;
}
return (ARCHIVE_OK);
}
static int
zip_read_data_deflate(struct archive_read *a, const void **buff,
size_t *size, int64_t *offset)
{
struct zip *zip;
ssize_t bytes_avail;
const void *compressed_buff, *sp;
int r;
(void)offset; /* UNUSED */
zip = (struct zip *)(a->format->data);
/* If the buffer hasn't been allocated, allocate it now. */
if (zip->uncompressed_buffer == NULL) {
zip->uncompressed_buffer_size = 256 * 1024;
zip->uncompressed_buffer
= (unsigned char *)malloc(zip->uncompressed_buffer_size);
if (zip->uncompressed_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for ZIP decompression");
return (ARCHIVE_FATAL);
}
}
r = zip_deflate_init(a, zip);
if (r != ARCHIVE_OK)
return (r);
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
&& bytes_avail > zip->entry_bytes_remaining) {
bytes_avail = (ssize_t)zip->entry_bytes_remaining;
}
if (bytes_avail <= 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file body");
return (ARCHIVE_FATAL);
}
if (zip->tctx_valid || zip->cctx_valid) {
if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
size_t buff_remaining = zip->decrypted_buffer_size
- (zip->decrypted_ptr - zip->decrypted_buffer);
if (buff_remaining > (size_t)bytes_avail)
buff_remaining = (size_t)bytes_avail;
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
zip->entry_bytes_remaining > 0) {
if ((int64_t)(zip->decrypted_bytes_remaining
+ buff_remaining)
> zip->entry_bytes_remaining) {
if (zip->entry_bytes_remaining <
(int64_t)zip->decrypted_bytes_remaining)
buff_remaining = 0;
else
buff_remaining =
(size_t)zip->entry_bytes_remaining
- zip->decrypted_bytes_remaining;
}
}
if (buff_remaining > 0) {
if (zip->tctx_valid) {
trad_enc_decrypt_update(&zip->tctx,
compressed_buff, buff_remaining,
zip->decrypted_ptr
+ zip->decrypted_bytes_remaining,
buff_remaining);
} else {
size_t dsize = buff_remaining;
archive_decrypto_aes_ctr_update(
&zip->cctx,
compressed_buff, buff_remaining,
zip->decrypted_ptr
+ zip->decrypted_bytes_remaining,
&dsize);
}
zip->decrypted_bytes_remaining += buff_remaining;
}
}
bytes_avail = zip->decrypted_bytes_remaining;
compressed_buff = (const char *)zip->decrypted_ptr;
}
/*
* A bug in zlib.h: stream.next_in should be marked 'const'
* but isn't (the library never alters data through the
* next_in pointer, only reads it). The result: this ugly
* cast to remove 'const'.
*/
zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
zip->stream.avail_in = (uInt)bytes_avail;
zip->stream.total_in = 0;
zip->stream.next_out = zip->uncompressed_buffer;
zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
zip->stream.total_out = 0;
r = inflate(&zip->stream, 0);
switch (r) {
case Z_OK:
break;
case Z_STREAM_END:
zip->end_of_entry = 1;
break;
case Z_MEM_ERROR:
archive_set_error(&a->archive, ENOMEM,
"Out of memory for ZIP decompression");
return (ARCHIVE_FATAL);
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP decompression failed (%d)", r);
return (ARCHIVE_FATAL);
}
/* Consume as much as the compressor actually used. */
bytes_avail = zip->stream.total_in;
if (zip->tctx_valid || zip->cctx_valid) {
zip->decrypted_bytes_remaining -= bytes_avail;
if (zip->decrypted_bytes_remaining == 0)
zip->decrypted_ptr = zip->decrypted_buffer;
else
zip->decrypted_ptr += bytes_avail;
}
/* Calculate compressed data as much as we used.*/
if (zip->hctx_valid)
archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
__archive_read_consume(a, bytes_avail);
zip->entry_bytes_remaining -= bytes_avail;
zip->entry_compressed_bytes_read += bytes_avail;
*size = zip->stream.total_out;
zip->entry_uncompressed_bytes_read += zip->stream.total_out;
*buff = zip->uncompressed_buffer;
if (zip->end_of_entry && zip->hctx_valid) {
r = check_authentication_code(a, NULL);
if (r != ARCHIVE_OK)
return (r);
}
if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
const char *p;
if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP end-of-file record");
return (ARCHIVE_FATAL);
}
/* Consume the optional PK\007\010 marker. */
if (p[0] == 'P' && p[1] == 'K' &&
p[2] == '\007' && p[3] == '\010') {
p += 4;
zip->unconsumed = 4;
}
if (zip->entry->flags & LA_USED_ZIP64) {
zip->entry->crc32 = archive_le32dec(p);
zip->entry->compressed_size = archive_le64dec(p + 4);
zip->entry->uncompressed_size = archive_le64dec(p + 12);
zip->unconsumed += 20;
} else {
zip->entry->crc32 = archive_le32dec(p);
zip->entry->compressed_size = archive_le32dec(p + 4);
zip->entry->uncompressed_size = archive_le32dec(p + 8);
zip->unconsumed += 12;
}
}
return (ARCHIVE_OK);
}
#endif
static int
read_decryption_header(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
const char *p;
unsigned int remaining_size;
unsigned int ts;
/*
* Read an initialization vector data field.
*/
p = __archive_read_ahead(a, 2, NULL);
if (p == NULL)
goto truncated;
ts = zip->iv_size;
zip->iv_size = archive_le16dec(p);
__archive_read_consume(a, 2);
if (ts < zip->iv_size) {
free(zip->iv);
zip->iv = NULL;
}
p = __archive_read_ahead(a, zip->iv_size, NULL);
if (p == NULL)
goto truncated;
if (zip->iv == NULL) {
zip->iv = malloc(zip->iv_size);
if (zip->iv == NULL)
goto nomem;
}
memcpy(zip->iv, p, zip->iv_size);
__archive_read_consume(a, zip->iv_size);
/*
* Read a size of remaining decryption header field.
*/
p = __archive_read_ahead(a, 14, NULL);
if (p == NULL)
goto truncated;
remaining_size = archive_le32dec(p);
if (remaining_size < 16 || remaining_size > (1 << 18))
goto corrupted;
/* Check if format version is supported. */
if (archive_le16dec(p+4) != 3) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported encryption format version: %u",
archive_le16dec(p+4));
return (ARCHIVE_FAILED);
}
/*
* Read an encryption algorithm field.
*/
zip->alg_id = archive_le16dec(p+6);
switch (zip->alg_id) {
case 0x6601:/* DES */
case 0x6602:/* RC2 */
case 0x6603:/* 3DES 168 */
case 0x6609:/* 3DES 112 */
case 0x660E:/* AES 128 */
case 0x660F:/* AES 192 */
case 0x6610:/* AES 256 */
case 0x6702:/* RC2 (version >= 5.2) */
case 0x6720:/* Blowfish */
case 0x6721:/* Twofish */
case 0x6801:/* RC4 */
/* Suuported encryption algorithm. */
break;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown encryption algorithm: %u", zip->alg_id);
return (ARCHIVE_FAILED);
}
/*
* Read a bit length field.
*/
zip->bit_len = archive_le16dec(p+8);
/*
* Read a flags field.
*/
zip->flags = archive_le16dec(p+10);
switch (zip->flags & 0xf000) {
case 0x0001: /* Password is required to decrypt. */
case 0x0002: /* Certificates only. */
case 0x0003: /* Password or certificate required to decrypt. */
break;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown encryption flag: %u", zip->flags);
return (ARCHIVE_FAILED);
}
if ((zip->flags & 0xf000) == 0 ||
(zip->flags & 0xf000) == 0x4000) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown encryption flag: %u", zip->flags);
return (ARCHIVE_FAILED);
}
/*
* Read an encrypted random data field.
*/
ts = zip->erd_size;
zip->erd_size = archive_le16dec(p+12);
__archive_read_consume(a, 14);
if ((zip->erd_size & 0xf) != 0 ||
(zip->erd_size + 16) > remaining_size ||
(zip->erd_size + 16) < zip->erd_size)
goto corrupted;
if (ts < zip->erd_size) {
free(zip->erd);
zip->erd = NULL;
}
p = __archive_read_ahead(a, zip->erd_size, NULL);
if (p == NULL)
goto truncated;
if (zip->erd == NULL) {
zip->erd = malloc(zip->erd_size);
if (zip->erd == NULL)
goto nomem;
}
memcpy(zip->erd, p, zip->erd_size);
__archive_read_consume(a, zip->erd_size);
/*
* Read a reserved data field.
*/
p = __archive_read_ahead(a, 4, NULL);
if (p == NULL)
goto truncated;
/* Reserved data size should be zero. */
if (archive_le32dec(p) != 0)
goto corrupted;
__archive_read_consume(a, 4);
/*
* Read a password validation data field.
*/
p = __archive_read_ahead(a, 2, NULL);
if (p == NULL)
goto truncated;
ts = zip->v_size;
zip->v_size = archive_le16dec(p);
__archive_read_consume(a, 2);
if ((zip->v_size & 0x0f) != 0 ||
(zip->erd_size + zip->v_size + 16) > remaining_size ||
(zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
goto corrupted;
if (ts < zip->v_size) {
free(zip->v_data);
zip->v_data = NULL;
}
p = __archive_read_ahead(a, zip->v_size, NULL);
if (p == NULL)
goto truncated;
if (zip->v_data == NULL) {
zip->v_data = malloc(zip->v_size);
if (zip->v_data == NULL)
goto nomem;
}
memcpy(zip->v_data, p, zip->v_size);
__archive_read_consume(a, zip->v_size);
p = __archive_read_ahead(a, 4, NULL);
if (p == NULL)
goto truncated;
zip->v_crc32 = archive_le32dec(p);
__archive_read_consume(a, 4);
/*return (ARCHIVE_OK);
* This is not fully implemnted yet.*/
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Encrypted file is unsupported");
return (ARCHIVE_FAILED);
truncated:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
corrupted:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Corrupted ZIP file data");
return (ARCHIVE_FATAL);
nomem:
archive_set_error(&a->archive, ENOMEM,
"No memory for ZIP decryption");
return (ARCHIVE_FATAL);
}
static int
zip_alloc_decryption_buffer(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
size_t bs = 256 * 1024;
if (zip->decrypted_buffer == NULL) {
zip->decrypted_buffer_size = bs;
zip->decrypted_buffer = malloc(bs);
if (zip->decrypted_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for ZIP decryption");
return (ARCHIVE_FATAL);
}
}
zip->decrypted_ptr = zip->decrypted_buffer;
return (ARCHIVE_OK);
}
static int
init_traditional_PKWARE_decryption(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
const void *p;
int retry;
int r;
if (zip->tctx_valid)
return (ARCHIVE_OK);
/*
Read the 12 bytes encryption header stored at
the start of the data area.
*/
#define ENC_HEADER_SIZE 12
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
&& zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated Zip encrypted body: only %jd bytes available",
(intmax_t)zip->entry_bytes_remaining);
return (ARCHIVE_FATAL);
}
p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
if (p == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
for (retry = 0;; retry++) {
const char *passphrase;
uint8_t crcchk;
passphrase = __archive_read_next_passphrase(a);
if (passphrase == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
(retry > 0)?
"Incorrect passphrase":
"Passphrase required for this entry");
return (ARCHIVE_FAILED);
}
/*
* Initialize ctx for Traditional PKWARE Decyption.
*/
r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
p, ENC_HEADER_SIZE, &crcchk);
if (r == 0 && crcchk == zip->entry->decdat)
break;/* The passphrase is OK. */
if (retry > 10000) {
/* Avoid infinity loop. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Too many incorrect passphrases");
return (ARCHIVE_FAILED);
}
}
__archive_read_consume(a, ENC_HEADER_SIZE);
zip->tctx_valid = 1;
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
}
/*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
zip->decrypted_bytes_remaining = 0;
return (zip_alloc_decryption_buffer(a));
#undef ENC_HEADER_SIZE
}
static int
init_WinZip_AES_decryption(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
const void *p;
const uint8_t *pv;
size_t key_len, salt_len;
uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
int retry;
int r;
if (zip->cctx_valid || zip->hctx_valid)
return (ARCHIVE_OK);
switch (zip->entry->aes_extra.strength) {
case 1: salt_len = 8; key_len = 16; break;
case 2: salt_len = 12; key_len = 24; break;
case 3: salt_len = 16; key_len = 32; break;
default: goto corrupted;
}
p = __archive_read_ahead(a, salt_len + 2, NULL);
if (p == NULL)
goto truncated;
for (retry = 0;; retry++) {
const char *passphrase;
passphrase = __archive_read_next_passphrase(a);
if (passphrase == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
(retry > 0)?
"Incorrect passphrase":
"Passphrase required for this entry");
return (ARCHIVE_FAILED);
}
memset(derived_key, 0, sizeof(derived_key));
r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
p, salt_len, 1000, derived_key, key_len * 2 + 2);
if (r != 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Decryption is unsupported due to lack of "
"crypto library");
return (ARCHIVE_FAILED);
}
/* Check password verification value. */
pv = ((const uint8_t *)p) + salt_len;
if (derived_key[key_len * 2] == pv[0] &&
derived_key[key_len * 2 + 1] == pv[1])
break;/* The passphrase is OK. */
if (retry > 10000) {
/* Avoid infinity loop. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Too many incorrect passphrases");
return (ARCHIVE_FAILED);
}
}
r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
if (r != 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Decryption is unsupported due to lack of crypto library");
return (ARCHIVE_FAILED);
}
r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
if (r != 0) {
archive_decrypto_aes_ctr_release(&zip->cctx);
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to initialize HMAC-SHA1");
return (ARCHIVE_FAILED);
}
zip->cctx_valid = zip->hctx_valid = 1;
__archive_read_consume(a, salt_len + 2);
zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
&& zip->entry_bytes_remaining < 0)
goto corrupted;
zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
zip->decrypted_bytes_remaining = 0;
zip->entry->compression = zip->entry->aes_extra.compression;
return (zip_alloc_decryption_buffer(a));
truncated:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
corrupted:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Corrupted ZIP file data");
return (ARCHIVE_FATAL);
}
static int
archive_read_format_zip_read_data(struct archive_read *a,
const void **buff, size_t *size, int64_t *offset)
{
int r;
struct zip *zip = (struct zip *)(a->format->data);
if (zip->has_encrypted_entries ==
ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
zip->has_encrypted_entries = 0;
}
*offset = zip->entry_uncompressed_bytes_read;
*size = 0;
*buff = NULL;
/* If we hit end-of-entry last time, return ARCHIVE_EOF. */
if (zip->end_of_entry)
return (ARCHIVE_EOF);
/* Return EOF immediately if this is a non-regular file. */
if (AE_IFREG != (zip->entry->mode & AE_IFMT))
return (ARCHIVE_EOF);
__archive_read_consume(a, zip->unconsumed);
zip->unconsumed = 0;
if (zip->init_decryption) {
zip->has_encrypted_entries = 1;
if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
r = read_decryption_header(a);
else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
r = init_WinZip_AES_decryption(a);
else
r = init_traditional_PKWARE_decryption(a);
if (r != ARCHIVE_OK)
return (r);
zip->init_decryption = 0;
}
switch(zip->entry->compression) {
case 0: /* No compression. */
r = zip_read_data_none(a, buff, size, offset);
break;
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
r = zip_read_data_deflate(a, buff, size, offset);
break;
#endif
default: /* Unsupported compression. */
/* Return a warning. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported ZIP compression method (%s)",
compression_name(zip->entry->compression));
/* We can't decompress this entry, but we will
* be able to skip() it and try the next entry. */
return (ARCHIVE_FAILED);
break;
}
if (r != ARCHIVE_OK)
return (r);
/* Update checksum */
if (*size)
zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
(unsigned)*size);
/* If we hit the end, swallow any end-of-data marker. */
if (zip->end_of_entry) {
/* Check file size, CRC against these values. */
if (zip->entry->compressed_size !=
zip->entry_compressed_bytes_read) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP compressed data is wrong size "
"(read %jd, expected %jd)",
(intmax_t)zip->entry_compressed_bytes_read,
(intmax_t)zip->entry->compressed_size);
return (ARCHIVE_WARN);
}
/* Size field only stores the lower 32 bits of the actual
* size. */
if ((zip->entry->uncompressed_size & UINT32_MAX)
!= (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP uncompressed data is wrong size "
"(read %jd, expected %jd)\n",
(intmax_t)zip->entry_uncompressed_bytes_read,
(intmax_t)zip->entry->uncompressed_size);
return (ARCHIVE_WARN);
}
/* Check computed CRC against header */
if ((!zip->hctx_valid ||
zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
zip->entry->crc32 != zip->entry_crc32
&& !zip->ignore_crc32) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP bad CRC: 0x%lx should be 0x%lx",
(unsigned long)zip->entry_crc32,
(unsigned long)zip->entry->crc32);
return (ARCHIVE_WARN);
}
}
return (ARCHIVE_OK);
}
static int
archive_read_format_zip_cleanup(struct archive_read *a)
{
struct zip *zip;
struct zip_entry *zip_entry, *next_zip_entry;
zip = (struct zip *)(a->format->data);
#ifdef HAVE_ZLIB_H
if (zip->stream_valid)
inflateEnd(&zip->stream);
free(zip->uncompressed_buffer);
#endif
if (zip->zip_entries) {
zip_entry = zip->zip_entries;
while (zip_entry != NULL) {
next_zip_entry = zip_entry->next;
archive_string_free(&zip_entry->rsrcname);
free(zip_entry);
zip_entry = next_zip_entry;
}
}
free(zip->decrypted_buffer);
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
free(zip->iv);
free(zip->erd);
free(zip->v_data);
archive_string_free(&zip->format_name);
free(zip);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
static int
archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
{
if (_a && _a->format) {
struct zip * zip = (struct zip *)_a->format->data;
if (zip) {
return zip->has_encrypted_entries;
}
}
return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
}
static int
archive_read_format_zip_options(struct archive_read *a,
const char *key, const char *val)
{
struct zip *zip;
int ret = ARCHIVE_FAILED;
zip = (struct zip *)(a->format->data);
if (strcmp(key, "compat-2x") == 0) {
/* Handle filenames as libarchive 2.x */
zip->init_default_conversion = (val != NULL) ? 1 : 0;
return (ARCHIVE_OK);
} else if (strcmp(key, "hdrcharset") == 0) {
if (val == NULL || val[0] == 0)
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"zip: hdrcharset option needs a character-set name"
);
else {
zip->sconv = archive_string_conversion_from_charset(
&a->archive, val, 0);
if (zip->sconv != NULL) {
if (strcmp(val, "UTF-8") == 0)
zip->sconv_utf8 = zip->sconv;
ret = ARCHIVE_OK;
} else
ret = ARCHIVE_FATAL;
}
return (ret);
} else if (strcmp(key, "ignorecrc32") == 0) {
/* Mostly useful for testing. */
if (val == NULL || val[0] == 0) {
zip->crc32func = real_crc32;
zip->ignore_crc32 = 0;
} else {
zip->crc32func = fake_crc32;
zip->ignore_crc32 = 1;
}
return (ARCHIVE_OK);
} else if (strcmp(key, "mac-ext") == 0) {
zip->process_mac_extensions = (val != NULL && val[0] != 0);
return (ARCHIVE_OK);
}
/* Note: The "warn" return is just to inform the options
* supervisor that we didn't handle it. It will generate
* a suitable error if no one used this option. */
return (ARCHIVE_WARN);
}
int
archive_read_support_format_zip(struct archive *a)
{
int r;
r = archive_read_support_format_zip_streamable(a);
if (r != ARCHIVE_OK)
return r;
return (archive_read_support_format_zip_seekable(a));
}
/* ------------------------------------------------------------------------ */
/*
* Streaming-mode support
*/
static int
archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
{
(void)a; /* UNUSED */
return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
}
static int
archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
{
const char *p;
(void)best_bid; /* UNUSED */
if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
return (-1);
/*
* Bid of 29 here comes from:
* + 16 bits for "PK",
* + next 16-bit field has 6 options so contributes
* about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
*
* So we've effectively verified ~29 total bits of check data.
*/
if (p[0] == 'P' && p[1] == 'K') {
if ((p[2] == '\001' && p[3] == '\002')
|| (p[2] == '\003' && p[3] == '\004')
|| (p[2] == '\005' && p[3] == '\006')
|| (p[2] == '\006' && p[3] == '\006')
|| (p[2] == '\007' && p[3] == '\010')
|| (p[2] == '0' && p[3] == '0'))
return (29);
}
/* TODO: It's worth looking ahead a little bit for a valid
* PK signature. In particular, that would make it possible
* to read some UUEncoded SFX files or SFX files coming from
* a network socket. */
return (0);
}
static int
archive_read_format_zip_streamable_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct zip *zip;
a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
if (a->archive.archive_format_name == NULL)
a->archive.archive_format_name = "ZIP";
zip = (struct zip *)(a->format->data);
/*
* It should be sufficient to call archive_read_next_header() for
* a reader to determine if an entry is encrypted or not. If the
* encryption of an entry is only detectable when calling
* archive_read_data(), so be it. We'll do the same check there
* as well.
*/
if (zip->has_encrypted_entries ==
ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
zip->has_encrypted_entries = 0;
/* Make sure we have a zip_entry structure to use. */
if (zip->zip_entries == NULL) {
zip->zip_entries = malloc(sizeof(struct zip_entry));
if (zip->zip_entries == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Out of memory");
return ARCHIVE_FATAL;
}
}
zip->entry = zip->zip_entries;
memset(zip->entry, 0, sizeof(struct zip_entry));
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
__archive_read_reset_passphrase(a);
/* Search ahead for the next local file header. */
__archive_read_consume(a, zip->unconsumed);
zip->unconsumed = 0;
for (;;) {
int64_t skipped = 0;
const char *p, *end;
ssize_t bytes;
p = __archive_read_ahead(a, 4, &bytes);
if (p == NULL)
return (ARCHIVE_FATAL);
end = p + bytes;
while (p + 4 <= end) {
if (p[0] == 'P' && p[1] == 'K') {
if (p[2] == '\003' && p[3] == '\004') {
/* Regular file entry. */
__archive_read_consume(a, skipped);
return zip_read_local_file_header(a,
entry, zip);
}
/*
* TODO: We cannot restore permissions
* based only on the local file headers.
* Consider scanning the central
* directory and returning additional
* entries for at least directories.
* This would allow us to properly set
* directory permissions.
*
* This won't help us fix symlinks
* and may not help with regular file
* permissions, either. <sigh>
*/
if (p[2] == '\001' && p[3] == '\002') {
return (ARCHIVE_EOF);
}
/* End of central directory? Must be an
* empty archive. */
if ((p[2] == '\005' && p[3] == '\006')
|| (p[2] == '\006' && p[3] == '\006'))
return (ARCHIVE_EOF);
}
++p;
++skipped;
}
__archive_read_consume(a, skipped);
}
}
static int
archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
{
struct zip *zip;
int64_t bytes_skipped;
zip = (struct zip *)(a->format->data);
bytes_skipped = __archive_read_consume(a, zip->unconsumed);
zip->unconsumed = 0;
if (bytes_skipped < 0)
return (ARCHIVE_FATAL);
/* If we've already read to end of data, we're done. */
if (zip->end_of_entry)
return (ARCHIVE_OK);
/* So we know we're streaming... */
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
|| zip->entry->compressed_size > 0) {
/* We know the compressed length, so we can just skip. */
bytes_skipped = __archive_read_consume(a,
zip->entry_bytes_remaining);
if (bytes_skipped < 0)
return (ARCHIVE_FATAL);
return (ARCHIVE_OK);
}
if (zip->init_decryption) {
int r;
zip->has_encrypted_entries = 1;
if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
r = read_decryption_header(a);
else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
r = init_WinZip_AES_decryption(a);
else
r = init_traditional_PKWARE_decryption(a);
if (r != ARCHIVE_OK)
return (r);
zip->init_decryption = 0;
}
/* We're streaming and we don't know the length. */
/* If the body is compressed and we know the format, we can
* find an exact end-of-entry by decompressing it. */
switch (zip->entry->compression) {
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
while (!zip->end_of_entry) {
int64_t offset = 0;
const void *buff = NULL;
size_t size = 0;
int r;
r = zip_read_data_deflate(a, &buff, &size, &offset);
if (r != ARCHIVE_OK)
return (r);
}
return ARCHIVE_OK;
#endif
default: /* Uncompressed or unknown. */
/* Scan for a PK\007\010 signature. */
for (;;) {
const char *p, *buff;
ssize_t bytes_avail;
buff = __archive_read_ahead(a, 16, &bytes_avail);
if (bytes_avail < 16) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
p = buff;
while (p <= buff + bytes_avail - 16) {
if (p[3] == 'P') { p += 3; }
else if (p[3] == 'K') { p += 2; }
else if (p[3] == '\007') { p += 1; }
else if (p[3] == '\010' && p[2] == '\007'
&& p[1] == 'K' && p[0] == 'P') {
if (zip->entry->flags & LA_USED_ZIP64)
__archive_read_consume(a,
p - buff + 24);
else
__archive_read_consume(a,
p - buff + 16);
return ARCHIVE_OK;
} else { p += 4; }
}
__archive_read_consume(a, p - buff);
}
}
}
int
archive_read_support_format_zip_streamable(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
struct zip *zip;
int r;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
zip = (struct zip *)calloc(1, sizeof(*zip));
if (zip == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate zip data");
return (ARCHIVE_FATAL);
}
/* Streamable reader doesn't support mac extensions. */
zip->process_mac_extensions = 0;
/*
* Until enough data has been read, we cannot tell about
* any encrypted entries yet.
*/
zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
zip->crc32func = real_crc32;
r = __archive_read_register_format(a,
zip,
"zip",
archive_read_format_zip_streamable_bid,
archive_read_format_zip_options,
archive_read_format_zip_streamable_read_header,
archive_read_format_zip_read_data,
archive_read_format_zip_read_data_skip_streamable,
NULL,
archive_read_format_zip_cleanup,
archive_read_support_format_zip_capabilities_streamable,
archive_read_format_zip_has_encrypted_entries);
if (r != ARCHIVE_OK)
free(zip);
return (ARCHIVE_OK);
}
/* ------------------------------------------------------------------------ */
/*
* Seeking-mode support
*/
static int
archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
{
(void)a; /* UNUSED */
return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
}
/*
* TODO: This is a performance sink because it forces the read core to
* drop buffered data from the start of file, which will then have to
* be re-read again if this bidder loses.
*
* We workaround this a little by passing in the best bid so far so
* that later bidders can do nothing if they know they'll never
* outbid. But we can certainly do better...
*/
static int
read_eocd(struct zip *zip, const char *p, int64_t current_offset)
{
/* Sanity-check the EOCD we've found. */
/* This must be the first volume. */
if (archive_le16dec(p + 4) != 0)
return 0;
/* Central directory must be on this volume. */
if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
return 0;
/* All central directory entries must be on this volume. */
if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
return 0;
/* Central directory can't extend beyond start of EOCD record. */
if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
> current_offset)
return 0;
/* Save the central directory location for later use. */
zip->central_directory_offset = archive_le32dec(p + 16);
/* This is just a tiny bit higher than the maximum
returned by the streaming Zip bidder. This ensures
that the more accurate seeking Zip parser wins
whenever seek is available. */
return 32;
}
/*
* Examine Zip64 EOCD locator: If it's valid, store the information
* from it.
*/
static void
read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
{
int64_t eocd64_offset;
int64_t eocd64_size;
/* Sanity-check the locator record. */
/* Central dir must be on first volume. */
if (archive_le32dec(p + 4) != 0)
return;
/* Must be only a single volume. */
if (archive_le32dec(p + 16) != 1)
return;
/* Find the Zip64 EOCD record. */
eocd64_offset = archive_le64dec(p + 8);
if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
return;
if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
return;
/* Make sure we can read all of it. */
eocd64_size = archive_le64dec(p + 4) + 12;
if (eocd64_size < 56 || eocd64_size > 16384)
return;
if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
return;
/* Sanity-check the EOCD64 */
if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
return;
if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
return;
/* CD can't be split. */
if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
return;
/* Save the central directory offset for later use. */
zip->central_directory_offset = archive_le64dec(p + 48);
}
static int
archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
{
struct zip *zip = (struct zip *)a->format->data;
int64_t file_size, current_offset;
const char *p;
int i, tail;
/* If someone has already bid more than 32, then avoid
trashing the look-ahead buffers with a seek. */
if (best_bid > 32)
return (-1);
file_size = __archive_read_seek(a, 0, SEEK_END);
if (file_size <= 0)
return 0;
/* Search last 16k of file for end-of-central-directory
* record (which starts with PK\005\006) */
tail = (int)zipmin(1024 * 16, file_size);
current_offset = __archive_read_seek(a, -tail, SEEK_END);
if (current_offset < 0)
return 0;
if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
return 0;
/* Boyer-Moore search backwards from the end, since we want
* to match the last EOCD in the file (there can be more than
* one if there is an uncompressed Zip archive as a member
* within this Zip archive). */
for (i = tail - 22; i > 0;) {
switch (p[i]) {
case 'P':
if (memcmp(p + i, "PK\005\006", 4) == 0) {
int ret = read_eocd(zip, p + i,
current_offset + i);
if (ret > 0) {
/* Zip64 EOCD locator precedes
* regular EOCD if present. */
if (i >= 20
&& memcmp(p + i - 20, "PK\006\007", 4) == 0) {
read_zip64_eocd(a, zip, p + i - 20);
}
return (ret);
}
}
i -= 4;
break;
case 'K': i -= 1; break;
case 005: i -= 2; break;
case 006: i -= 3; break;
default: i -= 4; break;
}
}
return 0;
}
/* The red-black trees are only used in seeking mode to manage
* the in-memory copy of the central directory. */
static int
cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
{
const struct zip_entry *e1 = (const struct zip_entry *)n1;
const struct zip_entry *e2 = (const struct zip_entry *)n2;
if (e1->local_header_offset > e2->local_header_offset)
return -1;
if (e1->local_header_offset < e2->local_header_offset)
return 1;
return 0;
}
static int
cmp_key(const struct archive_rb_node *n, const void *key)
{
/* This function won't be called */
(void)n; /* UNUSED */
(void)key; /* UNUSED */
return 1;
}
static const struct archive_rb_tree_ops rb_ops = {
&cmp_node, &cmp_key
};
static int
rsrc_cmp_node(const struct archive_rb_node *n1,
const struct archive_rb_node *n2)
{
const struct zip_entry *e1 = (const struct zip_entry *)n1;
const struct zip_entry *e2 = (const struct zip_entry *)n2;
return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
}
static int
rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
{
const struct zip_entry *e = (const struct zip_entry *)n;
return (strcmp((const char *)key, e->rsrcname.s));
}
static const struct archive_rb_tree_ops rb_rsrc_ops = {
&rsrc_cmp_node, &rsrc_cmp_key
};
static const char *
rsrc_basename(const char *name, size_t name_length)
{
const char *s, *r;
r = s = name;
for (;;) {
s = memchr(s, '/', name_length - (s - name));
if (s == NULL)
break;
r = ++s;
}
return (r);
}
static void
expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
{
struct archive_string str;
struct zip_entry *dir;
char *s;
archive_string_init(&str);
archive_strncpy(&str, name, name_length);
for (;;) {
s = strrchr(str.s, '/');
if (s == NULL)
break;
*s = '\0';
/* Transfer the parent directory from zip->tree_rsrc RB
* tree to zip->tree RB tree to expose. */
dir = (struct zip_entry *)
__archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
if (dir == NULL)
break;
__archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
archive_string_free(&dir->rsrcname);
__archive_rb_tree_insert_node(&zip->tree, &dir->node);
}
archive_string_free(&str);
}
static int
slurp_central_directory(struct archive_read *a, struct zip *zip)
{
ssize_t i;
unsigned found;
int64_t correction;
ssize_t bytes_avail;
const char *p;
/*
* Find the start of the central directory. The end-of-CD
* record has our starting point, but there are lots of
* Zip archives which have had other data prepended to the
* file, which makes the recorded offsets all too small.
* So we search forward from the specified offset until we
* find the real start of the central directory. Then we
* know the correction we need to apply to account for leading
* padding.
*/
if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
return ARCHIVE_FATAL;
found = 0;
while (!found) {
if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
return ARCHIVE_FATAL;
for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
switch (p[i + 3]) {
case 'P': i += 3; break;
case 'K': i += 2; break;
case 001: i += 1; break;
case 002:
if (memcmp(p + i, "PK\001\002", 4) == 0) {
p += i;
found = 1;
} else
i += 4;
break;
case 005: i += 1; break;
case 006:
if (memcmp(p + i, "PK\005\006", 4) == 0) {
p += i;
found = 1;
} else if (memcmp(p + i, "PK\006\006", 4) == 0) {
p += i;
found = 1;
} else
i += 1;
break;
default: i += 4; break;
}
}
__archive_read_consume(a, i);
}
correction = archive_filter_bytes(&a->archive, 0)
- zip->central_directory_offset;
__archive_rb_tree_init(&zip->tree, &rb_ops);
__archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
zip->central_directory_entries_total = 0;
while (1) {
struct zip_entry *zip_entry;
size_t filename_length, extra_length, comment_length;
uint32_t external_attributes;
const char *name, *r;
if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
return ARCHIVE_FATAL;
if (memcmp(p, "PK\006\006", 4) == 0
|| memcmp(p, "PK\005\006", 4) == 0) {
break;
} else if (memcmp(p, "PK\001\002", 4) != 0) {
archive_set_error(&a->archive,
-1, "Invalid central directory signature");
return ARCHIVE_FATAL;
}
if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
return ARCHIVE_FATAL;
zip_entry = calloc(1, sizeof(struct zip_entry));
zip_entry->next = zip->zip_entries;
zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
zip->zip_entries = zip_entry;
zip->central_directory_entries_total++;
/* version = p[4]; */
zip_entry->system = p[5];
/* version_required = archive_le16dec(p + 6); */
zip_entry->zip_flags = archive_le16dec(p + 8);
if (zip_entry->zip_flags
& (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
zip->has_encrypted_entries = 1;
}
zip_entry->compression = (char)archive_le16dec(p + 10);
zip_entry->mtime = zip_time(p + 12);
zip_entry->crc32 = archive_le32dec(p + 16);
if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
zip_entry->decdat = p[13];
else
zip_entry->decdat = p[19];
zip_entry->compressed_size = archive_le32dec(p + 20);
zip_entry->uncompressed_size = archive_le32dec(p + 24);
filename_length = archive_le16dec(p + 28);
extra_length = archive_le16dec(p + 30);
comment_length = archive_le16dec(p + 32);
/* disk_start = archive_le16dec(p + 34); */ /* Better be zero. */
/* internal_attributes = archive_le16dec(p + 36); */ /* text bit */
external_attributes = archive_le32dec(p + 38);
zip_entry->local_header_offset =
archive_le32dec(p + 42) + correction;
/* If we can't guess the mode, leave it zero here;
when we read the local file header we might get
more information. */
if (zip_entry->system == 3) {
zip_entry->mode = external_attributes >> 16;
} else if (zip_entry->system == 0) {
// Interpret MSDOS directory bit
if (0x10 == (external_attributes & 0x10)) {
zip_entry->mode = AE_IFDIR | 0775;
} else {
zip_entry->mode = AE_IFREG | 0664;
}
if (0x01 == (external_attributes & 0x01)) {
// Read-only bit; strip write permissions
zip_entry->mode &= 0555;
}
} else {
zip_entry->mode = 0;
}
/* We're done with the regular data; get the filename and
* extra data. */
__archive_read_consume(a, 46);
p = __archive_read_ahead(a, filename_length + extra_length,
NULL);
if (p == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return ARCHIVE_FATAL;
}
process_extra(p + filename_length, extra_length, zip_entry);
/*
* Mac resource fork files are stored under the
* "__MACOSX/" directory, so we should check if
* it is.
*/
if (!zip->process_mac_extensions) {
/* Treat every entry as a regular entry. */
__archive_rb_tree_insert_node(&zip->tree,
&zip_entry->node);
} else {
name = p;
r = rsrc_basename(name, filename_length);
if (filename_length >= 9 &&
strncmp("__MACOSX/", name, 9) == 0) {
/* If this file is not a resource fork nor
* a directory. We should treat it as a non
* resource fork file to expose it. */
if (name[filename_length-1] != '/' &&
(r - name < 3 || r[0] != '.' || r[1] != '_')) {
__archive_rb_tree_insert_node(
&zip->tree, &zip_entry->node);
/* Expose its parent directories. */
expose_parent_dirs(zip, name,
filename_length);
} else {
/* This file is a resource fork file or
* a directory. */
archive_strncpy(&(zip_entry->rsrcname),
name, filename_length);
__archive_rb_tree_insert_node(
&zip->tree_rsrc, &zip_entry->node);
}
} else {
/* Generate resource fork name to find its
* resource file at zip->tree_rsrc. */
archive_strcpy(&(zip_entry->rsrcname),
"__MACOSX/");
archive_strncat(&(zip_entry->rsrcname),
name, r - name);
archive_strcat(&(zip_entry->rsrcname), "._");
archive_strncat(&(zip_entry->rsrcname),
name + (r - name),
filename_length - (r - name));
/* Register an entry to RB tree to sort it by
* file offset. */
__archive_rb_tree_insert_node(&zip->tree,
&zip_entry->node);
}
}
/* Skip the comment too ... */
__archive_read_consume(a,
filename_length + extra_length + comment_length);
}
return ARCHIVE_OK;
}
static ssize_t
zip_get_local_file_header_size(struct archive_read *a, size_t extra)
{
const char *p;
ssize_t filename_length, extra_length;
if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_WARN);
}
p += extra;
if (memcmp(p, "PK\003\004", 4) != 0) {
archive_set_error(&a->archive, -1, "Damaged Zip archive");
return ARCHIVE_WARN;
}
filename_length = archive_le16dec(p + 26);
extra_length = archive_le16dec(p + 28);
return (30 + filename_length + extra_length);
}
static int
zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
struct zip_entry *rsrc)
{
struct zip *zip = (struct zip *)a->format->data;
unsigned char *metadata, *mp;
int64_t offset = archive_filter_bytes(&a->archive, 0);
size_t remaining_bytes, metadata_bytes;
ssize_t hsize;
int ret = ARCHIVE_OK, eof;
switch(rsrc->compression) {
case 0: /* No compression. */
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
#endif
break;
default: /* Unsupported compression. */
/* Return a warning. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported ZIP compression method (%s)",
compression_name(rsrc->compression));
/* We can't decompress this entry, but we will
* be able to skip() it and try the next entry. */
return (ARCHIVE_WARN);
}
if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Mac metadata is too large: %jd > 4M bytes",
(intmax_t)rsrc->uncompressed_size);
return (ARCHIVE_WARN);
}
metadata = malloc((size_t)rsrc->uncompressed_size);
if (metadata == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Mac metadata");
return (ARCHIVE_FATAL);
}
if (offset < rsrc->local_header_offset)
__archive_read_consume(a, rsrc->local_header_offset - offset);
else if (offset != rsrc->local_header_offset) {
__archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
}
hsize = zip_get_local_file_header_size(a, 0);
__archive_read_consume(a, hsize);
remaining_bytes = (size_t)rsrc->compressed_size;
metadata_bytes = (size_t)rsrc->uncompressed_size;
mp = metadata;
eof = 0;
while (!eof && remaining_bytes) {
const unsigned char *p;
ssize_t bytes_avail;
size_t bytes_used;
p = __archive_read_ahead(a, 1, &bytes_avail);
if (p == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
ret = ARCHIVE_WARN;
goto exit_mac_metadata;
}
if ((size_t)bytes_avail > remaining_bytes)
bytes_avail = remaining_bytes;
switch(rsrc->compression) {
case 0: /* No compression. */
memcpy(mp, p, bytes_avail);
bytes_used = (size_t)bytes_avail;
metadata_bytes -= bytes_used;
mp += bytes_used;
if (metadata_bytes == 0)
eof = 1;
break;
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
{
int r;
ret = zip_deflate_init(a, zip);
if (ret != ARCHIVE_OK)
goto exit_mac_metadata;
zip->stream.next_in =
(Bytef *)(uintptr_t)(const void *)p;
zip->stream.avail_in = (uInt)bytes_avail;
zip->stream.total_in = 0;
zip->stream.next_out = mp;
zip->stream.avail_out = (uInt)metadata_bytes;
zip->stream.total_out = 0;
r = inflate(&zip->stream, 0);
switch (r) {
case Z_OK:
break;
case Z_STREAM_END:
eof = 1;
break;
case Z_MEM_ERROR:
archive_set_error(&a->archive, ENOMEM,
"Out of memory for ZIP decompression");
ret = ARCHIVE_FATAL;
goto exit_mac_metadata;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"ZIP decompression failed (%d)", r);
ret = ARCHIVE_FATAL;
goto exit_mac_metadata;
}
bytes_used = zip->stream.total_in;
metadata_bytes -= zip->stream.total_out;
mp += zip->stream.total_out;
break;
}
#endif
default:
bytes_used = 0;
break;
}
__archive_read_consume(a, bytes_used);
remaining_bytes -= bytes_used;
}
archive_entry_copy_mac_metadata(entry, metadata,
(size_t)rsrc->uncompressed_size - metadata_bytes);
exit_mac_metadata:
__archive_read_seek(a, offset, SEEK_SET);
zip->decompress_init = 0;
free(metadata);
return (ret);
}
static int
archive_read_format_zip_seekable_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct zip *zip = (struct zip *)a->format->data;
struct zip_entry *rsrc;
int64_t offset;
int r, ret = ARCHIVE_OK;
/*
* It should be sufficient to call archive_read_next_header() for
* a reader to determine if an entry is encrypted or not. If the
* encryption of an entry is only detectable when calling
* archive_read_data(), so be it. We'll do the same check there
* as well.
*/
if (zip->has_encrypted_entries ==
ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
zip->has_encrypted_entries = 0;
a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
if (a->archive.archive_format_name == NULL)
a->archive.archive_format_name = "ZIP";
if (zip->zip_entries == NULL) {
r = slurp_central_directory(a, zip);
if (r != ARCHIVE_OK)
return r;
/* Get first entry whose local header offset is lower than
* other entries in the archive file. */
zip->entry =
(struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
} else if (zip->entry != NULL) {
/* Get next entry in local header offset order. */
zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
&zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
}
if (zip->entry == NULL)
return ARCHIVE_EOF;
if (zip->entry->rsrcname.s)
rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
&zip->tree_rsrc, zip->entry->rsrcname.s);
else
rsrc = NULL;
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
__archive_read_reset_passphrase(a);
/* File entries are sorted by the header offset, we should mostly
* use __archive_read_consume to advance a read point to avoid redundant
* data reading. */
offset = archive_filter_bytes(&a->archive, 0);
if (offset < zip->entry->local_header_offset)
__archive_read_consume(a,
zip->entry->local_header_offset - offset);
else if (offset != zip->entry->local_header_offset) {
__archive_read_seek(a, zip->entry->local_header_offset,
SEEK_SET);
}
zip->unconsumed = 0;
r = zip_read_local_file_header(a, entry, zip);
if (r != ARCHIVE_OK)
return r;
if (rsrc) {
int ret2 = zip_read_mac_metadata(a, entry, rsrc);
if (ret2 < ret)
ret = ret2;
}
return (ret);
}
/*
* We're going to seek for the next header anyway, so we don't
* need to bother doing anything here.
*/
static int
archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
{
struct zip *zip;
zip = (struct zip *)(a->format->data);
zip->unconsumed = 0;
return (ARCHIVE_OK);
}
int
archive_read_support_format_zip_seekable(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
struct zip *zip;
int r;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
zip = (struct zip *)calloc(1, sizeof(*zip));
if (zip == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate zip data");
return (ARCHIVE_FATAL);
}
#ifdef HAVE_COPYFILE_H
/* Set this by default on Mac OS. */
zip->process_mac_extensions = 1;
#endif
/*
* Until enough data has been read, we cannot tell about
* any encrypted entries yet.
*/
zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
zip->crc32func = real_crc32;
r = __archive_read_register_format(a,
zip,
"zip",
archive_read_format_zip_seekable_bid,
archive_read_format_zip_options,
archive_read_format_zip_seekable_read_header,
archive_read_format_zip_read_data,
archive_read_format_zip_read_data_skip_seekable,
NULL,
archive_read_format_zip_cleanup,
archive_read_support_format_zip_capabilities_seekable,
archive_read_format_zip_has_encrypted_entries);
if (r != ARCHIVE_OK)
free(zip);
return (ARCHIVE_OK);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4904_0 |
crossvul-cpp_data_good_4717_2 | /*
* verify.c:
*
* Author:
* Mono Project (http://www.mono-project.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*/
#include <config.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/verify.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/opcodes.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/reflection.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/metadata.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/security-manager.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/mono-basic-block.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/monobitset.h>
#include <string.h>
#include <signal.h>
#include <ctype.h>
static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
static gboolean verify_all = FALSE;
/*
* Set the desired level of checks for the verfier.
*
*/
void
mono_verifier_set_mode (MiniVerifierMode mode)
{
verifier_mode = mode;
}
void
mono_verifier_enable_verify_all ()
{
verify_all = TRUE;
}
#ifndef DISABLE_VERIFIER
/*
* Pull the list of opcodes
*/
#define OPDEF(a,b,c,d,e,f,g,h,i,j) \
a = i,
enum {
#include "mono/cil/opcode.def"
LAST = 0xff
};
#undef OPDEF
#ifdef MONO_VERIFIER_DEBUG
#define VERIFIER_DEBUG(code) do { code } while (0)
#else
#define VERIFIER_DEBUG(code)
#endif
//////////////////////////////////////////////////////////////////
#define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
#define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
#define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
#define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
#define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
#define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = __status; \
vinfo->info.message = ( __msg ); \
vinfo->exception_type = (__exception); \
(__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
} while (0)
//TODO support MONO_VERIFY_REPORT_ALL_ERRORS
#define ADD_VERIFY_ERROR(__ctx, __msg) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE(__ctx, __msg) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define ADD_VERIFY_ERROR2(__ctx, __msg, __exception) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
#define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
#if SIZEOF_VOID_P == 4
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
#else
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
#endif
#define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
#define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
/*Flags to be used with ILCodeDesc::flags */
enum {
/*Instruction has not been processed.*/
IL_CODE_FLAG_NOT_PROCESSED = 0,
/*Instruction was decoded by mono_method_verify loop.*/
IL_CODE_FLAG_SEEN = 1,
/*Instruction was target of a branch or is at a protected block boundary.*/
IL_CODE_FLAG_WAS_TARGET = 2,
/*Used by stack_init to avoid double initialize each entry.*/
IL_CODE_FLAG_STACK_INITED = 4,
/*Used by merge_stacks to decide if it should just copy the eval stack.*/
IL_CODE_STACK_MERGED = 8,
/*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
IL_CODE_DELEGATE_SEQUENCE = 0x10,
/*This is a delegate created from a ldftn to a non final virtual method*/
IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
/*This is a call to a non final virtual method*/
IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
};
typedef enum {
RESULT_VALID,
RESULT_UNVERIFIABLE,
RESULT_INVALID
} verify_result_t;
typedef struct {
MonoType *type;
int stype;
MonoMethod *method;
} ILStackDesc;
typedef struct {
ILStackDesc *stack;
guint16 size, max_size;
guint16 flags;
} ILCodeDesc;
typedef struct {
int max_args;
int max_stack;
int verifiable;
int valid;
int level;
int code_size;
ILCodeDesc *code;
ILCodeDesc eval;
MonoType **params;
GSList *list;
/*Allocated fnptr MonoType that should be freed by us.*/
GSList *funptrs;
/*Type dup'ed exception types from catch blocks.*/
GSList *exception_types;
int num_locals;
MonoType **locals;
/*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
int target;
guint32 ip_offset;
MonoMethodSignature *signature;
MonoMethodHeader *header;
MonoGenericContext *generic_context;
MonoImage *image;
MonoMethod *method;
/*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0"
*on a method that creates a delegate for a non-final virtual method using ldftn*/
gboolean has_this_store;
/*This flag is used to control if the contructor of the parent class has been called.
*If the this pointer is pushed on the eval stack and it's a reference type constructor and
* super_ctor_called is false, the uninitialized flag is set on the pushed value.
*
* Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
* the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
*/
gboolean super_ctor_called;
guint32 prefix_set;
gboolean has_flags;
MonoType *constrained_type;
} VerifyContext;
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
static int
get_stack_type (MonoType *type);
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn);
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
//////////////////////////////////////////////////////////////////
enum {
TYPE_INV = 0, /* leave at 0. */
TYPE_I4 = 1,
TYPE_I8 = 2,
TYPE_NATIVE_INT = 3,
TYPE_R8 = 4,
/* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/
TYPE_PTR = 5,
/* value types and classes */
TYPE_COMPLEX = 6,
/* Number of types, used to define the size of the tables*/
TYPE_MAX = 6,
/* Used by tables to signal that a result is not verifiable*/
NON_VERIFIABLE_RESULT = 0x80,
/*Mask used to extract just the type, excluding flags */
TYPE_MASK = 0x0F,
/* The stack type is a managed pointer, unmask the value to res */
POINTER_MASK = 0x100,
/*Stack type with the pointer mask*/
RAW_TYPE_MASK = 0x10F,
/* Controlled Mutability Manager Pointer */
CMMP_MASK = 0x200,
/* The stack type is a null literal*/
NULL_LITERAL_MASK = 0x400,
/**Used by ldarg.0 and family to let delegate verification happens.*/
THIS_POINTER_MASK = 0x800,
/**Signals that this is a boxed value type*/
BOXED_MASK = 0x1000,
/*This is an unitialized this ref*/
UNINIT_THIS_MASK = 0x2000,
};
static const char* const
type_names [TYPE_MAX + 1] = {
"Invalid",
"Int32",
"Int64",
"Native Int",
"Float64",
"Native Pointer",
"Complex"
};
enum {
PREFIX_UNALIGNED = 1,
PREFIX_VOLATILE = 2,
PREFIX_TAIL = 4,
PREFIX_CONSTRAINED = 8,
PREFIX_READONLY = 16
};
//////////////////////////////////////////////////////////////////
#ifdef ENABLE_VERIFIER_STATS
#define MEM_ALLOC(amt) do { allocated_memory += (amt); working_set += (amt); } while (0)
#define MEM_FREE(amt) do { working_set -= (amt); } while (0)
static int allocated_memory;
static int working_set;
static int max_allocated_memory;
static int max_working_set;
static int total_allocated_memory;
static void
finish_collect_stats (void)
{
max_allocated_memory = MAX (max_allocated_memory, allocated_memory);
max_working_set = MAX (max_working_set, working_set);
total_allocated_memory += allocated_memory;
allocated_memory = working_set = 0;
}
static void
init_verifier_stats (void)
{
static gboolean inited;
if (!inited) {
inited = TRUE;
mono_counters_register ("Maximum memory allocated during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_allocated_memory);
mono_counters_register ("Maximum memory used during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_working_set);
mono_counters_register ("Total memory allocated for verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &total_allocated_memory);
}
}
#else
#define MEM_ALLOC(amt) do {} while (0)
#define MEM_FREE(amt) do { } while (0)
#define finish_collect_stats()
#define init_verifier_stats()
#endif
//////////////////////////////////////////////////////////////////
/*Token validation macros and functions */
#define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
#define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
#define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
#define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
#define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
#define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
#define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
#define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
#define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
#define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
/*
* Verify if @token refers to a valid row on int's table.
*/
static gboolean
token_bounds_check (MonoImage *image, guint32 token)
{
if (image->dynamic)
return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token);
return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token);
}
static MonoType *
mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
{
MonoType *res = g_new0 (MonoType, 1);
MEM_ALLOC (sizeof (MonoType));
//FIXME use mono_method_get_signature_full
res->data.method = mono_method_signature (method);
res->type = MONO_TYPE_FNPTR;
ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
return res;
}
/*
* mono_type_is_enum_type:
*
* Returns TRUE if @type is an enum type.
*/
static gboolean
mono_type_is_enum_type (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return TRUE;
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return TRUE;
return FALSE;
}
/*
* mono_type_is_value_type:
*
* Returns TRUE if @type is named after @namespace.@name.
*
*/
static gboolean
mono_type_is_value_type (MonoType *type, const char *namespace, const char *name)
{
return type->type == MONO_TYPE_VALUETYPE &&
!strcmp (namespace, type->data.klass->name_space) &&
!strcmp (name, type->data.klass->name);
}
/*
* Returns TURE if @type is VAR or MVAR
*/
static gboolean
mono_type_is_generic_argument (MonoType *type)
{
return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
}
/*
* mono_type_get_underlying_type_any:
*
* This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
*
* Returns the underlying type of @type regardless if it is byref or not.
*/
static MonoType*
mono_type_get_underlying_type_any (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return mono_class_enum_basetype (type->data.klass);
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return mono_class_enum_basetype (type->data.generic_class->container_class);
return type;
}
static G_GNUC_UNUSED const char*
mono_type_get_stack_name (MonoType *type)
{
return type_names [get_stack_type (type) & TYPE_MASK];
}
#define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
#define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
static gboolean
mono_method_is_constructor (MonoMethod *method)
{
return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
!(method->flags & CTOR_INVALID_FLAGS) &&
!strcmp (".ctor", method->name));
}
static gboolean
mono_class_has_default_constructor (MonoClass *klass)
{
MonoMethod *method;
int i;
mono_class_setup_methods (klass);
if (klass->exception_type)
return FALSE;
for (i = 0; i < klass->method.count; ++i) {
method = klass->methods [i];
if (mono_method_is_constructor (method) &&
mono_method_signature (method) &&
mono_method_signature (method)->param_count == 0 &&
(method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
return TRUE;
}
return FALSE;
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
*/
static gboolean
mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context)
{
int i;
MonoGenericInst *inst;
switch (type->type) {
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
if (!context)
return FALSE;
inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst;
if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc)
return FALSE;
break;
case MONO_TYPE_SZARRAY:
return mono_type_is_valid_type_in_context (&type->data.klass->byval_arg, context);
case MONO_TYPE_ARRAY:
return mono_type_is_valid_type_in_context (&type->data.array->eklass->byval_arg, context);
case MONO_TYPE_PTR:
return mono_type_is_valid_type_in_context (type->data.type, context);
case MONO_TYPE_GENERICINST:
inst = type->data.generic_class->context.class_inst;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!mono_type_is_valid_type_in_context (inst->type_argv [i], context))
return FALSE;
break;
}
return TRUE;
}
/*This function returns NULL if the type is not instantiatable*/
static MonoType*
verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context)
{
MonoError error;
MonoType *result;
result = mono_class_inflate_generic_type_checked (type, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return NULL;
}
return result;
}
static gboolean
is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
MonoError error;
int i;
if (ginst->type_argc != gc->type_argc)
return FALSE;
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass *paramClass;
MonoClass **constraints;
if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
continue;
if (mono_type_is_generic_argument (ginst->type_argv [i]))
continue; //it's not our job to validate type variables
paramClass = mono_class_from_mono_type (ginst->type_argv [i]);
if (paramClass->exception_type != MONO_EXCEPTION_NONE)
return FALSE;
/*it's not safe to call mono_class_init from here*/
if (paramClass->generic_class && !paramClass->inited) {
if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
return FALSE;
}
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
return FALSE;
if (!param_info->constraints)
continue;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *inflated;
inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return FALSE;
}
ctr = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (!mono_class_is_assignable_from_slow (ctr, paramClass))
return FALSE;
}
}
return TRUE;
}
/*
* Return true if @candidate is constraint compatible with @target.
*
* This means that @candidate constraints are a super set of @target constaints
*/
static gboolean
mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoClass *candidate_param_class, MonoGenericContext *context)
{
MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
if ((tmask & cmask) != tmask)
return FALSE;
if (tinfo->constraints) {
MonoClass **target_class, **candidate_class;
for (target_class = tinfo->constraints; *target_class; ++target_class) {
MonoClass *tc;
MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
if (!inflated)
return FALSE;
tc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
/*
* A constraint from @target might inflate into @candidate itself and in that case we don't need
* check it's constraints since it satisfy the constraint by itself.
*/
if (mono_metadata_type_equal (&tc->byval_arg, &candidate_param_class->byval_arg))
continue;
if (!cinfo->constraints)
return FALSE;
for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
MonoClass *cc;
inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
if (!inflated)
return FALSE;
cc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (mono_class_is_assignable_from (tc, cc))
break;
}
if (!*candidate_class)
return FALSE;
}
}
return TRUE;
}
static MonoGenericParam*
verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
{
MonoGenericContainer *gc;
MonoMethod *method = ctx->method;
int num;
num = mono_type_get_generic_param_num (type);
if (type->type == MONO_TYPE_VAR) {
MonoClass *gtd = method->klass;
if (gtd->generic_class)
gtd = gtd->generic_class->container_class;
gc = gtd->generic_container;
} else { //MVAR
MonoMethod *gmd = method;
if (method->is_inflated)
gmd = ((MonoMethodInflated*)method)->declaring;
gc = mono_method_get_generic_container (gmd);
}
if (!gc)
return FALSE;
return mono_generic_container_get_param (gc, num);
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
* This means that it either
*/
static gboolean
is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
{
return mono_type_is_valid_type_in_context (type, ctx->generic_context);
}
static gboolean
is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
if (!is_valid_type_in_context (ctx, type))
return FALSE;
}
return TRUE;
}
static gboolean
generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
MonoGenericParam *target = mono_generic_container_get_param (gc, i);
MonoGenericParam *candidate;
MonoClass *candidate_class;
if (!mono_type_is_generic_argument (type))
continue;
if (!is_valid_type_in_context (ctx, type))
return FALSE;
candidate = verifier_get_generic_param_from_type (ctx, type);
candidate_class = mono_class_from_mono_type (type);
if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, candidate_class, context))
return FALSE;
}
return TRUE;
}
static gboolean
mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
}
static gboolean
mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = klass->generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = gklass->container_class->generic_container;
return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
}
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
if (!gc) /*non-generic inflated method - it's part of a generic type */
return TRUE;
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
return FALSE;
return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
}
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = klass->generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = gklass->container_class->generic_container;
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
return FALSE;
return is_valid_generic_instantiation (gc, &gklass->context, ginst);
}
static gboolean
mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
{
MonoClass *klass;
if (type == NULL) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return FALSE;
}
if (!is_valid_type_in_context (ctx, type)) {
char *str = mono_type_full_name (type);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
type->type == MONO_TYPE_VAR ? "!" : "!!",
str,
type->type == MONO_TYPE_VAR ? "class" : "method",
ctx->ip_offset),
MONO_EXCEPTION_BAD_IMAGE);
g_free (str);
return FALSE;
}
klass = mono_class_from_mono_type (type);
mono_class_init (klass);
if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
else
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
mono_loader_clear_error ();
return FALSE;
}
if (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!klass->generic_class)
return TRUE;
if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!mono_class_repect_method_constraints (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s (generic args don't respect target's constraints) at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
return TRUE;
}
static verify_result_t
mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
{
if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
return RESULT_INVALID;
if (!method->is_inflated)
return RESULT_VALID;
if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset), MONO_EXCEPTION_UNVERIFIABLE_IL);
return RESULT_INVALID;
}
if (!mono_method_repect_method_constraints (ctx, method)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s (generic args don't respect target's constraints) at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset));
return RESULT_UNVERIFIABLE;
}
return RESULT_VALID;
}
static MonoClassField*
verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) {
MonoClassField *field;
MonoClass *klass = NULL;
if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
if (!field || !field->parent || !klass || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load field from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
return NULL;
*out_klass = klass;
return field;
}
static MonoMethod*
verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
MonoMethod* method;
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid method token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
if (!method || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load method from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
return NULL;
return method;
}
static MonoType*
verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
MonoType* type;
if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
type = mono_type_get_full (ctx->image, token, ctx->generic_context);
if (!type || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load type from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, type))
return NULL;
return type;
}
/* stack_slot_get_type:
*
* Returns the stack type of @value. This value includes POINTER_MASK.
*
* Use this function to checks that account for a managed pointer.
*/
static gint32
stack_slot_get_type (ILStackDesc *value)
{
return value->stype & RAW_TYPE_MASK;
}
/* stack_slot_get_underlying_type:
*
* Returns the stack type of @value. This value does not include POINTER_MASK.
*
* Use this function is cases where the fact that the value could be a managed pointer is
* irrelevant. For example, field load doesn't care about this fact of type on stack.
*/
static gint32
stack_slot_get_underlying_type (ILStackDesc *value)
{
return value->stype & TYPE_MASK;
}
/* stack_slot_is_managed_pointer:
*
* Returns TRUE is @value is a managed pointer.
*/
static gboolean
stack_slot_is_managed_pointer (ILStackDesc *value)
{
return (value->stype & POINTER_MASK) == POINTER_MASK;
}
/* stack_slot_is_managed_mutability_pointer:
*
* Returns TRUE is @value is a managed mutability pointer.
*/
static G_GNUC_UNUSED gboolean
stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
{
return (value->stype & CMMP_MASK) == CMMP_MASK;
}
/* stack_slot_is_null_literal:
*
* Returns TRUE is @value is the null literal.
*/
static gboolean
stack_slot_is_null_literal (ILStackDesc *value)
{
return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
}
/* stack_slot_is_this_pointer:
*
* Returns TRUE is @value is the this literal
*/
static gboolean
stack_slot_is_this_pointer (ILStackDesc *value)
{
return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
}
/* stack_slot_is_boxed_value:
*
* Returns TRUE is @value is a boxed value
*/
static gboolean
stack_slot_is_boxed_value (ILStackDesc *value)
{
return (value->stype & BOXED_MASK) == BOXED_MASK;
}
static const char *
stack_slot_get_name (ILStackDesc *value)
{
return type_names [value->stype & TYPE_MASK];
}
#define APPEND_WITH_PREDICATE(PRED,NAME) do {\
if (PRED (value)) { \
if (!first) \
g_string_append (str, ", "); \
g_string_append (str, NAME); \
first = FALSE; \
} } while (0)
static char*
stack_slot_stack_type_full_name (ILStackDesc *value)
{
GString *str = g_string_new ("");
char *result;
gboolean has_pred = FALSE, first = TRUE;
if ((value->stype & TYPE_MASK) != value->stype) {
g_string_append(str, "[");
APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
has_pred = TRUE;
}
if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
if (!has_pred)
g_string_append(str, "[");
if (!first)
g_string_append (str, ", ");
g_string_append (str, "unboxed");
has_pred = TRUE;
}
if (has_pred)
g_string_append(str, "] ");
g_string_append (str, stack_slot_get_name (value));
result = str->str;
g_string_free (str, FALSE);
return result;
}
static char*
stack_slot_full_name (ILStackDesc *value)
{
char *type_name = mono_type_full_name (value->type);
char *stack_name = stack_slot_stack_type_full_name (value);
char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
g_free (type_name);
g_free (stack_name);
return res;
}
//////////////////////////////////////////////////////////////////
void
mono_free_verify_list (GSList *list)
{
MonoVerifyInfoExtended *info;
GSList *tmp;
for (tmp = list; tmp; tmp = tmp->next) {
info = tmp->data;
g_free (info->info.message);
g_free (info);
}
g_slist_free (list);
}
#define ADD_ERROR(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = MONO_VERIFY_ERROR; \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_WARN(list,code,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = (code); \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_INVALID(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->status = MONO_VERIFY_ERROR; \
vinfo->message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
/*G_BREAKPOINT ();*/ \
goto invalid_cil; \
} while (0)
#define CHECK_STACK_UNDERFLOW(num) \
do { \
if (cur_stack < (num)) \
ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
} while (0)
#define CHECK_STACK_OVERFLOW() \
do { \
if (cur_stack >= max_stack) \
ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
} while (0)
static int
in_any_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 1;
}
return 0;
}
/*
* in_any_exception_block:
*
* Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
*/
static gboolean
in_any_exception_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return TRUE;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return TRUE;
}
return FALSE;
}
/*
* is_valid_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with br and brtrue/false.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
* The major diferent from other similiar functions is that branching into a
* finally/fault block is invalid instead of just unverifiable.
*/
static int
is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching into a finally block is invalid*/
if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
!MONO_OFFSET_IN_HANDLER (clause, offset) &&
MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 1;
}
return 0;
}
/*
* is_valid_cmp_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with binary comparison branching instruction, like beq, bge and similars.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
*
* The major diferences from other similar functions are that most errors lead to invalid
* code and only branching out of finally, filter or fault clauses is unverifiable.
*/
static int
is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching out of a handler or finally*/
if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
MONO_OFFSET_IN_HANDLER (clause, offset) &&
!MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 2;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 2;
}
return 0;
}
/*
* A leave can't escape a finally block
*/
static int
is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
return 0;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 0;
}
return 1;
}
/*
* A rethrow can't happen outside of a catch handler.
*/
static int
is_correct_rethrow (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 1;
}
return 0;
}
/*
* An endfinally can't happen outside of a finally/fault handler.
*/
static int
is_correct_endfinally (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
return 1;
}
return 0;
}
/*
* An endfilter can only happens inside a filter clause.
* In non-strict mode filter is allowed inside the handler clause too
*/
static MonoExceptionClause *
is_correct_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
continue;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return clause;
if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
return clause;
}
return NULL;
}
/*
* Non-strict endfilter can happens inside a try block or any handler block
*/
static int
is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
}
return 0;
}
static gboolean
is_valid_bool_arg (ILStackDesc *arg)
{
if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
return TRUE;
switch (stack_slot_get_underlying_type (arg)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_PTR:
return TRUE;
case TYPE_COMPLEX:
g_assert (arg->type);
switch (arg->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
return TRUE;
case MONO_TYPE_GENERICINST:
/*We need to check if the container class
* of the generic type is a valuetype, iow:
* is it a "class Foo<T>" or a "struct Foo<T>"?
*/
return !arg->type->data.generic_class->container_class->valuetype;
}
default:
return FALSE;
}
}
/*Type manipulation helper*/
/*Returns the byref version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byref (MonoType *type)
{
if (type->byref)
return type;
return &mono_class_from_mono_type (type)->this_arg;
}
/*Returns the byval version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byval (MonoType *type)
{
if (!type->byref)
return type;
return &mono_class_from_mono_type (type)->byval_arg;
}
static MonoType*
mono_type_from_stack_slot (ILStackDesc *slot)
{
if (stack_slot_is_managed_pointer (slot))
return mono_type_get_type_byref (slot->type);
return slot->type;
}
/*Stack manipulation code*/
static void
ensure_stack_size (ILCodeDesc *stack, int required)
{
int new_size = 8;
ILStackDesc *tmp;
if (required < stack->max_size)
return;
/* We don't have to worry about the exponential growth since stack_copy prune unused space */
new_size = MAX (8, MAX (required, stack->max_size * 2));
g_assert (new_size >= stack->size);
g_assert (new_size >= required);
tmp = g_new0 (ILStackDesc, new_size);
MEM_ALLOC (sizeof (ILStackDesc) * new_size);
if (stack->stack) {
if (stack->size)
memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
g_free (stack->stack);
MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
}
stack->stack = tmp;
stack->max_size = new_size;
}
static void
stack_init (VerifyContext *ctx, ILCodeDesc *state)
{
if (state->flags & IL_CODE_FLAG_STACK_INITED)
return;
state->size = state->max_size = 0;
state->flags |= IL_CODE_FLAG_STACK_INITED;
}
static void
stack_copy (ILCodeDesc *to, ILCodeDesc *from)
{
ensure_stack_size (to, from->size);
to->size = from->size;
/*stack copy happens at merge points, which have small stacks*/
if (from->size)
memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
}
static void
copy_stack_value (ILStackDesc *to, ILStackDesc *from)
{
to->stype = from->stype;
to->type = from->type;
to->method = from->method;
}
static int
check_underflow (VerifyContext *ctx, int size)
{
if (ctx->eval.size < size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
return 0;
}
return 1;
}
static int
check_overflow (VerifyContext *ctx)
{
if (ctx->eval.size >= ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
return 0;
}
return 1;
}
/*This reject out PTR, FNPTR and TYPEDBYREF*/
static gboolean
check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
{
if (stack_slot_get_type (value) == TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
/*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
static gboolean
check_unverifiable_type (VerifyContext *ctx, MonoType *type)
{
if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
static ILStackDesc *
stack_push (VerifyContext *ctx)
{
g_assert (ctx->eval.size < ctx->max_stack);
g_assert (ctx->eval.size <= ctx->eval.max_size);
ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
return & ctx->eval.stack [ctx->eval.size++];
}
static ILStackDesc *
stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
{
ILStackDesc *top = stack_push (ctx);
top->stype = stype;
top->type = type;
return top;
}
static ILStackDesc *
stack_pop (VerifyContext *ctx)
{
ILStackDesc *ret;
g_assert (ctx->eval.size > 0);
ret = ctx->eval.stack + --ctx->eval.size;
if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
return ret;
}
/* This function allows to safely pop an unititialized this ptr from
* the eval stack without marking the method as unverifiable.
*/
static ILStackDesc *
stack_pop_safe (VerifyContext *ctx)
{
g_assert (ctx->eval.size > 0);
return ctx->eval.stack + --ctx->eval.size;
}
/*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
static ILStackDesc*
stack_peek (VerifyContext *ctx, int distance)
{
g_assert (ctx->eval.size - distance > 0);
return ctx->eval.stack + (ctx->eval.size - 1 - distance);
}
static ILStackDesc *
stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
{
ILStackDesc *top = stack_push (ctx);
copy_stack_value (top, value);
return top;
}
/* Returns the MonoType associated with the token, or NULL if it is invalid.
*
* A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
* */
static MonoType*
get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
{
MonoType *type;
MonoClass *class;
if (!(type = verifier_load_type (ctx, token, opcode)))
return NULL;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_TYPEDBYREF)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
if (!(class = mono_class_from_mono_type (type)))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the generic type definition in a boxable type position for %s at 0x%04x", opcode, ctx->ip_offset));
check_unverifiable_type (ctx, type);
return type;
}
/*operation result tables */
static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
};
static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
#ifdef MONO_VERIFIER_DEBUG
/*debug helpers */
static void
dump_stack_value (ILStackDesc *value)
{
printf ("[(%x)(%x)", value->type->type, value->stype);
if (stack_slot_is_this_pointer (value))
printf ("[this] ");
if (stack_slot_is_boxed_value (value))
printf ("[boxed] ");
if (stack_slot_is_null_literal (value))
printf ("[null] ");
if (stack_slot_is_managed_mutability_pointer (value))
printf ("Controled Mutability MP: ");
if (stack_slot_is_managed_pointer (value))
printf ("Managed Pointer to: ");
switch (stack_slot_get_underlying_type (value)) {
case TYPE_INV:
printf ("invalid type]");
return;
case TYPE_I4:
printf ("int32]");
return;
case TYPE_I8:
printf ("int64]");
return;
case TYPE_NATIVE_INT:
printf ("native int]");
return;
case TYPE_R8:
printf ("float64]");
return;
case TYPE_PTR:
printf ("unmanaged pointer]");
return;
case TYPE_COMPLEX:
switch (value->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE:
printf ("complex] (%s)", value->type->data.klass->name);
return;
case MONO_TYPE_STRING:
printf ("complex] (string)");
return;
case MONO_TYPE_OBJECT:
printf ("complex] (object)");
return;
case MONO_TYPE_SZARRAY:
printf ("complex] (%s [])", value->type->data.klass->name);
return;
case MONO_TYPE_ARRAY:
printf ("complex] (%s [%d %d %d])",
value->type->data.array->eklass->name,
value->type->data.array->rank,
value->type->data.array->numsizes,
value->type->data.array->numlobounds);
return;
case MONO_TYPE_GENERICINST:
printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
return;
case MONO_TYPE_VAR:
printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
case MONO_TYPE_MVAR:
printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
default: {
//should be a boxed value
char * name = mono_type_full_name (value->type);
printf ("complex] %s", name);
g_free (name);
return;
}
}
default:
printf ("unknown stack %x type]\n", value->stype);
g_assert_not_reached ();
}
}
static void
dump_stack_state (ILCodeDesc *state)
{
int i;
printf ("(%d) ", state->size);
for (i = 0; i < state->size; ++i)
dump_stack_value (state->stack + i);
printf ("\n");
}
#endif
/*Returns TRUE if candidate array type can be assigned to target.
*Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
*/
static gboolean
is_array_type_compatible (MonoType *target, MonoType *candidate)
{
MonoArrayType *left = target->data.array;
MonoArrayType *right = candidate->data.array;
g_assert (target->type == MONO_TYPE_ARRAY);
g_assert (candidate->type == MONO_TYPE_ARRAY);
if (left->rank != right->rank)
return FALSE;
return mono_class_is_assignable_from (left->eklass, right->eklass);
}
static int
get_stack_type (MonoType *type)
{
int mask = 0;
int type_kind = type->type;
if (type->byref)
mask = POINTER_MASK;
/*TODO handle CMMP_MASK */
handle_enum:
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
return TYPE_I4 | mask;
case MONO_TYPE_I:
case MONO_TYPE_U:
return TYPE_NATIVE_INT | mask;
/* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
return TYPE_PTR | mask;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
return TYPE_COMPLEX | mask;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return TYPE_I8 | mask;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
return TYPE_R8 | mask;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
type = mono_type_get_underlying_type_any (type);
if (!type)
return FALSE;
type_kind = type->type;
goto handle_enum;
} else {
return TYPE_COMPLEX | mask;
}
default:
return TYPE_INV;
}
}
/* convert MonoType to ILStackDesc format (stype) */
static gboolean
set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
{
int mask = 0;
int type_kind = type->type;
if (type->byref || take_addr)
mask = POINTER_MASK;
/* TODO handle CMMP_MASK */
handle_enum:
stack->type = type;
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
stack->stype = TYPE_I4 | mask;
break;
case MONO_TYPE_I:
case MONO_TYPE_U:
stack->stype = TYPE_NATIVE_INT | mask;
break;
/*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
stack->stype = TYPE_PTR | mask;
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
stack->stype = TYPE_COMPLEX | mask;
break;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
stack->stype = TYPE_I8 | mask;
break;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
stack->stype = TYPE_R8 | mask;
break;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
MonoType *utype = mono_type_get_underlying_type_any (type);
if (!utype) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
return FALSE;
}
type = utype;
type_kind = type->type;
goto handle_enum;
} else {
stack->stype = TYPE_COMPLEX | mask;
break;
}
default:
VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
return FALSE;
}
return TRUE;
}
/*
* init_stack_with_value_at_exception_boundary:
*
* Initialize the stack and push a given type.
* The instruction is marked as been on the exception boundary.
*/
static void
init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
{
MonoError error;
MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_get_full_name (klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
g_free (name);
mono_error_cleanup (&error);
return;
}
if (!ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
return;
}
stack_init (ctx, code);
ensure_stack_size (code, 1);
set_stack_value (ctx, code->stack, type, FALSE);
ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
code->size = 1;
code->flags |= IL_CODE_FLAG_WAS_TARGET;
if (mono_type_is_generic_argument (type))
code->stack->stype |= BOXED_MASK;
}
/*Verify if type 'candidate' can be stored in type 'target'.
*
* If strict, check for the underlying type and not the verification stack types
*/
static gboolean
verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
{
#define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
MonoType *original_candidate = candidate;
VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
/*only one is byref */
if (candidate->byref ^ target->byref) {
/* converting from native int to byref*/
if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
return TRUE;
}
return FALSE;
}
strict |= target->byref;
/*From now on we don't care about byref anymore, so it's ok to discard it here*/
candidate = mono_type_get_underlying_type_any (candidate);
handle_enum:
switch (target->type) {
case MONO_TYPE_VOID:
return candidate->type == MONO_TYPE_VOID;
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
case MONO_TYPE_I4:
case MONO_TYPE_U4: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
case MONO_TYPE_R4:
case MONO_TYPE_R8:
if (strict)
return candidate->type == target->type;
return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
case MONO_TYPE_I:
case MONO_TYPE_U: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_PTR:
if (candidate->type != MONO_TYPE_PTR)
return FALSE;
/* check the underlying type */
return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
case MONO_TYPE_FNPTR: {
MonoMethodSignature *left, *right;
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
left = mono_type_get_signature (target);
right = mono_type_get_signature (candidate);
return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
}
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (mono_class_is_nullable (target_klass)) {
if (!mono_class_is_nullable (candidate_klass))
return FALSE;
return target_klass == candidate_klass;
}
return mono_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_STRING:
return candidate->type == MONO_TYPE_STRING;
case MONO_TYPE_CLASS:
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
if (candidate->type == MONO_TYPE_VALUETYPE)
return FALSE;
/* If candidate is an enum it should return true for System.Enum and supertypes.
* That's why here we use the original type and not the underlying type.
*/
return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_SZARRAY: {
MonoClass *left;
MonoClass *right;
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
left = mono_class_from_mono_type (target);
right = mono_class_from_mono_type (candidate);
return mono_class_is_assignable_from (left, right);
}
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_TYPEDBYREF:
return candidate->type == MONO_TYPE_TYPEDBYREF;
case MONO_TYPE_VALUETYPE: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (candidate->type == MONO_TYPE_CLASS)
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (target_klass == candidate_klass)
return TRUE;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
return FALSE;
}
case MONO_TYPE_VAR:
if (candidate->type != MONO_TYPE_VAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
case MONO_TYPE_MVAR:
if (candidate->type != MONO_TYPE_MVAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
default:
VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
return 1;
#undef IS_ONE_OF3
#undef IS_ONE_OF2
}
static gboolean
verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
{
return verify_type_compatibility_full (ctx, target, candidate, FALSE);
}
/*
* Returns the generic param bound to the context been verified.
*
*/
static MonoGenericParam*
get_generic_param (VerifyContext *ctx, MonoType *param)
{
guint16 param_num = mono_type_get_generic_param_num (param);
if (param->type == MONO_TYPE_VAR) {
if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
return NULL;
}
return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
}
/*param must be a MVAR */
if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
return NULL;
}
return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
}
static gboolean
recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level)
{
MonoType *constraint_type = &constraint_class->byval_arg;
if (recursion_level <= 0)
return FALSE;
if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE))
return TRUE;
if (mono_type_is_generic_argument (constraint_type)) {
MonoGenericParam *param = get_generic_param (ctx, constraint_type);
MonoClass **class;
if (!param)
return FALSE;
for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
if (recursive_boxed_constraint_type_check (ctx, type, *class, recursion_level - 1))
return TRUE;
}
}
return FALSE;
}
/*
* is_compatible_boxed_valuetype:
*
* Returns TRUE if @candidate / @stack is a valid boxed valuetype.
*
* @type The source type. It it tested to be of the proper type.
* @candidate type of the boxed valuetype.
* @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
* @strict if TRUE candidate must be boxed compatible to the target type
*
*/
static gboolean
is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
{
if (!stack_slot_is_boxed_value (stack))
return FALSE;
if (type->byref || candidate->byref)
return FALSE;
if (mono_type_is_generic_argument (candidate)) {
MonoGenericParam *param = get_generic_param (ctx, candidate);
MonoClass **class;
if (!param)
return FALSE;
for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
/*256 should be enough since there can't be more than 255 generic arguments.*/
if (recursive_boxed_constraint_type_check (ctx, type, *class, 256))
return TRUE;
}
}
if (mono_type_is_generic_argument (type))
return FALSE;
if (!strict)
return TRUE;
return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
}
static int
verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
{
MonoType *candidate = mono_type_from_stack_slot (stack);
if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
return TRUE;
if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
return TRUE;
if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
return FALSE;
if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
return FALSE;
if (drop_byref)
return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
return verify_type_compatibility_full (ctx, type, candidate, FALSE);
}
static int
verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
{
return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
}
static gboolean
mono_delegate_type_equal (MonoType *target, MonoType *candidate)
{
if (candidate->byref ^ target->byref)
return FALSE;
switch (target->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_TYPEDBYREF:
return candidate->type == target->type;
case MONO_TYPE_PTR:
return mono_delegate_type_equal (target->data.type, candidate->data.type);
case MONO_TYPE_FNPTR:
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
/*FIXME handle nullables and enum*/
return mono_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_CLASS:
return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
case MONO_TYPE_SZARRAY:
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_VALUETYPE:
/*FIXME handle nullables and enum*/
return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
case MONO_TYPE_VAR:
return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
case MONO_TYPE_MVAR:
return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
default:
VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
}
static gboolean
mono_delegate_param_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (method, delegate);
}
static gboolean
mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (delegate, method);
}
/*
* mono_delegate_signature_equal:
*
* Compare two signatures in the way expected by delegates.
*
* This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
*
* FIXME can this function be eliminated and proper metadata functionality be used?
*/
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
{
int i;
int method_offset = is_static_ldftn ? 1 : 0;
if (delegate_sig->param_count + method_offset != method_sig->param_count)
return FALSE;
if (delegate_sig->call_convention != method_sig->call_convention)
return FALSE;
for (i = 0; i < delegate_sig->param_count; i++) {
MonoType *p1 = delegate_sig->params [i];
MonoType *p2 = method_sig->params [i + method_offset];
if (!mono_delegate_param_equal (p1, p2))
return FALSE;
}
if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
return FALSE;
return TRUE;
}
/*
* verify_ldftn_delegate:
*
* Verify properties of ldftn based delegates.
*/
static void
verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
MonoMethod *method = funptr->method;
/*ldftn non-final virtuals only allowed if method is not static,
* the object is a this arg (comes from a ldarg.0), and there is no starg.0.
* This rules doesn't apply if the object on stack is a boxed valuetype.
*/
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
/*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
/*current method must not be static*/
if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
/*value is the this pointer, loaded using ldarg.0 */
if (!stack_slot_is_this_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object argument, it is not the this pointer, to ldftn with virtual method at 0x%04x", ctx->ip_offset));
ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
}
}
/*
* verify_delegate_compatibility:
*
* Verify delegate creation sequence.
*
*/
static void
verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
#define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
#define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
MonoMethod *invoke, *method;
const guint8 *ip = ctx->header->code;
guint32 ip_offset = ctx->ip_offset;
gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
invoke = mono_get_delegate_invoke (delegate);
method = funptr->method;
if (!method || !mono_method_signature (method)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
if (!invoke || !mono_method_signature (invoke)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
if (is_static_ldftn)
is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Function pointer signature '%s' doesn't match delegate's signature '%s' at 0x%04x", fun_sig, invoke_sig, ctx->ip_offset));
g_free (fun_sig);
g_free (invoke_sig);
}
/*
* Delegate code sequences:
* [-6] ldftn token
* newobj ...
*
*
* [-7] dup
* [-6] ldvirtftn token
* newobj ...
*
* ldftn sequence:*/
if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
verify_ldftn_delegate (ctx, delegate, value, funptr);
} else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
}else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
}
ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
//general tests
if (is_first_arg_bound) {
if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_STATIC) {
if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
}
}
if (stack_slot_get_type (value) != TYPE_COMPLEX)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
#undef IS_VALID_OPCODE
#undef IS_LOAD_FUN_PTR
}
/* implement the opcode checks*/
static void
push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
{
ILStackDesc *top;
if (arg >= ctx->max_args) {
if (take_addr)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->params [arg]);
if (ctx->params [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
top = stack_push (ctx);
if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
return;
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
if (take_addr)
ctx->has_this_store = TRUE;
else
top->stype |= THIS_POINTER_MASK;
if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
top->stype |= UNINIT_THIS_MASK;
}
}
}
static void
push_local (VerifyContext *ctx, guint32 arg, int take_addr)
{
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->locals [arg]);
if (ctx->locals [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
}
}
static void
store_arg (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->max_args) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
if (check_underflow (ctx, 1))
stack_pop (ctx);
return;
}
if (check_underflow (ctx, 1)) {
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
}
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
ctx->has_this_store = 1;
}
static void
store_local (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
return;
}
/*TODO verify definite assigment */
if (check_underflow (ctx, 1)) {
value = stack_pop(ctx);
if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
char *expected = mono_type_full_name (ctx->locals [arg]);
char *found = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
found,
arg,
expected,
ctx->ip_offset));
g_free (expected);
g_free (found);
}
}
}
/*FIXME add and sub needs special care here*/
static void
do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b, *top;
int idxa, idxb, complexMerge = 0;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a)) {
idxa = TYPE_PTR;
complexMerge = 1;
}
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b)) {
idxb = TYPE_PTR;
complexMerge = 2;
}
--idxa;
--idxb;
res = table [idxa][idxb];
VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
top = stack_push (ctx);
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction applyed to ill formed stack (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
copy_stack_value (top, a);
return;
}
if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction is not verifiable (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
res = res & ~NON_VERIFIABLE_RESULT;
}
if (complexMerge && res == TYPE_PTR) {
if (complexMerge == 1)
copy_stack_value (top, a);
else if (complexMerge == 2)
copy_stack_value (top, b);
/*
* There is no need to merge the type of two pointers.
* The only valid operation is subtraction, that returns a native
* int as result and can be used with any 2 pointer kinds.
* This is valid acording to Patition III 1.1.4
*/
} else
top->stype = res;
}
static void
do_boolean_branch_op (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
ILStackDesc *top;
VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (!is_valid_bool_arg (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Argument type %s not valid for brtrue/brfalse at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
check_unmanaged_pointer (ctx, top);
}
static gboolean
stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
{
return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
}
static void
do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
int target = ctx->ip_offset + delta;
VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1: /*FIXME use constants and not magic numbers.*/
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx,
g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
}
static void
do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
if (opcode == CEE_CGT_UN) {
if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
return;
}
}
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
if(res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf("Compare instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
static void
do_ret (VerifyContext *ctx)
{
MonoType *ret = ctx->signature->ret;
VERIFIER_DEBUG ( printf ("checking ret\n"); );
if (ret->type != MONO_TYPE_VOID) {
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop(ctx);
if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
return;
}
if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
}
if (ctx->eval.size > 0) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
}
if (in_any_block (ctx->header, ctx->ip_offset))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
}
/*
* FIXME we need to fix the case of a non-virtual instance method defined in the parent but call using a token pointing to a subclass.
* This is illegal but mono_get_method_full decoded it.
* TODO handle calling .ctor outside one or calling the .ctor for other class but super
*/
static void
do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
{
int param_count, i;
MonoMethodSignature *sig;
ILStackDesc *value;
MonoMethod *method;
gboolean virt_check_this = FALSE;
gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
return;
if (virtual) {
CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
if (method->klass->valuetype) // && !constrained ???
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_STATIC))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
virt_check_this = TRUE;
ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
}
}
if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
sig = mono_method_get_signature (method, ctx->image, method_token);
if (!sig) {
char *name = mono_type_get_full_name (method->klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset));
g_free (name);
return;
}
param_count = sig->param_count + sig->hasthis;
if (!check_underflow (ctx, param_count))
return;
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter with function signature: Calling method with signature (%s) but for argument %d there is a (%s) on stack at 0x%04x", sig_name, i, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset));
if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot pass a byref argument to a tail %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset));
return;
}
}
if (sig->hasthis) {
MonoType *type = &method->klass->byval_arg;
ILStackDesc copy;
if (mono_method_is_constructor (method) && !method->klass->valuetype) {
if (!mono_method_is_constructor (ctx->method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor to a type diferent that this or super at 0x%04x", ctx->ip_offset));
ctx->super_ctor_called = TRUE;
value = stack_pop_safe (ctx);
if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
} else {
value = stack_pop (ctx);
}
copy_stack_value (©, value);
//TODO we should extract this to a 'drop_byref_argument' and use everywhere
//Other parts of the code suffer from the same issue of
copy.type = mono_type_get_type_byval (copy.type);
copy.stype &= ~POINTER_MASK;
if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object diferent thant the this pointer at 0x%04x", ctx->ip_offset));
if (constrained && virtual) {
if (!stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
copy.stype |= BOXED_MASK;
} else {
if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a reference type using a managed pointer to the this arg at 0x%04x", ctx->ip_offset));
if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a boxed or literal valuetype to call a valuetype method at 0x%04x", ctx->ip_offset));
}
if (!verify_stack_type_compatibility (ctx, type, ©)) {
char *expected = mono_type_full_name (type);
char *effective = stack_slot_full_name (©);
char *method_name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature expected '%s' but got '%s' for a call to '%s' at 0x%04x",
expected, effective, method_name, ctx->ip_offset));
g_free (method_name);
g_free (effective);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
} else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
if (sig->ret->type != MONO_TYPE_VOID) {
if (check_overflow (ctx)) {
value = stack_push (ctx);
set_stack_value (ctx, value, sig->ret, FALSE);
if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
ctx->prefix_set &= ~PREFIX_READONLY;
value->stype |= CMMP_MASK;
}
}
}
if ((ctx->prefix_set & PREFIX_TAIL)) {
if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
}
}
static void
do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
{
MonoClassField *field;
MonoClass *klass;
if (!check_overflow (ctx))
return;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
return;
}
/*taking the address of initonly field only works from the static constructor */
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
}
static void
do_store_static_field (VerifyContext *ctx, int token) {
MonoClassField *field;
MonoClass *klass;
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
return;
}
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
return;
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
if (!verify_stack_type_compatibility (ctx, field->type, value)) {
char *stack_name = stack_slot_full_name (value);
char *field_name = mono_type_full_name (field->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type in static field store expected '%s' but found '%s' at 0x%04x",
field_name, stack_name, ctx->ip_offset));
g_free (field_name);
g_free (stack_name);
}
}
static gboolean
check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
{
MonoClassField *field;
MonoClass *klass;
gboolean is_pointer;
/*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
return FALSE;
*ret_field = field;
//the value on stack is going to be used as a pointer
is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
return FALSE;
}
g_assert (obj->type);
/*The value on the stack must be a subclass of the defining type of the field*/
/* we need to check if we can load the field from the stack value*/
if (is_pointer) {
if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
} else {
if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a managed pointer to a reference type and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
/*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a boxed valuetype and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
char *found = stack_slot_full_name (obj);
char *expected = mono_type_full_name (&field->parent->byval_arg);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset));
g_free (found);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
}
check_unmanaged_pointer (ctx, obj);
return TRUE;
}
static void
do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
{
ILStackDesc *obj;
MonoClassField *field;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
return;
if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
}
static void
do_store_field (VerifyContext *ctx, int token)
{
ILStackDesc *value, *obj;
MonoClassField *field;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
value = stack_pop (ctx);
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
return;
if (!verify_stack_type_compatibility (ctx, field->type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
/*TODO proper handle for Nullable<T>*/
static void
do_box_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
MonoClass *klass;
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*box is a nop for reference types*/
if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
return;
}
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
klass = mono_class_from_mono_type (type);
if (mono_class_is_nullable (klass))
type = &mono_class_get_nullable_param (klass)->byval_arg;
stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
}
static void
do_unbox_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
if (!mono_class_from_mono_type (type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
value->stype |= CMMP_MASK;
}
static void
do_unbox_any (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox.any operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_unary_math_op (VerifyContext *ctx, int op)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
break;
case TYPE_R8:
if (op == CEE_NEG)
break;
case TYPE_COMPLEX: /*only enums are ok*/
if (mono_type_is_enum_type (value->type))
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
}
stack_push_stack_val (ctx, value);
}
static void
do_conversion (VerifyContext *ctx, int kind)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_R8:
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type (%s) at stack for conversion operation. Numeric type expected at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
switch (kind) {
case TYPE_I4:
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
break;
case TYPE_I8:
stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
break;
case TYPE_R8:
stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
break;
case TYPE_NATIVE_INT:
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
break;
default:
g_error ("unknown type %02x in conversion", kind);
}
}
static void
do_load_token (VerifyContext *ctx, int token)
{
gpointer handle;
MonoClass *handle_class;
if (!check_overflow (ctx))
return;
switch (token & 0xff000000) {
case MONO_TOKEN_TYPE_DEF:
case MONO_TOKEN_TYPE_REF:
case MONO_TOKEN_TYPE_SPEC:
case MONO_TOKEN_FIELD_DEF:
case MONO_TOKEN_METHOD_DEF:
case MONO_TOKEN_METHOD_SPEC:
case MONO_TOKEN_MEMBER_REF:
if (!token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Table index out of range 0x%x for token %x for ldtoken at 0x%04x", mono_metadata_token_index (token), token, ctx->ip_offset));
return;
}
break;
default:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid table 0x%x for token 0x%x for ldtoken at 0x%04x", mono_metadata_token_table (token), token, ctx->ip_offset));
return;
}
handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
if (!handle) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
return;
}
if (handle_class == mono_defaults.typehandle_class) {
mono_type_is_valid_in_context (ctx, (MonoType*)handle);
} else if (handle_class == mono_defaults.methodhandle_class) {
mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
} else if (handle_class == mono_defaults.fieldhandle_class) {
mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
} else {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
}
stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
}
static void
do_ldobj_value (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)
&& stack_slot_get_type (value) != TYPE_NATIVE_INT
&& !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
return;
}
if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
/*We have a byval on the stack, but the comparison must be strict. */
if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_stobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, type, src)) {
char *type_name = mono_type_full_name (type);
char *src_name = stack_slot_full_name (src);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token '%s' and source '%s' of stobj don't match ' at 0x%04x", type_name, src_name, ctx->ip_offset));
g_free (type_name);
g_free (src_name);
}
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_cpobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (src))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_initobj (VerifyContext *ctx, int token)
{
ILStackDesc *obj;
MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
obj = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
stack = mono_type_get_type_byval (obj->type);
if (MONO_TYPE_IS_REFERENCE (stack)) {
if (!verify_type_compatibility (ctx, stack, type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility (ctx, stack, type)) {
char *expected_name = mono_type_full_name (type);
char *stack_name = mono_type_full_name (stack);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Initobj %s not compatible with value on stack %s at 0x%04x", expected_name, stack_name, ctx->ip_offset));
g_free (expected_name);
g_free (stack_name);
}
}
static void
do_newobj (VerifyContext *ctx, int token)
{
ILStackDesc *value;
int i;
MonoMethodSignature *sig;
MonoMethod *method;
gboolean is_delegate = FALSE;
if (!(method = verifier_load_method (ctx, token, "newobj")))
return;
if (!mono_method_is_constructor (method)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
return;
}
if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *from = mono_method_full_name (ctx->method, TRUE);
char *to = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Constructor %s not visible from %s at 0x%04x", to, from, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (from);
g_free (to);
}
//FIXME use mono_method_get_signature_full
sig = mono_method_signature (method);
if (!sig) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
return;
}
if (!check_underflow (ctx, sig->param_count))
return;
is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
if (is_delegate) {
ILStackDesc *funptr;
//first arg is object, second arg is fun ptr
if (sig->param_count != 2) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
funptr = stack_pop (ctx);
value = stack_pop (ctx);
verify_delegate_compatibility (ctx, method->klass, value, funptr);
} else {
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with constructor signature: %s X %s at 0x%04x", sig_name, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
}
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
}
static void
do_cast (VerifyContext *ctx, int token, const char *opcode) {
ILStackDesc *value;
MonoType *type;
gboolean is_boxed;
gboolean do_box;
if (!check_underflow (ctx, 1))
return;
if (!(type = verifier_load_type (ctx, token, opcode)))
return;
if (type->byref) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
return;
}
value = stack_pop (ctx);
is_boxed = stack_slot_is_boxed_value (value);
if (stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
char *name = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a reference type on stack for %s but found %s at 0x%04x", opcode, name, ctx->ip_offset));
g_free (name);
}
switch (value->type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
}
do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
}
static MonoType *
mono_type_from_opcode (int opcode) {
switch (opcode) {
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_STIND_I1:
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_STELEM_I1:
return &mono_defaults.sbyte_class->byval_arg;
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_STIND_I2:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_STELEM_I2:
return &mono_defaults.int16_class->byval_arg;
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_STIND_I4:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_STELEM_I4:
return &mono_defaults.int32_class->byval_arg;
case CEE_LDIND_I8:
case CEE_STIND_I8:
case CEE_LDELEM_I8:
case CEE_STELEM_I8:
return &mono_defaults.int64_class->byval_arg;
case CEE_LDIND_R4:
case CEE_STIND_R4:
case CEE_LDELEM_R4:
case CEE_STELEM_R4:
return &mono_defaults.single_class->byval_arg;
case CEE_LDIND_R8:
case CEE_STIND_R8:
case CEE_LDELEM_R8:
case CEE_STELEM_R8:
return &mono_defaults.double_class->byval_arg;
case CEE_LDIND_I:
case CEE_STIND_I:
case CEE_LDELEM_I:
case CEE_STELEM_I:
return &mono_defaults.int_class->byval_arg;
case CEE_LDIND_REF:
case CEE_STIND_REF:
case CEE_LDELEM_REF:
case CEE_STELEM_REF:
return &mono_defaults.object_class->byval_arg;
default:
g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
return NULL;
}
}
static void
do_load_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
return;
}
if (opcode == CEE_LDIND_REF) {
if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
} else {
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
}
}
static void
do_store_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *addr, *val;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
val = stack_pop (ctx);
addr = stack_pop (ctx);
check_unmanaged_pointer (ctx, addr);
if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
return;
}
if (stack_slot_is_managed_mutability_pointer (addr)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
return;
}
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
}
static void
do_newarr (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
}
/*FIXME handle arrays that are not 0-indexed*/
static void
do_ldlen (VerifyContext *ctx)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
}
/*FIXME handle arrays that are not 0-indexed*/
/*FIXME handle readonly prefix and CMMP*/
static void
do_ldelema (VerifyContext *ctx, int klass_token)
{
ILStackDesc *index, *array, *res;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
gboolean valid;
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelema is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
} else {
valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
}
if (!valid)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
}
}
res = stack_push (ctx);
set_stack_value (ctx, res, type, TRUE);
if (ctx->prefix_set & PREFIX_READONLY) {
ctx->prefix_set &= ~PREFIX_READONLY;
res->stype |= CMMP_MASK;
}
}
/*
* FIXME handle arrays that are not 0-indexed
* FIXME handle readonly prefix and CMMP
*/
static void
do_ldelem (VerifyContext *ctx, int opcode, int token)
{
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
ILStackDesc *index, *array;
MonoType *type;
if (!check_underflow (ctx, 2))
return;
if (opcode == CEE_LDELEM) {
if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (opcode == CEE_LDELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
type = &array->type->data.klass->byval_arg;
} else {
MonoType *candidate = &array->type->data.klass->byval_arg;
if (IS_STRICT_MODE (ctx)) {
MonoType *underlying_type = mono_type_get_underlying_type_any (type);
MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
if ((IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I, MONO_TYPE_U)) ||
(IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
}
}
set_stack_value (ctx, stack_push (ctx), type, FALSE);
#undef IS_ONE_OF2
}
/*
* FIXME handle arrays that are not 0-indexed
*/
static void
do_stelem (VerifyContext *ctx, int opcode, int token)
{
ILStackDesc *index, *array, *value;
MonoType *type;
if (!check_underflow (ctx, 3))
return;
if (opcode == CEE_STELEM) {
if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
value = stack_pop (ctx);
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for stdelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for stelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
} else {
if (opcode == CEE_STELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
}
}
}
if (opcode == CEE_STELEM_REF) {
if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (opcode != CEE_STELEM_REF) {
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
}
}
static void
do_throw (VerifyContext *ctx)
{
ILStackDesc *exception;
if (!check_underflow (ctx, 1))
return;
exception = stack_pop (ctx);
if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
char *name = mono_type_full_name (exception->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type but found unboxed %s at 0x%04x ", name, ctx->ip_offset));
g_free (name);
}
/*The stack is left empty after a throw*/
ctx->eval.size = 0;
}
static void
do_endfilter (VerifyContext *ctx)
{
MonoExceptionClause *clause;
if (IS_STRICT_MODE (ctx)) {
if (ctx->eval.size != 1)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
}
if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
if (IS_STRICT_MODE (ctx)) {
if (ctx->ip_offset != clause->handler_offset - 2)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
} else {
if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
}
} else {
if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
else
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
}
ctx->eval.size = 0;
}
static void
do_leave (VerifyContext *ctx, int delta)
{
int target = ((gint32)ctx->ip_offset) + delta;
if (target >= ctx->code_size || target < 0)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
ctx->eval.size = 0;
}
/*
* do_static_branch:
*
* Verify br and br.s opcodes.
*/
static void
do_static_branch (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
}
ctx->target = target;
}
static void
do_switch (VerifyContext *ctx, int count, const unsigned char *data)
{
int i, base = ctx->ip_offset + 5 + count * 4;
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
for (i = 0; i < count; ++i) {
int target = base + read32 (data + i * 4);
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
return;
}
merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
}
}
static void
do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
{
ILStackDesc *top;
MonoMethod *method;
if (virtual && !check_underflow (ctx, 1))
return;
if (!virtual && !check_overflow (ctx))
return;
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
return;
if (mono_method_is_constructor (method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
if (virtual) {
ILStackDesc *top = stack_pop (ctx);
if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
if (method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
}
if (!mono_method_can_access_method_full (ctx->method, method, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Loaded method is not visible for ldftn/ldvirtftn at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
top->method = method;
}
static void
do_sizeof (VerifyContext *ctx, int token)
{
MonoType *type;
if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!(type = verifier_load_type (ctx, token, "sizeof")))
return;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
return;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
return;
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
}
/* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
static void
do_localloc (VerifyContext *ctx)
{
ILStackDesc *top;
if (ctx->eval.size != 1) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
/*TODO verify top type*/
top = stack_pop (ctx);
set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
}
static void
do_ldstr (VerifyContext *ctx, guint32 token)
{
GSList *error = NULL;
if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!ctx->image->dynamic && !mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
if (error)
ctx->list = g_slist_concat (ctx->list, error);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (check_overflow (ctx))
stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
}
static void
do_refanyval (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanyval, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, TRUE);
}
static void
do_refanytype (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanytype, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
}
static void
do_mkrefany (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (top)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a managed pointer for mkrefany, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
}else {
MonoType *stack_type = mono_type_get_type_byval (top->type);
if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
}
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
}
static void
do_ckfinite (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (stack_slot_get_underlying_type (top) != TYPE_R8)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected float32 or float64 on stack for ckfinit but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
stack_push_stack_val (ctx, top);
}
/*
* merge_stacks:
* Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
*
* @from holds new values for a given control path
* @to holds the current values of a given control path
*
* TODO we can eliminate the from argument as all callers pass &ctx->eval
*/
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
{
MonoError error;
int i, j, k;
stack_init (ctx, to);
if (start) {
if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
from->size = 0;
else
stack_copy (&ctx->eval, to);
goto end_verify;
} else if (!(to->flags & IL_CODE_STACK_MERGED)) {
stack_copy (to, &ctx->eval);
goto end_verify;
}
VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
if (from->size != to->size) {
VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not merge stacks, different sizes (%d x %d) at 0x%04x", from->size, to->size, ctx->ip_offset));
goto end_verify;
}
//FIXME we need to preserve CMMP attributes
//FIXME we must take null literals into consideration.
for (i = 0; i < from->size; ++i) {
ILStackDesc *new_slot = from->stack + i;
ILStackDesc *old_slot = to->stack + i;
MonoType *new_type = mono_type_from_stack_slot (new_slot);
MonoType *old_type = mono_type_from_stack_slot (old_slot);
MonoClass *old_class = mono_class_from_mono_type (old_type);
MonoClass *new_class = mono_class_from_mono_type (new_type);
MonoClass *match_class = NULL;
// S := T then U = S (new value is compatible with current value, keep current)
if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
copy_stack_value (new_slot, old_slot);
continue;
}
// T := S then U = T (old value is compatible with current value, use new)
if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
copy_stack_value (old_slot, new_slot);
continue;
}
if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
goto end_verify;
}
//both are reference types, use closest common super type
if (!mono_class_from_mono_type (old_type)->valuetype
&& !mono_class_from_mono_type (new_type)->valuetype
&& !stack_slot_is_managed_pointer (old_slot)
&& !stack_slot_is_managed_pointer (new_slot)) {
for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
match_class = old_class->supertypes [j];
goto match_found;
}
}
mono_class_setup_interfaces (old_class, &error);
if (!mono_error_ok (&error)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset));
mono_error_cleanup (&error);
goto end_verify;
}
for (j = 0; j < old_class->interface_count; ++j) {
for (k = 0; k < new_class->interface_count; ++k) {
if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
match_class = old_class->interfaces [j];
goto match_found;
}
}
}
//No decent super type found, use object
match_class = mono_defaults.object_class;
goto match_found;
} else if (is_compatible_boxed_valuetype (ctx,old_type, new_type, new_slot, FALSE) || is_compatible_boxed_valuetype (ctx, new_type, old_type, old_slot, FALSE)) {
match_class = mono_defaults.object_class;
goto match_found;
}
{
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
}
set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
goto end_verify;
match_found:
g_assert (match_class);
set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
continue;
}
end_verify:
if (external)
to->flags |= IL_CODE_FLAG_WAS_TARGET;
to->flags |= IL_CODE_STACK_MERGED;
}
#define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
#define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
/*
* is_clause_in_range :
*
* Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
*/
static gboolean
is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset >= start && clause->try_offset < end)
return TRUE;
if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
return TRUE;
return FALSE;
}
/*
* is_clause_inside_range :
*
* Returns TRUE if @clause lies completely inside the @start - @end range.
*/
static gboolean
is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
return FALSE;
if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
return FALSE;
return TRUE;
}
/*
* is_clause_nested :
*
* Returns TRUE if @nested is nested in @clause.
*/
static gboolean
is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
{
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
return TRUE;
return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
}
/* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
* the each pair of exception must have the following properties:
* - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
* - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
* - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
*/
static void
verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
{
/*clause is nested*/
if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
return;
}
/*wrong nesting order.*/
if (is_clause_nested (clause, to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
return;
}
/*mutual protection*/
if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
/*handlers are not disjoint*/
if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
return;
}
/* handlers are not catch or filter */
if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
return;
}
/*OK*/
return;
}
/*not completelly disjoint*/
if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
}
#define code_bounds_check(size) \
if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
break; \
} \
static gboolean
mono_opcode_is_prefix (int op)
{
switch (op) {
case MONO_CEE_UNALIGNED_:
case MONO_CEE_VOLATILE_:
case MONO_CEE_TAIL_:
case MONO_CEE_CONSTRAINED_:
case MONO_CEE_READONLY_:
return TRUE;
}
return FALSE;
}
/*
* FIXME: need to distinguish between valid and verifiable.
* Need to keep track of types on the stack.
* Verify types for opcodes.
*/
GSList*
mono_method_verify (MonoMethod *method, int level)
{
MonoError error;
const unsigned char *ip, *code_start;
const unsigned char *end;
MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
int i, n, need_merge = 0, start = 0;
guint token, ip_offset = 0, prefix = 0;
MonoGenericContext *generic_context = NULL;
MonoImage *image;
VerifyContext ctx;
GSList *tmp;
VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
init_verifier_stats ();
if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
return NULL;
}
memset (&ctx, 0, sizeof (VerifyContext));
//FIXME use mono_method_get_signature_full
ctx.signature = mono_method_signature (method);
if (!ctx.signature) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
finish_collect_stats ();
return ctx.list;
}
ctx.header = mono_method_get_header (method);
if (!ctx.header) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
finish_collect_stats ();
return ctx.list;
}
ctx.method = method;
code_start = ip = ctx.header->code;
end = ip + ctx.header->code_size;
ctx.image = image = method->klass->image;
ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
ctx.max_stack = ctx.header->max_stack;
ctx.verifiable = ctx.valid = 1;
ctx.level = level;
ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
ctx.code_size = ctx.header->code_size;
MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
ctx.num_locals = ctx.header->num_locals;
ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
if (ctx.num_locals > 0 && !ctx.header->init_locals)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
ctx.params = g_new (MonoType*, ctx.max_args);
MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
if (ctx.signature->hasthis)
ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
if (ctx.signature->is_inflated)
ctx.generic_context = generic_context = mono_method_get_context (method);
if (!generic_context && (method->klass->generic_container || method->is_generic)) {
if (method->is_generic)
ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
else
ctx.generic_context = generic_context = &method->klass->generic_container->context;
}
for (i = 0; i < ctx.num_locals; ++i) {
MonoType *uninflated = ctx.locals [i];
ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.num_locals = i;
ctx.max_args = 0;
goto cleanup;
}
}
for (i = 0; i < ctx.max_args; ++i) {
MonoType *uninflated = ctx.params [i];
ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.max_args = i;
goto cleanup;
}
}
stack_init (&ctx, &ctx.eval);
for (i = 0; i < ctx.num_locals; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
break;
if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.locals [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
g_free (name);
break;
}
}
for (i = 0; i < ctx.max_args; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
break;
if (get_stack_type (ctx.params [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.params [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
g_free (name);
break;
}
}
if (!ctx.valid)
goto cleanup;
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
VERIFIER_DEBUG (printf ("clause try %x len %x filter at %x handler at %x len %x\n", clause->try_offset, clause->try_len, clause->data.filter_offset, clause->handler_offset, clause->handler_len); );
if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
if (clause->try_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
if (clause->handler_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
if (clause->data.filter_offset > ctx.code_size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
if (clause->data.filter_offset >= clause->handler_offset)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
}
for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
if (!ctx.valid)
break;
ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->try_offset + clause->try_len < ctx.code_size)
ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->handler_offset + clause->handler_len < ctx.code_size)
ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
if (!clause->data.catch_class) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
break;
}
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
}
else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
}
}
original_bb = bb = mono_basic_block_split (method, &error);
if (!mono_error_ok (&error)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
mono_error_cleanup (&error);
goto cleanup;
}
g_assert (bb);
while (ip < end && ctx.valid) {
ip_offset = ip - code_start;
{
const unsigned char *ip_copy = ip;
int size, op;
if (ip_offset > bb->end) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
goto cleanup;
}
if (ip_offset == bb->end)
bb = bb->next;
size = mono_opcode_value_and_size (&ip_copy, end, &op);
if (size == -1) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
goto cleanup;
}
if (ADD_IS_GREATER_OR_OVF (ip_offset, size, bb->end)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
goto cleanup;
}
/*Last Instruction*/
if (ip_offset + size == bb->end && mono_opcode_is_prefix (op)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets between prefix '%s' and instruction at 0x%04x", mono_opcode_name (op), ip_offset));
goto cleanup;
}
if (bb->dead) {
/*FIXME remove this once we move all bad branch checking code to use BB only*/
ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
ip += size;
continue;
}
}
ctx.ip_offset = ip_offset = ip - code_start;
/*We need to check against fallthrou in and out of protected blocks.
* For fallout we check the once a protected block ends, if the start flag is not set.
* Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
* TODO convert these checks to be done using flags and not this loop
*/
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
start = 1;
}
if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
start = 1;
}
if (clause->handler_offset == ip_offset && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
start = 1;
}
}
if (!ctx.valid)
break;
if (need_merge) {
VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
need_merge = 0;
}
merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
start = 0;
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
#ifdef MONO_VERIFIER_DEBUG
{
char *discode;
discode = mono_disasm_code_one (NULL, method, ip, NULL);
discode [strlen (discode) - 1] = 0; /* no \n */
g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
g_free (discode);
}
dump_stack_state (&ctx.code [ip_offset]);
dump_stack_state (&ctx.eval);
#endif
switch (*ip) {
case CEE_NOP:
case CEE_BREAK:
++ip;
break;
case CEE_LDARG_0:
case CEE_LDARG_1:
case CEE_LDARG_2:
case CEE_LDARG_3:
push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
++ip;
break;
case CEE_LDARG_S:
case CEE_LDARGA_S:
code_bounds_check (2);
push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
ip += 2;
break;
case CEE_ADD_OVF_UN:
do_binop (&ctx, *ip, add_ovf_un_table);
++ip;
break;
case CEE_SUB_OVF_UN:
do_binop (&ctx, *ip, sub_ovf_un_table);
++ip;
break;
case CEE_ADD_OVF:
case CEE_SUB_OVF:
case CEE_MUL_OVF:
case CEE_MUL_OVF_UN:
do_binop (&ctx, *ip, bin_ovf_table);
++ip;
break;
case CEE_ADD:
do_binop (&ctx, *ip, add_table);
++ip;
break;
case CEE_SUB:
do_binop (&ctx, *ip, sub_table);
++ip;
break;
case CEE_MUL:
case CEE_DIV:
case CEE_REM:
do_binop (&ctx, *ip, bin_op_table);
++ip;
break;
case CEE_AND:
case CEE_DIV_UN:
case CEE_OR:
case CEE_REM_UN:
case CEE_XOR:
do_binop (&ctx, *ip, int_bin_op_table);
++ip;
break;
case CEE_SHL:
case CEE_SHR:
case CEE_SHR_UN:
do_binop (&ctx, *ip, shift_op_table);
++ip;
break;
case CEE_POP:
if (!check_underflow (&ctx, 1))
break;
stack_pop_safe (&ctx);
++ip;
break;
case CEE_RET:
do_ret (&ctx);
++ip;
start = 1;
break;
case CEE_LDLOC_0:
case CEE_LDLOC_1:
case CEE_LDLOC_2:
case CEE_LDLOC_3:
/*TODO support definite assignment verification? */
push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
++ip;
break;
case CEE_STLOC_0:
case CEE_STLOC_1:
case CEE_STLOC_2:
case CEE_STLOC_3:
store_local (&ctx, *ip - CEE_STLOC_0);
++ip;
break;
case CEE_STLOC_S:
code_bounds_check (2);
store_local (&ctx, ip [1]);
ip += 2;
break;
case CEE_STARG_S:
code_bounds_check (2);
store_arg (&ctx, ip [1]);
ip += 2;
break;
case CEE_LDC_I4_M1:
case CEE_LDC_I4_0:
case CEE_LDC_I4_1:
case CEE_LDC_I4_2:
case CEE_LDC_I4_3:
case CEE_LDC_I4_4:
case CEE_LDC_I4_5:
case CEE_LDC_I4_6:
case CEE_LDC_I4_7:
case CEE_LDC_I4_8:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
++ip;
break;
case CEE_LDC_I4_S:
code_bounds_check (2);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 2;
break;
case CEE_LDC_I4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 5;
break;
case CEE_LDC_I8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
ip += 9;
break;
case CEE_LDC_R4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 5;
break;
case CEE_LDC_R8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 9;
break;
case CEE_LDNULL:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
++ip;
break;
case CEE_BEQ_S:
case CEE_BNE_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
ip += 2;
need_merge = 1;
break;
case CEE_BGE_S:
case CEE_BGT_S:
case CEE_BLE_S:
case CEE_BLT_S:
case CEE_BGE_UN_S:
case CEE_BGT_UN_S:
case CEE_BLE_UN_S:
case CEE_BLT_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
ip += 2;
need_merge = 1;
break;
case CEE_BEQ:
case CEE_BNE_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
ip += 5;
need_merge = 1;
break;
case CEE_BGE:
case CEE_BGT:
case CEE_BLE:
case CEE_BLT:
case CEE_BGE_UN:
case CEE_BGT_UN:
case CEE_BLE_UN:
case CEE_BLT_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
ip += 5;
need_merge = 1;
break;
case CEE_LDLOC_S:
case CEE_LDLOCA_S:
code_bounds_check (2);
push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
ip += 2;
break;
case CEE_UNUSED99:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_DUP: {
ILStackDesc *top;
if (!check_underflow (&ctx, 1))
break;
if (!check_overflow (&ctx))
break;
top = stack_push (&ctx);
copy_stack_value (top, stack_peek (&ctx, 1));
++ip;
break;
}
case CEE_JMP:
code_bounds_check (5);
if (ctx.eval.size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
token = read32 (ip + 1);
if (in_any_block (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
/*
* FIXME: check signature, retval, arguments etc.
*/
ip += 5;
break;
case CEE_CALL:
case CEE_CALLVIRT:
code_bounds_check (5);
do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
ip += 5;
break;
case CEE_CALLI:
code_bounds_check (5);
token = read32 (ip + 1);
/*
* FIXME: check signature, retval, arguments etc.
* FIXME: check requirements for tail call
*/
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
ip += 5;
break;
case CEE_BR_S:
code_bounds_check (2);
do_static_branch (&ctx, (signed char)ip [1] + 2);
need_merge = 1;
ip += 2;
start = 1;
break;
case CEE_BRFALSE_S:
case CEE_BRTRUE_S:
code_bounds_check (2);
do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
ip += 2;
need_merge = 1;
break;
case CEE_BR:
code_bounds_check (5);
do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
need_merge = 1;
ip += 5;
start = 1;
break;
case CEE_BRFALSE:
case CEE_BRTRUE:
code_bounds_check (5);
do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
ip += 5;
need_merge = 1;
break;
case CEE_SWITCH: {
guint32 entries;
code_bounds_check (5);
entries = read32 (ip + 1);
if (entries > 0xFFFFFFFFU / sizeof (guint32))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
ip += 5;
code_bounds_check (sizeof (guint32) * entries);
do_switch (&ctx, entries, ip);
ip += sizeof (guint32) * entries;
break;
}
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_LDIND_I8:
case CEE_LDIND_I:
case CEE_LDIND_R4:
case CEE_LDIND_R8:
case CEE_LDIND_REF:
do_load_indirect (&ctx, *ip);
++ip;
break;
case CEE_STIND_REF:
case CEE_STIND_I1:
case CEE_STIND_I2:
case CEE_STIND_I4:
case CEE_STIND_I8:
case CEE_STIND_R4:
case CEE_STIND_R8:
case CEE_STIND_I:
do_store_indirect (&ctx, *ip);
++ip;
break;
case CEE_NOT:
case CEE_NEG:
do_unary_math_op (&ctx, *ip);
++ip;
break;
case CEE_CONV_I1:
case CEE_CONV_I2:
case CEE_CONV_I4:
case CEE_CONV_U1:
case CEE_CONV_U2:
case CEE_CONV_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_I8:
case CEE_CONV_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_R4:
case CEE_CONV_R8:
case CEE_CONV_R_UN:
do_conversion (&ctx, TYPE_R8);
++ip;
break;
case CEE_CONV_I:
case CEE_CONV_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_CPOBJ:
code_bounds_check (5);
do_cpobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDOBJ:
code_bounds_check (5);
do_ldobj_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDSTR:
code_bounds_check (5);
do_ldstr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWOBJ:
code_bounds_check (5);
do_newobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CASTCLASS:
case CEE_ISINST:
code_bounds_check (5);
do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
ip += 5;
break;
case CEE_UNUSED58:
case CEE_UNUSED1:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_UNBOX:
code_bounds_check (5);
do_unbox_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_THROW:
do_throw (&ctx);
start = 1;
++ip;
break;
case CEE_LDFLD:
case CEE_LDFLDA:
code_bounds_check (5);
do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
ip += 5;
break;
case CEE_LDSFLD:
case CEE_LDSFLDA:
code_bounds_check (5);
do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
ip += 5;
break;
case CEE_STFLD:
code_bounds_check (5);
do_store_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STSFLD:
code_bounds_check (5);
do_store_static_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STOBJ:
code_bounds_check (5);
do_stobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1_UN:
case CEE_CONV_OVF_I2_UN:
case CEE_CONV_OVF_I4_UN:
case CEE_CONV_OVF_U1_UN:
case CEE_CONV_OVF_U2_UN:
case CEE_CONV_OVF_U4_UN:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8_UN:
case CEE_CONV_OVF_U8_UN:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I_UN:
case CEE_CONV_OVF_U_UN:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_BOX:
code_bounds_check (5);
do_box_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWARR:
code_bounds_check (5);
do_newarr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDLEN:
do_ldlen (&ctx);
++ip;
break;
case CEE_LDELEMA:
code_bounds_check (5);
do_ldelema (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_LDELEM_I8:
case CEE_LDELEM_I:
case CEE_LDELEM_R4:
case CEE_LDELEM_R8:
case CEE_LDELEM_REF:
do_ldelem (&ctx, *ip, 0);
++ip;
break;
case CEE_STELEM_I:
case CEE_STELEM_I1:
case CEE_STELEM_I2:
case CEE_STELEM_I4:
case CEE_STELEM_I8:
case CEE_STELEM_R4:
case CEE_STELEM_R8:
case CEE_STELEM_REF:
do_stelem (&ctx, *ip, 0);
++ip;
break;
case CEE_LDELEM:
code_bounds_check (5);
do_ldelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_STELEM:
code_bounds_check (5);
do_stelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_UNBOX_ANY:
code_bounds_check (5);
do_unbox_any (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1:
case CEE_CONV_OVF_U1:
case CEE_CONV_OVF_I2:
case CEE_CONV_OVF_U2:
case CEE_CONV_OVF_I4:
case CEE_CONV_OVF_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8:
case CEE_CONV_OVF_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I:
case CEE_CONV_OVF_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_REFANYVAL:
code_bounds_check (5);
do_refanyval (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CKFINITE:
do_ckfinite (&ctx);
++ip;
break;
case CEE_MKREFANY:
code_bounds_check (5);
do_mkrefany (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDTOKEN:
code_bounds_check (5);
do_load_token (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_ENDFINALLY:
if (!is_correct_endfinally (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_LEAVE:
code_bounds_check (5);
do_leave (&ctx, read32 (ip + 1) + 5);
ip += 5;
start = 1;
break;
case CEE_LEAVE_S:
code_bounds_check (2);
do_leave (&ctx, (signed char)ip [1] + 2);
ip += 2;
start = 1;
break;
case CEE_PREFIX1:
code_bounds_check (2);
++ip;
switch (*ip) {
case CEE_STLOC:
code_bounds_check (3);
store_local (&ctx, read16 (ip + 1));
ip += 3;
break;
case CEE_CEQ:
do_cmp_op (&ctx, cmp_br_eq_op, *ip);
++ip;
break;
case CEE_CGT:
case CEE_CGT_UN:
case CEE_CLT:
case CEE_CLT_UN:
do_cmp_op (&ctx, cmp_br_op, *ip);
++ip;
break;
case CEE_STARG:
code_bounds_check (3);
store_arg (&ctx, read16 (ip + 1) );
ip += 3;
break;
case CEE_ARGLIST:
if (!check_overflow (&ctx))
break;
if (ctx.signature->call_convention != MONO_CALL_VARARG)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
++ip;
break;
case CEE_LDFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
ip += 5;
break;
case CEE_LDVIRTFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
ip += 5;
break;
case CEE_LDARG:
case CEE_LDARGA:
code_bounds_check (3);
push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
ip += 3;
break;
case CEE_LDLOC:
case CEE_LDLOCA:
code_bounds_check (3);
push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
ip += 3;
break;
case CEE_LOCALLOC:
do_localloc (&ctx);
++ip;
break;
case CEE_UNUSED56:
case CEE_UNUSED57:
case CEE_UNUSED70:
case CEE_UNUSED:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_ENDFILTER:
do_endfilter (&ctx);
start = 1;
++ip;
break;
case CEE_UNALIGNED_:
code_bounds_check (2);
prefix |= PREFIX_UNALIGNED;
ip += 2;
break;
case CEE_VOLATILE_:
prefix |= PREFIX_VOLATILE;
++ip;
break;
case CEE_TAIL_:
prefix |= PREFIX_TAIL;
++ip;
if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
break;
case CEE_INITOBJ:
code_bounds_check (5);
do_initobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONSTRAINED_:
code_bounds_check (5);
ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
prefix |= PREFIX_CONSTRAINED;
ip += 5;
break;
case CEE_READONLY_:
prefix |= PREFIX_READONLY;
ip++;
break;
case CEE_CPBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_INITBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_NO_:
ip += 2;
break;
case CEE_RETHROW:
if (!is_correct_rethrow (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_SIZEOF:
code_bounds_check (5);
do_sizeof (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_REFANYTYPE:
do_refanytype (&ctx);
++ip;
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
if (prefix) {
if (!ctx.prefix_set) //first prefix
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
ctx.prefix_set |= prefix;
ctx.has_flags = TRUE;
prefix = 0;
} else {
if (!ctx.has_flags)
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
if (ctx.prefix_set & PREFIX_CONSTRAINED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_READONLY)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_VOLATILE)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_UNALIGNED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
ctx.prefix_set = prefix = 0;
ctx.has_flags = FALSE;
}
}
/*
* if ip != end we overflowed: mark as error.
*/
if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
}
/*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
}
if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid call to a non-final virtual function in method with stdarg.0 or ldarga.0 at 0x%04x", i));
}
if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
char *method_name = mono_method_full_name (ctx.method, TRUE);
char *type = mono_type_get_full_name (ctx.method->klass);
if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor due to a TypeLoadException on base type.", method_name, type));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
g_free (method_name);
g_free (type);
}
cleanup:
if (ctx.code) {
for (i = 0; i < ctx.header->code_size; ++i) {
if (ctx.code [i].stack)
g_free (ctx.code [i].stack);
}
}
for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
g_free (tmp->data);
g_slist_free (ctx.funptrs);
for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
mono_metadata_free_type (tmp->data);
g_slist_free (ctx.exception_types);
for (i = 0; i < ctx.num_locals; ++i) {
if (ctx.locals [i])
mono_metadata_free_type (ctx.locals [i]);
}
for (i = 0; i < ctx.max_args; ++i) {
if (ctx.params [i])
mono_metadata_free_type (ctx.params [i]);
}
if (ctx.eval.stack)
g_free (ctx.eval.stack);
if (ctx.code)
g_free (ctx.code);
g_free (ctx.locals);
g_free (ctx.params);
mono_basic_block_free (original_bb);
mono_metadata_free_mh (ctx.header);
finish_collect_stats ();
return ctx.list;
}
char*
mono_verify_corlib ()
{
/* This is a public API function so cannot be removed */
return NULL;
}
/*
* Returns true if @method needs to be verified.
*
*/
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
}
/*
* Returns true if @klass need to be verified.
*
*/
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
}
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
return mono_verifier_is_class_full_trust (method->klass);
}
/*
* Returns if @klass is under full trust or not.
*
* TODO This code doesn't take CAS into account.
*
* Under verify_all all user code must be verifiable if no security option was set
*
*/
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
(klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
return trusted_location || klass->image == mono_defaults.corlib;
return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
{
return mono_method_verify (method,
(verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
| (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
| (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
}
static int
get_field_end (MonoClassField *field)
{
int align;
int size = mono_type_size (field->type, &align);
if (size == 0)
size = 4; /*FIXME Is this a safe bet?*/
return size + field->offset;
}
static gboolean
verify_class_for_overlapping_reference_fields (MonoClass *class)
{
int i = 0, j;
gpointer iter = NULL;
MonoClassField *field;
gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
/*We can't skip types with !has_references since this is calculated after we have run.*/
if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT))
return TRUE;
/*We must check for stuff overlapping reference fields.
The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
*/
while ((field = mono_class_get_fields (class, &iter))) {
int fieldEnd = get_field_end (field);
gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
++i;
if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
for (j = i; j < class->field.count; ++j) {
MonoClassField *other = &class->fields [j];
int otherEnd = get_field_end (other);
if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
continue;
if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
return FALSE;
}
}
return TRUE;
}
static guint
field_hash (gconstpointer key)
{
const MonoClassField *field = key;
return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
}
static gboolean
field_equals (gconstpointer _a, gconstpointer _b)
{
const MonoClassField *a = _a;
const MonoClassField *b = _b;
return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
}
static gboolean
verify_class_fields (MonoClass *class)
{
gpointer iter = NULL;
MonoClassField *field;
MonoGenericContext *context = mono_class_get_context (class);
GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
if (class->generic_container)
context = &class->generic_container->context;
while ((field = mono_class_get_fields (class, &iter)) != NULL) {
if (!mono_type_is_valid_type_in_context (field->type, context)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
if (g_hash_table_lookup (unique_fields, field)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
g_hash_table_insert (unique_fields, field, field);
}
g_hash_table_destroy (unique_fields);
return TRUE;
}
static gboolean
verify_interfaces (MonoClass *class)
{
int i;
for (i = 0; i < class->interface_count; ++i) {
MonoClass *iface = class->interfaces [i];
if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
{
int type;
gpointer iter = NULL;
MonoClassField *field;
MonoClass *field_class;
if (!class->valuetype)
return TRUE;
type = class->byval_arg.type;
/*primitive type fields are not properly decoded*/
if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
return TRUE;
while ((field = mono_class_get_fields (class, &iter)) != NULL) {
if (!field->type)
return FALSE;
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout (MonoClass *class)
{
gboolean res;
res = verify_valuetype_layout_with_target (class, class);
return res;
}
static gboolean
recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type)
{
int idx;
MonoClass **constraints;
MonoGenericParamInfo *param_info;
g_assert (mono_type_is_generic_argument (type));
idx = mono_type_get_generic_param_num (type);
if (mono_bitset_test_fast (used_args, idx))
return FALSE;
mono_bitset_set_fast (used_args, idx);
param_info = mono_generic_container_get_param_info (gc, idx);
if (!param_info->constraints)
return TRUE;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
return FALSE;
}
return TRUE;
}
static gboolean
verify_generic_parameters (MonoClass *class)
{
int i;
MonoGenericContainer *gc = class->generic_container;
MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0);
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass **constraints;
if (!param_info->constraints)
continue;
mono_bitset_clear_all (used_args);
mono_bitset_set_fast (used_args, i);
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context))
goto fail;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
goto fail;
}
}
mono_bitset_free (used_args);
return TRUE;
fail:
mono_bitset_free (used_args);
return FALSE;
}
/*
* Check if the class is verifiable.
*
* Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
* field and invalid generic instantiation are fatal errors.
*
* This method must be safe to be called from mono_class_init and all code must be carefull about that.
*
*/
gboolean
mono_verifier_verify_class (MonoClass *class)
{
/*Neither <Module>, object or ifaces have parent.*/
if (!class->parent &&
class != mono_defaults.object_class &&
!MONO_CLASS_IS_INTERFACE (class) &&
(!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
return FALSE;
if (class->parent && MONO_CLASS_IS_INTERFACE (class->parent))
return FALSE;
if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
return FALSE;
if (class->generic_container && !verify_generic_parameters (class))
return FALSE;
if (!verify_class_for_overlapping_reference_fields (class))
return FALSE;
if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
return FALSE;
if (class->generic_class == NULL && !verify_class_fields (class))
return FALSE;
if (class->valuetype && !verify_valuetype_layout (class))
return FALSE;
if (!verify_interfaces (class))
return FALSE;
return TRUE;
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
{
return mono_class_is_valid_generic_instantiation (NULL, class);
}
gboolean
mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)
{
if (!method->is_inflated)
return TRUE;
return mono_method_is_valid_generic_instantiation (NULL, method);
}
#else
gboolean
mono_verifier_verify_class (MonoClass *class)
{
/* The verifier was disabled at compile time */
return TRUE;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
{
/* The verifier was disabled at compile time */
return NULL;
}
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return FALSE;
}
GSList*
mono_method_verify (MonoMethod *method, int level)
{
/* The verifier was disabled at compile time */
return NULL;
}
void
mono_free_verify_list (GSList *list)
{
/* The verifier was disabled at compile time */
/* will always be null if verifier is disabled */
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
{
return TRUE;
}
gboolean
mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)
{
return TRUE;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4717_2 |
crossvul-cpp_data_good_5526_1 | /* -*- C -*-
* $Id$
*/
#include <ruby.h>
#include "dl.h"
#define SafeStringValuePtr(v) (rb_string_value(&v), rb_check_safe_obj(v), RSTRING_PTR(v))
VALUE rb_cDLHandle;
void
dlhandle_free(struct dl_handle *dlhandle)
{
if( dlhandle->ptr && dlhandle->open && dlhandle->enable_close ){
dlclose(dlhandle->ptr);
}
}
VALUE
rb_dlhandle_close(VALUE self)
{
struct dl_handle *dlhandle;
Data_Get_Struct(self, struct dl_handle, dlhandle);
dlhandle->open = 0;
return INT2NUM(dlclose(dlhandle->ptr));
}
VALUE
rb_dlhandle_s_allocate(VALUE klass)
{
VALUE obj;
struct dl_handle *dlhandle;
obj = Data_Make_Struct(rb_cDLHandle, struct dl_handle, 0,
dlhandle_free, dlhandle);
dlhandle->ptr = 0;
dlhandle->open = 0;
dlhandle->enable_close = 0;
return obj;
}
VALUE
rb_dlhandle_initialize(int argc, VALUE argv[], VALUE self)
{
void *ptr;
struct dl_handle *dlhandle;
VALUE lib, flag;
char *clib;
int cflag;
const char *err;
switch( rb_scan_args(argc, argv, "02", &lib, &flag) ){
case 0:
clib = NULL;
cflag = RTLD_LAZY | RTLD_GLOBAL;
break;
case 1:
clib = NIL_P(lib) ? NULL : SafeStringValuePtr(lib);
cflag = RTLD_LAZY | RTLD_GLOBAL;
break;
case 2:
clib = NIL_P(lib) ? NULL : SafeStringValuePtr(lib);
cflag = NUM2INT(flag);
break;
default:
rb_bug("rb_dlhandle_new");
}
ptr = dlopen(clib, cflag);
#if defined(HAVE_DLERROR)
if( !ptr && (err = dlerror()) ){
rb_raise(rb_eDLError, "%s", err);
}
#else
if( !ptr ){
err = dlerror();
rb_raise(rb_eDLError, "%s", err);
}
#endif
Data_Get_Struct(self, struct dl_handle, dlhandle);
if( dlhandle->ptr && dlhandle->open && dlhandle->enable_close ){
dlclose(dlhandle->ptr);
}
dlhandle->ptr = ptr;
dlhandle->open = 1;
dlhandle->enable_close = 0;
if( rb_block_given_p() ){
rb_ensure(rb_yield, self, rb_dlhandle_close, self);
}
return Qnil;
}
VALUE
rb_dlhandle_enable_close(VALUE self)
{
struct dl_handle *dlhandle;
Data_Get_Struct(self, struct dl_handle, dlhandle);
dlhandle->enable_close = 1;
return Qnil;
}
VALUE
rb_dlhandle_disable_close(VALUE self)
{
struct dl_handle *dlhandle;
Data_Get_Struct(self, struct dl_handle, dlhandle);
dlhandle->enable_close = 0;
return Qnil;
}
VALUE
rb_dlhandle_to_i(VALUE self)
{
struct dl_handle *dlhandle;
Data_Get_Struct(self, struct dl_handle, dlhandle);
return PTR2NUM(dlhandle);
}
VALUE
rb_dlhandle_sym(VALUE self, VALUE sym)
{
void (*func)();
struct dl_handle *dlhandle;
void *handle;
const char *name;
const char *err;
int i;
#if defined(HAVE_DLERROR)
# define CHECK_DLERROR if( err = dlerror() ){ func = 0; }
#else
# define CHECK_DLERROR
#endif
rb_secure(2);
name = SafeStringValuePtr(sym);
Data_Get_Struct(self, struct dl_handle, dlhandle);
if( ! dlhandle->open ){
rb_raise(rb_eDLError, "closed handle");
}
handle = dlhandle->ptr;
func = dlsym(handle, name);
CHECK_DLERROR;
#if defined(FUNC_STDCALL)
if( !func ){
int len = strlen(name);
char *name_n;
#if defined(__CYGWIN__) || defined(_WIN32) || defined(__MINGW32__)
{
char *name_a = (char*)xmalloc(len+2);
strcpy(name_a, name);
name_n = name_a;
name_a[len] = 'A';
name_a[len+1] = '\0';
func = dlsym(handle, name_a);
CHECK_DLERROR;
if( func ) goto found;
name_n = xrealloc(name_a, len+6);
}
#else
name_n = (char*)xmalloc(len+6);
#endif
memcpy(name_n, name, len);
name_n[len++] = '@';
for( i = 0; i < 256; i += 4 ){
sprintf(name_n + len, "%d", i);
func = dlsym(handle, name_n);
CHECK_DLERROR;
if( func ) break;
}
if( func ) goto found;
name_n[len-1] = 'A';
name_n[len++] = '@';
for( i = 0; i < 256; i += 4 ){
sprintf(name_n + len, "%d", i);
func = dlsym(handle, name_n);
CHECK_DLERROR;
if( func ) break;
}
found:
xfree(name_n);
}
#endif
if( !func ){
rb_raise(rb_eDLError, "unknown symbol \"%s\"", name);
}
return PTR2NUM(func);
}
void
Init_dlhandle()
{
rb_cDLHandle = rb_define_class_under(rb_mDL, "Handle", rb_cObject);
rb_define_alloc_func(rb_cDLHandle, rb_dlhandle_s_allocate);
rb_define_method(rb_cDLHandle, "initialize", rb_dlhandle_initialize, -1);
rb_define_method(rb_cDLHandle, "to_i", rb_dlhandle_to_i, 0);
rb_define_method(rb_cDLHandle, "close", rb_dlhandle_close, 0);
rb_define_method(rb_cDLHandle, "sym", rb_dlhandle_sym, 1);
rb_define_method(rb_cDLHandle, "[]", rb_dlhandle_sym, 1);
rb_define_method(rb_cDLHandle, "disable_close", rb_dlhandle_disable_close, 0);
rb_define_method(rb_cDLHandle, "enable_close", rb_dlhandle_enable_close, 0);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5526_1 |
crossvul-cpp_data_bad_191_0 | /*
* MPEG-4 decoder
* Copyright (c) 2000,2001 Fabrice Bellard
* Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define UNCHECKED_BITSTREAM_READER 1
#include "libavutil/internal.h"
#include "libavutil/opt.h"
#include "error_resilience.h"
#include "hwaccel.h"
#include "idctdsp.h"
#include "internal.h"
#include "mpegutils.h"
#include "mpegvideo.h"
#include "mpegvideodata.h"
#include "mpeg4video.h"
#include "h263.h"
#include "profiles.h"
#include "thread.h"
#include "xvididct.h"
/* The defines below define the number of bits that are read at once for
* reading vlc values. Changing these may improve speed and data cache needs
* be aware though that decreasing them may need the number of stages that is
* passed to get_vlc* to be increased. */
#define SPRITE_TRAJ_VLC_BITS 6
#define DC_VLC_BITS 9
#define MB_TYPE_B_VLC_BITS 4
#define STUDIO_INTRA_BITS 9
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb);
static VLC dc_lum, dc_chrom;
static VLC sprite_trajectory;
static VLC mb_type_b_vlc;
static const int mb_type_b_map[4] = {
MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
MB_TYPE_L0L1 | MB_TYPE_16x16,
MB_TYPE_L1 | MB_TYPE_16x16,
MB_TYPE_L0 | MB_TYPE_16x16,
};
/**
* Predict the ac.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir the ac prediction direction
*/
void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
{
int i;
int16_t *ac_val, *ac_val1;
int8_t *const qscale_table = s->current_picture.qscale_table;
/* find prediction */
ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
ac_val1 = ac_val;
if (s->ac_pred) {
if (dir == 0) {
const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
/* left prediction */
ac_val -= 16;
if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
n == 1 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
}
} else {
const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
/* top prediction */
ac_val -= 16 * s->block_wrap[n];
if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
n == 2 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
}
}
}
/* left copy */
for (i = 1; i < 8; i++)
ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
/* top copy */
for (i = 1; i < 8; i++)
ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
}
/**
* check if the next stuff is a resync marker or the end.
* @return 0 if not
*/
static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int bits_count = get_bits_count(&s->gb);
int v = show_bits(&s->gb, 16);
if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
return 0;
while (v <= 0xFF) {
if (s->pict_type == AV_PICTURE_TYPE_B ||
(v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
break;
skip_bits(&s->gb, 8 + s->pict_type);
bits_count += 8 + s->pict_type;
v = show_bits(&s->gb, 16);
}
if (bits_count + 8 >= s->gb.size_in_bits) {
v >>= 8;
v |= 0x7F >> (7 - (bits_count & 7));
if (v == 0x7F)
return s->mb_num;
} else {
if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
int len, mb_num;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
GetBitContext gb = s->gb;
skip_bits(&s->gb, 1);
align_get_bits(&s->gb);
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
mb_num = get_bits(&s->gb, mb_num_bits);
if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
mb_num= -1;
s->gb = gb;
if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
return mb_num;
}
}
return 0;
}
static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int a = 2 << s->sprite_warping_accuracy;
int rho = 3 - s->sprite_warping_accuracy;
int r = 16 / a;
int alpha = 1;
int beta = 0;
int w = s->width;
int h = s->height;
int min_ab, i, w2, h2, w3, h3;
int sprite_ref[4][2];
int virtual_ref[2][2];
int64_t sprite_offset[2][2];
int64_t sprite_delta[2][2];
// only true for rectangle shapes
const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 },
{ 0, s->height }, { s->width, s->height } };
int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
if (w <= 0 || h <= 0)
return AVERROR_INVALIDDATA;
/* the decoder was not properly initialized and we cannot continue */
if (sprite_trajectory.table == NULL)
return AVERROR_INVALIDDATA;
for (i = 0; i < ctx->num_sprite_warping_points; i++) {
int length;
int x = 0, y = 0;
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
x = get_xbits(gb, length);
if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
check_marker(s->avctx, gb, "before sprite_trajectory");
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
y = get_xbits(gb, length);
check_marker(s->avctx, gb, "after sprite_trajectory");
ctx->sprite_traj[i][0] = d[i][0] = x;
ctx->sprite_traj[i][1] = d[i][1] = y;
}
for (; i < 4; i++)
ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
while ((1 << alpha) < w)
alpha++;
while ((1 << beta) < h)
beta++; /* typo in the MPEG-4 std for the definition of w' and h' */
w2 = 1 << alpha;
h2 = 1 << beta;
// Note, the 4th point isn't used for GMC
if (ctx->divx_version == 500 && ctx->divx_build == 413) {
sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
} else {
sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
}
/* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
* sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
/* This is mostly identical to the MPEG-4 std (and is totally unreadable
* because of that...). Perhaps it should be reordered to be more readable.
* The idea behind this virtual_ref mess is to be able to use shifts later
* per pixel instead of divides so the distance between points is converted
* from w&h based to w2&h2 based which are of the 2^x form. */
virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w);
virtual_ref[0][1] = 16 * vop_ref[0][1] +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w);
virtual_ref[1][0] = 16 * vop_ref[0][0] +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h);
virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h);
switch (ctx->num_sprite_warping_points) {
case 0:
sprite_offset[0][0] =
sprite_offset[0][1] =
sprite_offset[1][0] =
sprite_offset[1][1] = 0;
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 1: // GMC only
sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];
sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];
sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
a * (vop_ref[0][0] / 2);
sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
a * (vop_ref[0][1] / 2);
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 2:
sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
ctx->sprite_shift[0] = alpha + rho;
ctx->sprite_shift[1] = alpha + rho + 2;
break;
case 3:
min_ab = FFMIN(alpha, beta);
w3 = w2 >> min_ab;
h3 = h2 >> min_ab;
sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3;
sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3;
sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3;
sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3;
ctx->sprite_shift[0] = alpha + beta + rho - min_ab;
ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2;
break;
}
/* try to simplify the situation */
if (sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
sprite_delta[0][1] == 0 &&
sprite_delta[1][0] == 0 &&
sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
sprite_offset[0][0] >>= ctx->sprite_shift[0];
sprite_offset[0][1] >>= ctx->sprite_shift[0];
sprite_offset[1][0] >>= ctx->sprite_shift[1];
sprite_offset[1][1] >>= ctx->sprite_shift[1];
sprite_delta[0][0] = a;
sprite_delta[0][1] = 0;
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] = 0;
ctx->sprite_shift[1] = 0;
s->real_sprite_warping_points = 1;
} else {
int shift_y = 16 - ctx->sprite_shift[0];
int shift_c = 16 - ctx->sprite_shift[1];
for (i = 0; i < 2; i++) {
if (shift_c < 0 || shift_y < 0 ||
FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c ||
FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y
) {
avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset");
goto overflow;
}
}
for (i = 0; i < 2; i++) {
sprite_offset[0][i] *= 1 << shift_y;
sprite_offset[1][i] *= 1 << shift_c;
sprite_delta[0][i] *= 1 << shift_y;
sprite_delta[1][i] *= 1 << shift_y;
ctx->sprite_shift[i] = 16;
}
for (i = 0; i < 2; i++) {
int64_t sd[2] = {
sprite_delta[i][0] - a * (1LL<<16),
sprite_delta[i][1] - a * (1LL<<16)
};
if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX ||
llabs(sd[0]) >= INT_MAX ||
llabs(sd[1]) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX
) {
avpriv_request_sample(s->avctx, "Overflow on sprite points");
goto overflow;
}
}
s->real_sprite_warping_points = ctx->num_sprite_warping_points;
}
for (i = 0; i < 4; i++) {
s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1];
s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1];
}
return 0;
overflow:
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
return AVERROR_PATCHWELCOME;
}
static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
MpegEncContext *s = &ctx->m;
int len = FFMIN(ctx->time_increment_bits + 3, 15);
get_bits(gb, len);
if (get_bits1(gb))
get_bits(gb, len);
check_marker(s->avctx, gb, "after new_pred");
return 0;
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
int header_extension = 0, mb_num, len;
/* is there enough space left for a video packet + header */
if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
return AVERROR_INVALIDDATA;
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
return AVERROR_INVALIDDATA;
}
if (ctx->shape != RECT_SHAPE) {
header_extension = get_bits1(&s->gb);
// FIXME more stuff here
}
mb_num = get_bits(&s->gb, mb_num_bits);
if (mb_num >= s->mb_num || !mb_num) {
av_log(s->avctx, AV_LOG_ERROR,
"illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
return AVERROR_INVALIDDATA;
}
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE) {
int qscale = get_bits(&s->gb, s->quant_precision);
if (qscale)
s->chroma_qscale = s->qscale = qscale;
}
if (ctx->shape == RECT_SHAPE)
header_extension = get_bits1(&s->gb);
if (header_extension) {
int time_incr = 0;
while (get_bits1(&s->gb) != 0)
time_incr++;
check_marker(s->avctx, &s->gb, "before time_increment in video packed header");
skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */
check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");
skip_bits(&s->gb, 2); /* vop coding type */
// FIXME not rect stuff here
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits(&s->gb, 3); /* intra dc vlc threshold */
// FIXME don't just ignore everything
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
return AVERROR_INVALIDDATA;
av_log(s->avctx, AV_LOG_ERROR, "untested\n");
}
// FIXME reduced res stuff here
if (s->pict_type != AV_PICTURE_TYPE_I) {
int f_code = get_bits(&s->gb, 3); /* fcode_for */
if (f_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (f_code=0)\n");
}
if (s->pict_type == AV_PICTURE_TYPE_B) {
int b_code = get_bits(&s->gb, 3);
if (b_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (b_code=0)\n");
}
}
}
if (ctx->new_pred)
decode_new_pred(ctx, &s->gb);
return 0;
}
static void reset_studio_dc_predictors(MpegEncContext *s)
{
/* Reset DC Predictors */
s->last_dc[0] =
s->last_dc[1] =
s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1);
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
GetBitContext *gb = &s->gb;
unsigned vlc_len;
uint16_t mb_num;
if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) {
vlc_len = av_log2(s->mb_width * s->mb_height) + 1;
mb_num = get_bits(gb, vlc_len);
if (mb_num >= s->mb_num)
return AVERROR_INVALIDDATA;
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE)
s->qscale = mpeg_get_qscale(s);
if (get_bits1(gb)) { /* slice_extension_flag */
skip_bits1(gb); /* intra_slice */
skip_bits1(gb); /* slice_VOP_id_enable */
skip_bits(gb, 6); /* slice_VOP_id */
while (get_bits1(gb)) /* extra_bit_slice */
skip_bits(gb, 8); /* extra_information_slice */
}
reset_studio_dc_predictors(s);
}
else {
return AVERROR_INVALIDDATA;
}
return 0;
}
/**
* Get the average motion vector for a GMC MB.
* @param n either 0 for the x component or 1 for y
* @return the average MV for a GMC MB
*/
static inline int get_amv(Mpeg4DecContext *ctx, int n)
{
MpegEncContext *s = &ctx->m;
int x, y, mb_v, sum, dx, dy, shift;
int len = 1 << (s->f_code + 4);
const int a = s->sprite_warping_accuracy;
if (s->workaround_bugs & FF_BUG_AMV)
len >>= s->quarter_sample;
if (s->real_sprite_warping_points == 1) {
if (ctx->divx_version == 500 && ctx->divx_build == 413)
sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
else
sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a);
} else {
dx = s->sprite_delta[n][0];
dy = s->sprite_delta[n][1];
shift = ctx->sprite_shift[0];
if (n)
dy -= 1 << (shift + a + 1);
else
dx -= 1 << (shift + a + 1);
mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;
sum = 0;
for (y = 0; y < 16; y++) {
int v;
v = mb_v + dy * y;
// FIXME optimize
for (x = 0; x < 16; x++) {
sum += v >> shift;
v += dx;
}
}
sum = RSHIFT(sum, a + 8 - s->quarter_sample);
}
if (sum < -len)
sum = -len;
else if (sum >= len)
sum = len - 1;
return sum;
}
/**
* Decode the dc value.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir_ptr the prediction direction will be stored here
* @return the quantized dc
*/
static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
{
int level, code;
if (n < 4)
code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
else
code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
if (code < 0 || code > 9 /* && s->nbit < 9 */) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
return AVERROR_INVALIDDATA;
}
if (code == 0) {
level = 0;
} else {
if (IS_3IV1) {
if (code == 1)
level = 2 * get_bits1(&s->gb) - 1;
else {
if (get_bits1(&s->gb))
level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
else
level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
}
} else {
level = get_xbits(&s->gb, code);
}
if (code > 8) {
if (get_bits1(&s->gb) == 0) { /* marker */
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
return AVERROR_INVALIDDATA;
}
}
}
}
return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
}
/**
* Decode first partition.
* @return number of MBs decoded or <0 if an error occurred
*/
static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
/* decode first partition */
s->first_slice_line = 1;
for (; s->mb_y < s->mb_height; s->mb_y++) {
ff_init_block_index(s);
for (; s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
int cbpc;
int dir = 0;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int i;
do {
if (show_bits_long(&s->gb, 19) == DC_MARKER)
return mb_num - 1;
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
s->cbp_table[xy] = cbpc & 3;
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mb_intra = 1;
if (cbpc & 4)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->mbintra_table[xy] = 1;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->pred_dir_table[xy] = dir;
} else { /* P/S_TYPE */
int mx, my, pred_x, pred_y, bits;
int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
const int stride = s->b8_stride * 2;
try_again:
bits = show_bits(&s->gb, 17);
if (bits == MOTION_MARKER)
return mb_num - 1;
skip_bits1(&s->gb);
if (bits & 0x10000) {
/* skip mb */
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
mx = my = 0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
continue;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (cbpc == 20)
goto try_again;
s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra) {
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mbintra_table[xy] = 1;
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = 0;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = 0;
} else {
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE &&
(cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
if ((cbpc & 16) == 0) {
/* 16x16 motion prediction */
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
if (!s->mcsel) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_L0;
} else {
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
} else {
int i;
s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
MB_TYPE_L0;
for (i = 0; i < 4; i++) {
int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
mot_val[0] = mx;
mot_val[1] = my;
}
}
}
}
}
s->mb_x = 0;
}
return mb_num;
}
/**
* decode second partition.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
{
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
s->mb_x = s->resync_mb_x;
s->first_slice_line = 1;
for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
ff_init_block_index(s);
for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
} else { /* P || S_TYPE */
if (IS_INTRA(s->current_picture.mb_type[xy])) {
int i;
int dir = 0;
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
s->pred_dir_table[xy] = dir;
} else if (IS_SKIP(s->current_picture.mb_type[xy])) {
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] = 0;
} else {
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
}
}
}
if (mb_num >= mb_count)
return 0;
s->mb_x = 0;
}
return 0;
}
/**
* Decode the first and second partition.
* @return <0 if error (and sets error type in the error_status_table)
*/
int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num;
int ret;
const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END;
mb_num = mpeg4_decode_partition_a(ctx);
if (mb_num <= 0) {
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return mb_num ? mb_num : AVERROR_INVALIDDATA;
}
if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return AVERROR_INVALIDDATA;
}
s->mb_num_left = mb_num;
if (s->pict_type == AV_PICTURE_TYPE_I) {
while (show_bits(&s->gb, 9) == 1)
skip_bits(&s->gb, 9);
if (get_bits_long(&s->gb, 19) != DC_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first I partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} else {
while (show_bits(&s->gb, 10) == 1)
skip_bits(&s->gb, 10);
if (get_bits(&s->gb, 17) != MOTION_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first P partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
}
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, part_a_end);
ret = mpeg4_decode_partition_b(s, mb_num);
if (ret < 0) {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, ER_DC_ERROR);
return ret;
} else {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, ER_DC_END);
}
return 0;
}
/**
* Decode a block.
* @return <0 if an error occurred
*/
static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
int n, int coded, int intra, int rvlc)
{
MpegEncContext *s = &ctx->m;
int level, i, last, run, qmul, qadd;
int av_uninit(dc_pred_dir);
RLTable *rl;
RL_VLC_ELEM *rl_vlc;
const uint8_t *scan_table;
// Note intra & rvlc should be optimized away if this is inlined
if (intra) {
if (ctx->use_intra_dc_vlc) {
/* DC coef */
if (s->partitioned_frame) {
level = s->dc_val[0][s->block_index[n]];
if (n < 4)
level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
else
level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
} else {
level = mpeg4_decode_dc(s, n, &dc_pred_dir);
if (level < 0)
return level;
}
block[0] = level;
i = 0;
} else {
i = -1;
ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
}
if (!coded)
goto not_coded;
if (rvlc) {
rl = &ff_rvlc_rl_intra;
rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
} else {
rl = &ff_mpeg4_rl_intra;
rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
}
if (s->ac_pred) {
if (dc_pred_dir == 0)
scan_table = s->intra_v_scantable.permutated; /* left */
else
scan_table = s->intra_h_scantable.permutated; /* top */
} else {
scan_table = s->intra_scantable.permutated;
}
qmul = 1;
qadd = 0;
} else {
i = -1;
if (!coded) {
s->block_last_index[n] = i;
return 0;
}
if (rvlc)
rl = &ff_rvlc_rl_inter;
else
rl = &ff_h263_rl_inter;
scan_table = s->intra_scantable.permutated;
if (s->mpeg_quant) {
qmul = 1;
qadd = 0;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[0];
} else {
qmul = s->qscale << 1;
qadd = (s->qscale - 1) | 1;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
}
}
{
OPEN_READER(re, &s->gb);
for (;;) {
UPDATE_CACHE(re, &s->gb);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
if (level == 0) {
/* escape */
if (rvlc) {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_UBITS(re, &s->gb, 11);
SKIP_CACHE(re, &s->gb, 11);
if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 5);
level = level * qmul + qadd;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
i += run + 1;
if (last)
i += 192;
} else {
int cache;
cache = GET_CACHE(re, &s->gb);
if (IS_3IV1)
cache ^= 0xC0000000;
if (cache & 0x80000000) {
if (cache & 0x40000000) {
/* third escape */
SKIP_CACHE(re, &s->gb, 2);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (IS_3IV1) {
level = SHOW_SBITS(re, &s->gb, 12);
LAST_SKIP_BITS(re, &s->gb, 12);
} else {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_SBITS(re, &s->gb, 12);
SKIP_CACHE(re, &s->gb, 12);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
}
#if 0
if (s->error_recognition >= FF_ER_COMPLIANT) {
const int abs_level= FFABS(level);
if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
const int run1= run - rl->max_run[last][abs_level] - 1;
if (abs_level <= rl->max_level[last][run]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (s->error_recognition > FF_ER_COMPLIANT) {
if (abs_level <= rl->max_level[last][run]*2) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
return AVERROR_INVALIDDATA;
}
}
}
}
#endif
if (level > 0)
level = level * qmul + qadd;
else
level = level * qmul - qadd;
if ((unsigned)(level + 2048) > 4095) {
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
if (level > 2560 || level < -2560) {
av_log(s->avctx, AV_LOG_ERROR,
"|level| overflow in 3. esc, qp=%d\n",
s->qscale);
return AVERROR_INVALIDDATA;
}
}
level = level < 0 ? -2048 : 2047;
}
i += run + 1;
if (last)
i += 192;
} else {
/* second escape */
SKIP_BITS(re, &s->gb, 2);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
} else {
/* first escape */
SKIP_BITS(re, &s->gb, 1);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run;
level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
}
} else {
i += run;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
if (i > 62) {
i -= 192;
if (i & (~63)) {
av_log(s->avctx, AV_LOG_ERROR,
"ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
block[scan_table[i]] = level;
break;
}
block[scan_table[i]] = level;
}
CLOSE_READER(re, &s->gb);
}
not_coded:
if (intra) {
if (!ctx->use_intra_dc_vlc) {
block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
i -= i >> 31; // if (i == -1) i = 0;
}
ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
if (s->ac_pred)
i = 63; // FIXME not optimal
}
s->block_last_index[n] = i;
return 0;
}
/**
* decode partition C of one MB.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbp, mb_type;
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
mb_type = s->current_picture.mb_type[xy];
cbp = s->cbp_table[xy];
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (s->current_picture.qscale_table[xy] != s->qscale)
ff_set_qscale(s, s->current_picture.qscale_table[xy]);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
int i;
for (i = 0; i < 4; i++) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
}
s->mb_intra = IS_INTRA(mb_type);
if (IS_SKIP(mb_type)) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S
&& ctx->vol_sprite_usage == GMC_SPRITE) {
s->mcsel = 1;
s->mb_skipped = 0;
} else {
s->mcsel = 0;
s->mb_skipped = 1;
}
} else if (s->mb_intra) {
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
} else if (!s->mb_intra) {
// s->mcsel = 0; // FIXME do we need to init that?
s->mv_dir = MV_DIR_FORWARD;
if (IS_8X8(mb_type)) {
s->mv_type = MV_TYPE_8X8;
} else {
s->mv_type = MV_TYPE_16X16;
}
}
} else { /* I-Frame */
s->mb_intra = 1;
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
}
if (!IS_SKIP(mb_type)) {
int i;
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"texture corrupted at %d %d %d\n",
s->mb_x, s->mb_y, s->mb_intra);
return AVERROR_INVALIDDATA;
}
cbp += cbp;
}
}
/* per-MB end of slice check */
if (--s->mb_num_left <= 0) {
if (mpeg4_is_resync(ctx))
return SLICE_END;
else
return SLICE_NOEND;
} else {
if (mpeg4_is_resync(ctx)) {
const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
if (s->cbp_table[xy + delta])
return SLICE_END;
}
return SLICE_OK;
}
}
static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
int16_t *mot_val;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
av_assert2(s->h263_pred);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
do {
if (get_bits1(&s->gb)) {
/* skip mb */
s->mb_intra = 0;
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 1;
s->mv[0][0][0] = get_amv(ctx, 0);
s->mv[0][0][1] = get_amv(ctx, 1);
s->mb_skipped = 0;
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 0;
s->mv[0][0][0] = 0;
s->mv[0][0][1] = 0;
s->mb_skipped = 1;
}
goto end;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 20);
s->bdsp.clear_blocks(s->block[0]);
dquant = cbpc & 8;
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra)
goto intra;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if ((!s->progressive_sequence) &&
(cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
s->interlaced_dct = get_bits1(&s->gb);
s->mv_dir = MV_DIR_FORWARD;
if ((cbpc & 16) == 0) {
if (s->mcsel) {
s->current_picture.mb_type[xy] = MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
/* 16x16 global motion prediction */
s->mv_type = MV_TYPE_16X16;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
} else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
MB_TYPE_L0 |
MB_TYPE_INTERLACED;
/* 16x8 field motion prediction */
s->mv_type = MV_TYPE_FIELD;
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
/* 16x16 motion prediction */
s->mv_type = MV_TYPE_16X16;
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
s->mv_type = MV_TYPE_8X8;
for (i = 0; i < 4; i++) {
mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
mot_val[0] = mx;
mot_val[1] = my;
}
}
} else if (s->pict_type == AV_PICTURE_TYPE_B) {
int modb1; // first bit of modb
int modb2; // second bit of modb
int mb_type;
s->mb_intra = 0; // B-frames never contain intra blocks
s->mcsel = 0; // ... true gmc blocks
if (s->mb_x == 0) {
for (i = 0; i < 2; i++) {
s->last_mv[i][0][0] =
s->last_mv[i][0][1] =
s->last_mv[i][1][0] =
s->last_mv[i][1][1] = 0;
}
ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
}
/* if we skipped it in the future P-frame than skip it now too */
s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
if (s->mb_skipped) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
s->mv[0][0][0] =
s->mv[0][0][1] =
s->mv[1][0][0] =
s->mv[1][0][1] = 0;
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
goto end;
}
modb1 = get_bits1(&s->gb);
if (modb1) {
// like MB_TYPE_B_DIRECT but no vectors coded
mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
cbp = 0;
} else {
modb2 = get_bits1(&s->gb);
mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
if (mb_type < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
return AVERROR_INVALIDDATA;
}
mb_type = mb_type_b_map[mb_type];
if (modb2) {
cbp = 0;
} else {
s->bdsp.clear_blocks(s->block[0]);
cbp = get_bits(&s->gb, 6);
}
if ((!IS_DIRECT(mb_type)) && cbp) {
if (get_bits1(&s->gb))
ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
}
if (!s->progressive_sequence) {
if (cbp)
s->interlaced_dct = get_bits1(&s->gb);
if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
mb_type &= ~MB_TYPE_16x16;
if (USES_LIST(mb_type, 0)) {
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
}
if (USES_LIST(mb_type, 1)) {
s->field_select[1][0] = get_bits1(&s->gb);
s->field_select[1][1] = get_bits1(&s->gb);
}
}
}
s->mv_dir = 0;
if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
s->mv_type = MV_TYPE_16X16;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
s->last_mv[0][1][0] =
s->last_mv[0][0][0] =
s->mv[0][0][0] = mx;
s->last_mv[0][1][1] =
s->last_mv[0][0][1] =
s->mv[0][0][1] = my;
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
s->last_mv[1][1][0] =
s->last_mv[1][0][0] =
s->mv[1][0][0] = mx;
s->last_mv[1][1][1] =
s->last_mv[1][0][1] =
s->mv[1][0][1] = my;
}
} else if (!IS_DIRECT(mb_type)) {
s->mv_type = MV_TYPE_FIELD;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
s->last_mv[0][i][0] =
s->mv[0][i][0] = mx;
s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
}
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
s->last_mv[1][i][0] =
s->mv[1][i][0] = mx;
s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
}
}
}
}
if (IS_DIRECT(mb_type)) {
if (IS_SKIP(mb_type)) {
mx =
my = 0;
} else {
mx = ff_h263_decode_motion(s, 0, 1);
my = ff_h263_decode_motion(s, 0, 1);
}
s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
}
s->current_picture.mb_type[xy] = mb_type;
} else { /* I-Frame */
do {
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
dquant = cbpc & 4;
s->mb_intra = 1;
intra:
s->ac_pred = get_bits1(&s->gb);
if (s->ac_pred)
s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
else
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if (!s->progressive_sequence)
s->interlaced_dct = get_bits1(&s->gb);
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
goto end;
}
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
end:
/* per-MB end of slice check */
if (s->codec_id == AV_CODEC_ID_MPEG4) {
int next = mpeg4_is_resync(ctx);
if (next) {
if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
return AVERROR_INVALIDDATA;
} else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
return SLICE_END;
if (s->pict_type == AV_PICTURE_TYPE_B) {
const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
ff_thread_await_progress(&s->next_picture_ptr->tf,
(s->mb_x + delta >= s->mb_width)
? FFMIN(s->mb_y + 1, s->mb_height - 1)
: s->mb_y, 0);
if (s->next_picture.mbskip_table[xy + delta])
return SLICE_OK;
}
return SLICE_END;
}
}
return SLICE_OK;
}
/* As per spec, studio start code search isn't the same as the old type of start code */
static void next_start_code_studio(GetBitContext *gb)
{
align_get_bits(gb);
while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) {
get_bits(gb, 8);
}
}
/* additional_code, vlc index */
static const uint8_t ac_state_tab[22][2] =
{
{0, 0},
{0, 1},
{1, 1},
{2, 1},
{3, 1},
{4, 1},
{5, 1},
{1, 2},
{2, 2},
{3, 2},
{4, 2},
{5, 2},
{6, 2},
{1, 3},
{2, 4},
{3, 5},
{4, 6},
{5, 7},
{6, 8},
{7, 9},
{8, 10},
{0, 11}
};
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
{
int i;
/* StudioMacroblock */
/* Assumes I-VOP */
s->mb_intra = 1;
if (get_bits1(&s->gb)) { /* compression_mode */
/* DCT */
/* macroblock_type, 1 or 2-bit VLC */
if (!get_bits1(&s->gb)) {
skip_bits1(&s->gb);
s->qscale = mpeg_get_qscale(s);
}
for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
} else {
/* DPCM */
check_marker(s->avctx, &s->gb, "DPCM block start");
avpriv_request_sample(s->avctx, "DPCM encoded block");
next_start_code_studio(&s->gb);
return SLICE_ERROR;
}
if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
next_start_code_studio(&s->gb);
return SLICE_END;
}
return SLICE_OK;
}
static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
{
int hours, minutes, seconds;
if (!show_bits(gb, 23)) {
av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
return AVERROR_INVALIDDATA;
}
hours = get_bits(gb, 5);
minutes = get_bits(gb, 6);
check_marker(s->avctx, gb, "in gop_header");
seconds = get_bits(gb, 6);
s->time_base = seconds + 60*(minutes + 60*hours);
skip_bits1(gb);
skip_bits1(gb);
return 0;
}
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb)
{
s->avctx->profile = get_bits(gb, 4);
s->avctx->level = get_bits(gb, 4);
// for Simple profile, level 0
if (s->avctx->profile == 0 && s->avctx->level == 8) {
s->avctx->level = 0;
}
return 0;
}
static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb)
{
int visual_object_type;
int is_visual_object_identifier = get_bits1(gb);
if (is_visual_object_identifier) {
skip_bits(gb, 4+3);
}
visual_object_type = get_bits(gb, 4);
if (visual_object_type == VOT_VIDEO_ID ||
visual_object_type == VOT_STILL_TEXTURE_ID) {
int video_signal_type = get_bits1(gb);
if (video_signal_type) {
int video_range, color_description;
skip_bits(gb, 3); // video_format
video_range = get_bits1(gb);
color_description = get_bits1(gb);
s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
if (color_description) {
s->avctx->color_primaries = get_bits(gb, 8);
s->avctx->color_trc = get_bits(gb, 8);
s->avctx->colorspace = get_bits(gb, 8);
}
}
}
return 0;
}
static void mpeg4_load_default_matrices(MpegEncContext *s)
{
int i, v;
/* load default matrices */
for (i = 0; i < 64; i++) {
int j = s->idsp.idct_permutation[i];
v = ff_mpeg4_default_intra_matrix[i];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
v = ff_mpeg4_default_non_intra_matrix[i];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
}
static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height, vo_ver_id;
/* vol header */
skip_bits(gb, 1); /* random access */
s->vo_type = get_bits(gb, 8);
/* If we are in studio profile (per vo_type), check if its all consistent
* and if so continue pass control to decode_studio_vol_header().
* elIf something is inconsistent, error out
* else continue with (non studio) vol header decpoding.
*/
if (s->vo_type == CORE_STUDIO_VO_TYPE ||
s->vo_type == SIMPLE_STUDIO_VO_TYPE) {
if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO)
return AVERROR_INVALIDDATA;
s->studio_profile = 1;
s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO;
return decode_studio_vol_header(ctx, gb);
} else if (s->studio_profile) {
return AVERROR_PATCHWELCOME;
}
if (get_bits1(gb) != 0) { /* is_ol_id */
vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
skip_bits(gb, 3); /* vo_priority */
} else {
vo_ver_id = 1;
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
int chroma_format = get_bits(gb, 2);
if (chroma_format != CHROMA_420)
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
s->low_delay = get_bits1(gb);
if (get_bits1(gb)) { /* vbv parameters */
get_bits(gb, 15); /* first_half_bitrate */
check_marker(s->avctx, gb, "after first_half_bitrate");
get_bits(gb, 15); /* latter_half_bitrate */
check_marker(s->avctx, gb, "after latter_half_bitrate");
get_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
get_bits(gb, 3); /* latter_half_vbv_buffer_size */
get_bits(gb, 11); /* first_half_vbv_occupancy */
check_marker(s->avctx, gb, "after first_half_vbv_occupancy");
get_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
}
} else {
/* is setting low delay flag only once the smartest thing to do?
* low delay detection will not be overridden. */
if (s->picture_number == 0) {
switch(s->vo_type) {
case SIMPLE_VO_TYPE:
case ADV_SIMPLE_VO_TYPE:
s->low_delay = 1;
break;
default:
s->low_delay = 0;
}
}
}
ctx->shape = get_bits(gb, 2); /* vol shape */
if (ctx->shape != RECT_SHAPE)
av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
skip_bits(gb, 4); /* video_object_layer_shape_extension */
}
check_marker(s->avctx, gb, "before time_increment_resolution");
s->avctx->framerate.num = get_bits(gb, 16);
if (!s->avctx->framerate.num) {
av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
return AVERROR_INVALIDDATA;
}
ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
if (ctx->time_increment_bits < 1)
ctx->time_increment_bits = 1;
check_marker(s->avctx, gb, "before fixed_vop_rate");
if (get_bits1(gb) != 0) /* fixed_vop_rate */
s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
else
s->avctx->framerate.den = 1;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
ctx->t_frame = 0;
if (ctx->shape != BIN_ONLY_SHAPE) {
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before width");
width = get_bits(gb, 13);
check_marker(s->avctx, gb, "before height");
height = get_bits(gb, 13);
check_marker(s->avctx, gb, "after height");
if (width && height && /* they should be non zero but who knows */
!(s->width && s->codec_tag == AV_RL32("MP4S"))) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->progressive_sequence =
s->progressive_frame = get_bits1(gb) ^ 1;
s->interlaced_dct = 0;
if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */
"MPEG-4 OBMC not supported (very likely buggy encoder)\n");
if (vo_ver_id == 1)
ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
else
ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE) {
if (ctx->vol_sprite_usage == STATIC_SPRITE) {
skip_bits(gb, 13); // sprite_width
check_marker(s->avctx, gb, "after sprite_width");
skip_bits(gb, 13); // sprite_height
check_marker(s->avctx, gb, "after sprite_height");
skip_bits(gb, 13); // sprite_left
check_marker(s->avctx, gb, "after sprite_left");
skip_bits(gb, 13); // sprite_top
check_marker(s->avctx, gb, "after sprite_top");
}
ctx->num_sprite_warping_points = get_bits(gb, 6);
if (ctx->num_sprite_warping_points > 3) {
av_log(s->avctx, AV_LOG_ERROR,
"%d sprite_warping_points\n",
ctx->num_sprite_warping_points);
ctx->num_sprite_warping_points = 0;
return AVERROR_INVALIDDATA;
}
s->sprite_warping_accuracy = get_bits(gb, 2);
ctx->sprite_brightness_change = get_bits1(gb);
if (ctx->vol_sprite_usage == STATIC_SPRITE)
skip_bits1(gb); // low_latency_sprite
}
// FIXME sadct disable bit if verid!=1 && shape not rect
if (get_bits1(gb) == 1) { /* not_8_bit */
s->quant_precision = get_bits(gb, 4); /* quant_precision */
if (get_bits(gb, 4) != 8) /* bits_per_pixel */
av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
if (s->quant_precision != 5)
av_log(s->avctx, AV_LOG_ERROR,
"quant precision %d\n", s->quant_precision);
if (s->quant_precision<3 || s->quant_precision>9) {
s->quant_precision = 5;
}
} else {
s->quant_precision = 5;
}
// FIXME a bunch of grayscale shape things
if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
int i, v;
mpeg4_load_default_matrices(s);
/* load custom intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
}
/* load custom non intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = last;
s->chroma_inter_matrix[j] = last;
}
}
// FIXME a bunch of grayscale shape things
}
if (vo_ver_id != 1)
s->quarter_sample = get_bits1(gb);
else
s->quarter_sample = 0;
if (get_bits_left(gb) < 4) {
av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
return AVERROR_INVALIDDATA;
}
if (!get_bits1(gb)) {
int pos = get_bits_count(gb);
int estimation_method = get_bits(gb, 2);
if (estimation_method < 2) {
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */
ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */
ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (estimation_method == 1) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */
}
} else
av_log(s->avctx, AV_LOG_ERROR,
"Invalid Complexity estimation method %d\n",
estimation_method);
} else {
no_cplx_est:
ctx->cplx_estimation_trash_i =
ctx->cplx_estimation_trash_p =
ctx->cplx_estimation_trash_b = 0;
}
ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
s->data_partitioning = get_bits1(gb);
if (s->data_partitioning)
ctx->rvlc = get_bits1(gb);
if (vo_ver_id != 1) {
ctx->new_pred = get_bits1(gb);
if (ctx->new_pred) {
av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
skip_bits(gb, 2); /* requested upstream message type */
skip_bits1(gb); /* newpred segment type */
}
if (get_bits1(gb)) // reduced_res_vop
av_log(s->avctx, AV_LOG_ERROR,
"reduced resolution VOP not supported\n");
} else {
ctx->new_pred = 0;
}
ctx->scalability = get_bits1(gb);
if (ctx->scalability) {
GetBitContext bak = *gb;
int h_sampling_factor_n;
int h_sampling_factor_m;
int v_sampling_factor_n;
int v_sampling_factor_m;
skip_bits1(gb); // hierarchy_type
skip_bits(gb, 4); /* ref_layer_id */
skip_bits1(gb); /* ref_layer_sampling_dir */
h_sampling_factor_n = get_bits(gb, 5);
h_sampling_factor_m = get_bits(gb, 5);
v_sampling_factor_n = get_bits(gb, 5);
v_sampling_factor_m = get_bits(gb, 5);
ctx->enhancement_type = get_bits1(gb);
if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
/* illegal scalability header (VERY broken encoder),
* trying to workaround */
ctx->scalability = 0;
*gb = bak;
} else
av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
// bin shape stuff FIXME
}
}
if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n",
s->avctx->framerate.den, s->avctx->framerate.num,
ctx->time_increment_bits,
s->quant_precision,
s->progressive_sequence,
s->low_delay,
ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
);
}
return 0;
}
/**
* Decode the user data stuff in the header.
* Also initializes divx/xvid/lavc_version/build.
*/
static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
char buf[256];
int i;
int e;
int ver = 0, build = 0, ver2 = 0, ver3 = 0;
char last;
for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
if (show_bits(gb, 23) == 0)
break;
buf[i] = get_bits(gb, 8);
}
buf[i] = 0;
/* divx detection */
e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
if (e < 2)
e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
if (e >= 2) {
ctx->divx_version = ver;
ctx->divx_build = build;
s->divx_packed = e == 3 && last == 'p';
}
/* libavcodec detection */
e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
if (e != 4)
e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
if (e != 4) {
e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
if (e > 1) {
if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) {
av_log(s->avctx, AV_LOG_WARNING,
"Unknown Lavc version string encountered, %d.%d.%d; "
"clamping sub-version values to 8-bits.\n",
ver, ver2, ver3);
}
build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF);
}
}
if (e != 4) {
if (strcmp(buf, "ffmpeg") == 0)
ctx->lavc_build = 4600;
}
if (e == 4)
ctx->lavc_build = build;
/* Xvid detection */
e = sscanf(buf, "XviD%d", &build);
if (e == 1)
ctx->xvid_build = build;
return 0;
}
int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
if (s->codec_tag == AV_RL32("XVID") ||
s->codec_tag == AV_RL32("XVIX") ||
s->codec_tag == AV_RL32("RMP4") ||
s->codec_tag == AV_RL32("ZMP4") ||
s->codec_tag == AV_RL32("SIPP"))
ctx->xvid_build = 0;
}
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
ctx->vol_control_parameters == 0)
ctx->divx_version = 400; // divx 4
if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
ctx->divx_version =
ctx->divx_build = -1;
}
if (s->workaround_bugs & FF_BUG_AUTODETECT) {
if (s->codec_tag == AV_RL32("XVIX"))
s->workaround_bugs |= FF_BUG_XVID_ILACE;
if (s->codec_tag == AV_RL32("UMP4"))
s->workaround_bugs |= FF_BUG_UMP4;
if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->divx_version > 502 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
if (ctx->xvid_build <= 3U)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->xvid_build <= 1U)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->xvid_build <= 12U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->xvid_build <= 32U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
#define SET_QPEL_FUNC(postfix1, postfix2) \
s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \
s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \
s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2;
if (ctx->lavc_build < 4653U)
s->workaround_bugs |= FF_BUG_STD_QPEL;
if (ctx->lavc_build < 4655U)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->lavc_build < 4670U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->lavc_build <= 4712U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
if ((ctx->lavc_build&0xFF) >= 100) {
if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 &&
(ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+
)
s->workaround_bugs |= FF_BUG_IEDGE;
}
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->divx_version < 500U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
}
if (s->workaround_bugs & FF_BUG_STD_QPEL) {
SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
}
if (avctx->debug & FF_DEBUG_BUGS)
av_log(s->avctx, AV_LOG_DEBUG,
"bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
s->codec_id == AV_CODEC_ID_MPEG4 &&
avctx->idct_algo == FF_IDCT_AUTO) {
avctx->idct_algo = FF_IDCT_XVID;
ff_mpv_idct_init(s);
return 1;
}
return 0;
}
static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int time_incr, time_increment;
int64_t pts;
s->mcsel = 0;
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */
if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
s->low_delay = 0;
}
s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
if (s->partitioned_frame)
s->decode_mb = mpeg4_decode_partitioned_mb;
else
s->decode_mb = mpeg4_decode_mb;
time_incr = 0;
while (get_bits1(gb) != 0)
time_incr++;
check_marker(s->avctx, gb, "before time_increment");
if (ctx->time_increment_bits == 0 ||
!(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits);
for (ctx->time_increment_bits = 1;
ctx->time_increment_bits < 16;
ctx->time_increment_bits++) {
if (s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE)) {
if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
break;
} else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
break;
}
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
s->avctx->framerate.num = 1<<ctx->time_increment_bits;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
}
}
if (IS_3IV1)
time_increment = get_bits1(gb); // FIXME investigate further
else
time_increment = get_bits(gb, ctx->time_increment_bits);
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->last_time_base = s->time_base;
s->time_base += time_incr;
s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment;
if (s->workaround_bugs & FF_BUG_UMP4) {
if (s->time < s->last_non_b_time) {
/* header is not mpeg-4-compatible, broken encoder,
* trying to workaround */
s->time_base++;
s->time += s->avctx->framerate.num;
}
}
s->pp_time = s->time - s->last_non_b_time;
s->last_non_b_time = s->time;
} else {
s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment;
s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
if (s->pp_time <= s->pb_time ||
s->pp_time <= s->pp_time - s->pb_time ||
s->pp_time <= 0) {
/* messed up order, maybe after seeking? skipping current B-frame */
return FRAME_SKIPPED;
}
ff_mpeg4_init_direct_mv(s);
if (ctx->t_frame == 0)
ctx->t_frame = s->pb_time;
if (ctx->t_frame == 0)
ctx->t_frame = 1; // 1/0 protection
s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
s->pb_field_time = 2;
s->pp_field_time = 4;
if (!s->progressive_sequence)
return FRAME_SKIPPED;
}
}
if (s->avctx->framerate.den)
pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
else
pts = AV_NOPTS_VALUE;
ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
check_marker(s->avctx, gb, "before vop_coded");
/* vop coded */
if (get_bits1(gb) != 1) {
if (s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
return FRAME_SKIPPED;
}
if (ctx->new_pred)
decode_new_pred(ctx, gb);
if (ctx->shape != BIN_ONLY_SHAPE &&
(s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE))) {
/* rounding type for motion estimation */
s->no_rounding = get_bits1(gb);
} else {
s->no_rounding = 0;
}
// FIXME reduced res stuff
if (ctx->shape != RECT_SHAPE) {
if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
skip_bits(gb, 13); /* width */
check_marker(s->avctx, gb, "after width");
skip_bits(gb, 13); /* height */
check_marker(s->avctx, gb, "after height");
skip_bits(gb, 13); /* hor_spat_ref */
check_marker(s->avctx, gb, "after hor_spat_ref");
skip_bits(gb, 13); /* ver_spat_ref */
}
skip_bits1(gb); /* change_CR_disable */
if (get_bits1(gb) != 0)
skip_bits(gb, 8); /* constant_alpha_value */
}
// FIXME complexity estimation stuff
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits_long(gb, ctx->cplx_estimation_trash_i);
if (s->pict_type != AV_PICTURE_TYPE_I)
skip_bits_long(gb, ctx->cplx_estimation_trash_p);
if (s->pict_type == AV_PICTURE_TYPE_B)
skip_bits_long(gb, ctx->cplx_estimation_trash_b);
if (get_bits_left(gb) < 3) {
av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
return AVERROR_INVALIDDATA;
}
ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
if (!s->progressive_sequence) {
s->top_field_first = get_bits1(gb);
s->alternate_scan = get_bits1(gb);
} else
s->alternate_scan = 0;
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
if (s->pict_type == AV_PICTURE_TYPE_S) {
if((ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE)) {
if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
return AVERROR_INVALIDDATA;
if (ctx->sprite_brightness_change)
av_log(s->avctx, AV_LOG_ERROR,
"sprite_brightness_change not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
} else {
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
}
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
if (s->qscale == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (qscale=0)\n");
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
if (s->pict_type != AV_PICTURE_TYPE_I) {
s->f_code = get_bits(gb, 3); /* fcode_for */
if (s->f_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (f_code=0)\n");
s->f_code = 1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
} else
s->f_code = 1;
if (s->pict_type == AV_PICTURE_TYPE_B) {
s->b_code = get_bits(gb, 3);
if (s->b_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG4 header (b_code=0)\n");
s->b_code=1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
}
} else
s->b_code = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG,
"qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
s->qscale, s->f_code, s->b_code,
s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
s->top_field_first, s->quarter_sample ? "q" : "h",
s->data_partitioning, ctx->resync_marker,
ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
1 - s->no_rounding, s->vo_type,
ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
ctx->cplx_estimation_trash_b,
s->time,
time_increment
);
}
if (!ctx->scalability) {
if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
skip_bits1(gb); // vop shape coding type
} else {
if (ctx->enhancement_type) {
int load_backward_shape = get_bits1(gb);
if (load_backward_shape)
av_log(s->avctx, AV_LOG_ERROR,
"load backward shape isn't supported\n");
}
skip_bits(gb, 2); // ref_select_code
}
}
/* detect buggy encoders which don't set the low_delay flag
* (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames
* easily (although it's buggy too) */
if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
ctx->divx_version == -1 && s->picture_number == 0) {
av_log(s->avctx, AV_LOG_WARNING,
"looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
s->low_delay = 1;
}
s->picture_number++; // better than pic number==0 always ;)
// FIXME add short header support
s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
if (s->workaround_bugs & FF_BUG_EDGE) {
s->h_edge_pos = s->width;
s->v_edge_pos = s->height;
}
return 0;
}
static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
}
static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)
{
uint32_t startcode;
uint8_t extension_type;
startcode = show_bits_long(gb, 32);
if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) {
if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) {
skip_bits_long(gb, 32);
extension_type = get_bits(gb, 4);
if (extension_type == QUANT_MATRIX_EXT_ID)
read_quant_matrix_ext(s, gb);
}
}
}
static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
skip_bits(gb, 16); /* Time_code[63..48] */
check_marker(s->avctx, gb, "after Time_code[63..48]");
skip_bits(gb, 16); /* Time_code[47..32] */
check_marker(s->avctx, gb, "after Time_code[47..32]");
skip_bits(gb, 16); /* Time_code[31..16] */
check_marker(s->avctx, gb, "after Time_code[31..16]");
skip_bits(gb, 16); /* Time_code[15..0] */
check_marker(s->avctx, gb, "after Time_code[15..0]");
skip_bits(gb, 4); /* reserved_bits */
}
/**
* Decode the next studio vop header.
* @return <0 if something went wrong
*/
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int visual_object_type;
skip_bits(gb, 4); /* visual_object_verid */
visual_object_type = get_bits(gb, 4);
if (visual_object_type != VOT_VIDEO_ID) {
avpriv_request_sample(s->avctx, "VO type %u", visual_object_type);
return AVERROR_PATCHWELCOME;
}
next_start_code_studio(gb);
extension_and_user_data(s, gb, 1);
return 0;
}
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height;
int bits_per_raw_sample;
// random_accessible_vol and video_object_type_indication have already
// been read by the caller decode_vol_header()
skip_bits(gb, 4); /* video_object_layer_verid */
ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */
skip_bits(gb, 4); /* video_object_layer_shape_extension */
skip_bits1(gb); /* progressive_sequence */
if (ctx->shape != BIN_ONLY_SHAPE) {
ctx->rgb = get_bits1(gb); /* rgb_components */
s->chroma_format = get_bits(gb, 2); /* chroma_format */
if (!s->chroma_format) {
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
return AVERROR_INVALIDDATA;
}
bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */
if (bits_per_raw_sample == 10) {
if (ctx->rgb) {
s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
}
else {
s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10;
}
}
else {
avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample);
return AVERROR_PATCHWELCOME;
}
s->avctx->bits_per_raw_sample = bits_per_raw_sample;
}
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before video_object_layer_width");
width = get_bits(gb, 14); /* video_object_layer_width */
check_marker(s->avctx, gb, "before video_object_layer_height");
height = get_bits(gb, 14); /* video_object_layer_height */
check_marker(s->avctx, gb, "after video_object_layer_height");
/* Do the same check as non-studio profile */
if (width && height) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
skip_bits(gb, 4); /* frame_rate_code */
skip_bits(gb, 15); /* first_half_bit_rate */
check_marker(s->avctx, gb, "after first_half_bit_rate");
skip_bits(gb, 15); /* latter_half_bit_rate */
check_marker(s->avctx, gb, "after latter_half_bit_rate");
skip_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 3); /* latter_half_vbv_buffer_size */
skip_bits(gb, 11); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
s->low_delay = get_bits1(gb);
s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */
next_start_code_studio(gb);
extension_and_user_data(s, gb, 2);
return 0;
}
/**
* Decode MPEG-4 headers.
* @return <0 if no VOP found (or a damaged one)
* FRAME_SKIPPED if a not coded VOP is found
* 0 if a VOP is found
*/
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
mpeg4_decode_profile_level(s, gb);
if (s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(s->avctx->level > 0 && s->avctx->level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
}
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
av_cold void ff_mpeg4videodec_static_init(void) {
static int done = 0;
if (!done) {
ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_lum[0][1], 2, 1,
&ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_chrom[0][1], 2, 1,
&ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
&ff_sprite_trajectory_tab[0][1], 4, 2,
&ff_sprite_trajectory_tab[0][0], 4, 2, 128);
INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
&ff_mb_type_b_tab[0][1], 2, 1,
&ff_mb_type_b_tab[0][0], 2, 1, 16);
done = 1;
}
}
int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
/* divx 5.01+ bitstream reorder stuff */
/* Since this clobbers the input buffer and hwaccel codecs still need the
* data during hwaccel->end_frame we should not do this any earlier */
if (s->divx_packed) {
int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
int startcode_found = 0;
if (buf_size - current_pos > 7) {
int i;
for (i = current_pos; i < buf_size - 4; i++)
if (buf[i] == 0 &&
buf[i + 1] == 0 &&
buf[i + 2] == 1 &&
buf[i + 3] == 0xB6) {
startcode_found = !(buf[i + 4] & 0x40);
break;
}
}
if (startcode_found) {
if (!ctx->showed_packed_warning) {
av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
"wasteful way to store B-frames ('packed B-frames'). "
"Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
ctx->showed_packed_warning = 1;
}
av_fast_padded_malloc(&s->bitstream_buffer,
&s->allocated_bitstream_buffer_size,
buf_size - current_pos);
if (!s->bitstream_buffer) {
s->bitstream_buffer_size = 0;
return AVERROR(ENOMEM);
}
memcpy(s->bitstream_buffer, buf + current_pos,
buf_size - current_pos);
s->bitstream_buffer_size = buf_size - current_pos;
}
}
return 0;
}
#if HAVE_THREADS
static int mpeg4_update_thread_context(AVCodecContext *dst,
const AVCodecContext *src)
{
Mpeg4DecContext *s = dst->priv_data;
const Mpeg4DecContext *s1 = src->priv_data;
int init = s->m.context_initialized;
int ret = ff_mpeg_update_thread_context(dst, src);
if (ret < 0)
return ret;
memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
ff_xvid_idct_init(&s->m.idsp, dst);
return 0;
}
#endif
static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx)
{
int i, ret;
for (i = 0; i < 12; i++) {
ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22,
&ff_mpeg4_studio_intra[i][0][1], 4, 2,
&ff_mpeg4_studio_intra[i][0][0], 4, 2,
0);
if (ret < 0)
return ret;
}
ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_luma[0][1], 4, 2,
&ff_mpeg4_studio_dc_luma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_chroma[0][1], 4, 2,
&ff_mpeg4_studio_dc_chroma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
int ret;
ctx->divx_version =
ctx->divx_build =
ctx->xvid_build =
ctx->lavc_build = -1;
if ((ret = ff_h263_decode_init(avctx)) < 0)
return ret;
ff_mpeg4videodec_static_init();
if ((ret = init_studio_vlcs(ctx)) < 0)
return ret;
s->h263_pred = 1;
s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
s->decode_mb = mpeg4_decode_mb;
ctx->time_increment_bits = 4; /* default value for broken headers */
avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
avctx->internal->allocate_progress = 1;
return 0;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
int i;
if (!avctx->internal->is_copy) {
for (i = 0; i < 12; i++)
ff_free_vlc(&ctx->studio_intra_tab[i]);
ff_free_vlc(&ctx->studio_luma_dc);
ff_free_vlc(&ctx->studio_chroma_dc);
}
return ff_h263_decode_end(avctx);
}
static const AVOption mpeg4_options[] = {
{"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{NULL}
};
static const AVClass mpeg4_class = {
.class_name = "MPEG4 Video Decoder",
.item_name = av_default_item_name,
.option = mpeg4_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_mpeg4_decoder = {
.name = "mpeg4",
.long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_MPEG4,
.priv_data_size = sizeof(Mpeg4DecContext),
.init = decode_init,
.close = decode_end,
.decode = ff_h263_decode_frame,
.capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
AV_CODEC_CAP_FRAME_THREADS,
.caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
.flush = ff_mpeg_flush,
.max_lowres = 3,
.pix_fmts = ff_h263_hwaccel_pixfmt_list_420,
.profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles),
.update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
.priv_class = &mpeg4_class,
.hw_configs = (const AVCodecHWConfigInternal*[]) {
#if CONFIG_MPEG4_NVDEC_HWACCEL
HWACCEL_NVDEC(mpeg4),
#endif
#if CONFIG_MPEG4_VAAPI_HWACCEL
HWACCEL_VAAPI(mpeg4),
#endif
#if CONFIG_MPEG4_VDPAU_HWACCEL
HWACCEL_VDPAU(mpeg4),
#endif
#if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL
HWACCEL_VIDEOTOOLBOX(mpeg4),
#endif
NULL
},
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_191_0 |
crossvul-cpp_data_good_5259_1 | /*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Andrei Zmievski <andrei@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_WDDX
#include "ext/xml/expat_compat.h"
#include "php_wddx.h"
#include "php_wddx_api.h"
#define PHP_XML_INTERNAL
#include "ext/xml/php_xml.h"
#include "ext/standard/php_incomplete_class.h"
#include "ext/standard/base64.h"
#include "ext/standard/info.h"
#include "ext/standard/php_smart_str.h"
#include "ext/standard/html.h"
#include "ext/standard/php_string.h"
#include "ext/date/php_date.h"
#include "zend_globals.h"
#define WDDX_BUF_LEN 256
#define PHP_CLASS_NAME_VAR "php_class_name"
#define EL_ARRAY "array"
#define EL_BINARY "binary"
#define EL_BOOLEAN "boolean"
#define EL_CHAR "char"
#define EL_CHAR_CODE "code"
#define EL_NULL "null"
#define EL_NUMBER "number"
#define EL_PACKET "wddxPacket"
#define EL_STRING "string"
#define EL_STRUCT "struct"
#define EL_VALUE "value"
#define EL_VAR "var"
#define EL_NAME "name"
#define EL_VERSION "version"
#define EL_RECORDSET "recordset"
#define EL_FIELD "field"
#define EL_DATETIME "dateTime"
#define php_wddx_deserialize(a,b) \
php_wddx_deserialize_ex((a)->value.str.val, (a)->value.str.len, (b))
#define SET_STACK_VARNAME \
if (stack->varname) { \
ent.varname = estrdup(stack->varname); \
efree(stack->varname); \
stack->varname = NULL; \
} else \
ent.varname = NULL; \
static int le_wddx;
typedef struct {
zval *data;
enum {
ST_ARRAY,
ST_BOOLEAN,
ST_NULL,
ST_NUMBER,
ST_STRING,
ST_BINARY,
ST_STRUCT,
ST_RECORDSET,
ST_FIELD,
ST_DATETIME
} type;
char *varname;
} st_entry;
typedef struct {
int top, max;
char *varname;
zend_bool done;
void **elements;
} wddx_stack;
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len);
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_value, 0, 0, 1)
ZEND_ARG_INFO(0, var)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_vars, 0, 0, 1)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_serialize_start, 0, 0, 0)
ZEND_ARG_INFO(0, comment)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_packet_end, 0, 0, 1)
ZEND_ARG_INFO(0, packet_id)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_add_vars, 0, 0, 2)
ZEND_ARG_INFO(0, packet_id)
ZEND_ARG_VARIADIC_INFO(0, var_names)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_wddx_deserialize, 0, 0, 1)
ZEND_ARG_INFO(0, packet)
ZEND_END_ARG_INFO()
/* }}} */
/* {{{ wddx_functions[]
*/
const zend_function_entry wddx_functions[] = {
PHP_FE(wddx_serialize_value, arginfo_wddx_serialize_value)
PHP_FE(wddx_serialize_vars, arginfo_wddx_serialize_vars)
PHP_FE(wddx_packet_start, arginfo_wddx_serialize_start)
PHP_FE(wddx_packet_end, arginfo_wddx_packet_end)
PHP_FE(wddx_add_vars, arginfo_wddx_add_vars)
PHP_FE(wddx_deserialize, arginfo_wddx_deserialize)
PHP_FE_END
};
/* }}} */
PHP_MINIT_FUNCTION(wddx);
PHP_MINFO_FUNCTION(wddx);
/* {{{ dynamically loadable module stuff */
#ifdef COMPILE_DL_WDDX
ZEND_GET_MODULE(wddx)
#endif /* COMPILE_DL_WDDX */
/* }}} */
/* {{{ wddx_module_entry
*/
zend_module_entry wddx_module_entry = {
STANDARD_MODULE_HEADER,
"wddx",
wddx_functions,
PHP_MINIT(wddx),
NULL,
NULL,
NULL,
PHP_MINFO(wddx),
NO_VERSION_YET,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
/* {{{ wddx_stack_init
*/
static int wddx_stack_init(wddx_stack *stack)
{
stack->top = 0;
stack->elements = (void **) safe_emalloc(sizeof(void **), STACK_BLOCK_SIZE, 0);
stack->max = STACK_BLOCK_SIZE;
stack->varname = NULL;
stack->done = 0;
return SUCCESS;
}
/* }}} */
/* {{{ wddx_stack_push
*/
static int wddx_stack_push(wddx_stack *stack, void *element, int size)
{
if (stack->top >= stack->max) { /* we need to allocate more memory */
stack->elements = (void **) erealloc(stack->elements,
(sizeof(void **) * (stack->max += STACK_BLOCK_SIZE)));
}
stack->elements[stack->top] = (void *) emalloc(size);
memcpy(stack->elements[stack->top], element, size);
return stack->top++;
}
/* }}} */
/* {{{ wddx_stack_top
*/
static int wddx_stack_top(wddx_stack *stack, void **element)
{
if (stack->top > 0) {
*element = stack->elements[stack->top - 1];
return SUCCESS;
} else {
*element = NULL;
return FAILURE;
}
}
/* }}} */
/* {{{ wddx_stack_is_empty
*/
static int wddx_stack_is_empty(wddx_stack *stack)
{
if (stack->top == 0) {
return 1;
} else {
return 0;
}
}
/* }}} */
/* {{{ wddx_stack_destroy
*/
static int wddx_stack_destroy(wddx_stack *stack)
{
register int i;
if (stack->elements) {
for (i = 0; i < stack->top; i++) {
if (((st_entry *)stack->elements[i])->data) {
zval_ptr_dtor(&((st_entry *)stack->elements[i])->data);
}
if (((st_entry *)stack->elements[i])->varname) {
efree(((st_entry *)stack->elements[i])->varname);
}
efree(stack->elements[i]);
}
efree(stack->elements);
}
return SUCCESS;
}
/* }}} */
/* {{{ release_wddx_packet_rsrc
*/
static void release_wddx_packet_rsrc(zend_rsrc_list_entry *rsrc TSRMLS_DC)
{
smart_str *str = (smart_str *)rsrc->ptr;
smart_str_free(str);
efree(str);
}
/* }}} */
#include "ext/session/php_session.h"
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
/* {{{ PS_SERIALIZER_ENCODE_FUNC
*/
PS_SERIALIZER_ENCODE_FUNC(wddx)
{
wddx_packet *packet;
PS_ENCODE_VARS;
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
PS_ENCODE_LOOP(
php_wddx_serialize_var(packet, *struc, key, key_length TSRMLS_CC);
);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
*newstr = php_wddx_gather(packet);
php_wddx_destructor(packet);
if (newlen) {
*newlen = strlen(*newstr);
}
return SUCCESS;
}
/* }}} */
/* {{{ PS_SERIALIZER_DECODE_FUNC
*/
PS_SERIALIZER_DECODE_FUNC(wddx)
{
zval *retval;
zval **ent;
char *key;
uint key_length;
char tmp[128];
ulong idx;
int hash_type;
int ret;
if (vallen == 0) {
return SUCCESS;
}
MAKE_STD_ZVAL(retval);
if ((ret = php_wddx_deserialize_ex((char *)val, vallen, retval)) == SUCCESS) {
if (Z_TYPE_P(retval) != IS_ARRAY) {
zval_ptr_dtor(&retval);
return FAILURE;
}
for (zend_hash_internal_pointer_reset(Z_ARRVAL_P(retval));
zend_hash_get_current_data(Z_ARRVAL_P(retval), (void **) &ent) == SUCCESS;
zend_hash_move_forward(Z_ARRVAL_P(retval))) {
hash_type = zend_hash_get_current_key_ex(Z_ARRVAL_P(retval), &key, &key_length, &idx, 0, NULL);
switch (hash_type) {
case HASH_KEY_IS_LONG:
key_length = slprintf(tmp, sizeof(tmp), "%ld", idx) + 1;
key = tmp;
/* fallthru */
case HASH_KEY_IS_STRING:
php_set_session_var(key, key_length-1, *ent, NULL TSRMLS_CC);
PS_ADD_VAR(key);
}
}
}
zval_ptr_dtor(&retval);
return ret;
}
/* }}} */
#endif
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(wddx)
{
le_wddx = zend_register_list_destructors_ex(release_wddx_packet_rsrc, NULL, "wddx", module_number);
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_session_register_serializer("wddx",
PS_SERIALIZER_ENCODE_NAME(wddx),
PS_SERIALIZER_DECODE_NAME(wddx));
#endif
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(wddx)
{
php_info_print_table_start();
#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
php_info_print_table_header(2, "WDDX Support", "enabled" );
php_info_print_table_row(2, "WDDX Session Serializer", "enabled" );
#else
php_info_print_table_row(2, "WDDX Support", "enabled" );
#endif
php_info_print_table_end();
}
/* }}} */
/* {{{ php_wddx_packet_start
*/
void php_wddx_packet_start(wddx_packet *packet, char *comment, int comment_len)
{
php_wddx_add_chunk_static(packet, WDDX_PACKET_S);
if (comment) {
char *escaped;
size_t escaped_len;
TSRMLS_FETCH();
escaped = php_escape_html_entities(
comment, comment_len, &escaped_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_static(packet, WDDX_HEADER_S);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_S);
php_wddx_add_chunk_ex(packet, escaped, escaped_len);
php_wddx_add_chunk_static(packet, WDDX_COMMENT_E);
php_wddx_add_chunk_static(packet, WDDX_HEADER_E);
str_efree(escaped);
} else {
php_wddx_add_chunk_static(packet, WDDX_HEADER);
}
php_wddx_add_chunk_static(packet, WDDX_DATA_S);
}
/* }}} */
/* {{{ php_wddx_packet_end
*/
void php_wddx_packet_end(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_DATA_E);
php_wddx_add_chunk_static(packet, WDDX_PACKET_E);
}
/* }}} */
#define FLUSH_BUF() \
if (l > 0) { \
php_wddx_add_chunk_ex(packet, buf, l); \
l = 0; \
}
/* {{{ php_wddx_serialize_string
*/
static void php_wddx_serialize_string(wddx_packet *packet, zval *var TSRMLS_DC)
{
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
if (Z_STRLEN_P(var) > 0) {
char *buf;
size_t buf_len;
buf = php_escape_html_entities(Z_STRVAL_P(var), Z_STRLEN_P(var), &buf_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
php_wddx_add_chunk_ex(packet, buf, buf_len);
str_efree(buf);
}
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
}
/* }}} */
/* {{{ php_wddx_serialize_number
*/
static void php_wddx_serialize_number(wddx_packet *packet, zval *var)
{
char tmp_buf[WDDX_BUF_LEN];
zval tmp;
tmp = *var;
zval_copy_ctor(&tmp);
convert_to_string(&tmp);
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_NUMBER, Z_STRVAL(tmp));
zval_dtor(&tmp);
php_wddx_add_chunk(packet, tmp_buf);
}
/* }}} */
/* {{{ php_wddx_serialize_boolean
*/
static void php_wddx_serialize_boolean(wddx_packet *packet, zval *var)
{
php_wddx_add_chunk(packet, Z_LVAL_P(var) ? WDDX_BOOLEAN_TRUE : WDDX_BOOLEAN_FALSE);
}
/* }}} */
/* {{{ php_wddx_serialize_unset
*/
static void php_wddx_serialize_unset(wddx_packet *packet)
{
php_wddx_add_chunk_static(packet, WDDX_NULL);
}
/* }}} */
/* {{{ php_wddx_serialize_object
*/
static void php_wddx_serialize_object(wddx_packet *packet, zval *obj)
{
/* OBJECTS_FIXME */
zval **ent, *fname, **varname;
zval *retval = NULL;
const char *key;
ulong idx;
char tmp_buf[WDDX_BUF_LEN];
HashTable *objhash, *sleephash;
TSRMLS_FETCH();
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__sleep", 1);
/*
* We try to call __sleep() method on object. It's supposed to return an
* array of property names to be serialized.
*/
if (call_user_function_ex(CG(function_table), &obj, fname, &retval, 0, 0, 1, NULL TSRMLS_CC) == SUCCESS) {
if (retval && (sleephash = HASH_OF(retval))) {
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(sleephash);
zend_hash_get_current_data(sleephash, (void **)&varname) == SUCCESS;
zend_hash_move_forward(sleephash)) {
if (Z_TYPE_PP(varname) != IS_STRING) {
php_error_docref(NULL TSRMLS_CC, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize.");
continue;
}
if (zend_hash_find(objhash, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname)+1, (void **)&ent) == SUCCESS) {
php_wddx_serialize_var(packet, *ent, Z_STRVAL_PP(varname), Z_STRLEN_PP(varname) TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
} else {
uint key_len;
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(obj);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
snprintf(tmp_buf, WDDX_BUF_LEN, WDDX_VAR_S, PHP_CLASS_NAME_VAR);
php_wddx_add_chunk(packet, tmp_buf);
php_wddx_add_chunk_static(packet, WDDX_STRING_S);
php_wddx_add_chunk_ex(packet, class_name, name_len);
php_wddx_add_chunk_static(packet, WDDX_STRING_E);
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
PHP_CLEANUP_CLASS_ATTRIBUTES();
objhash = HASH_OF(obj);
for (zend_hash_internal_pointer_reset(objhash);
zend_hash_get_current_data(objhash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(objhash)) {
if (*ent == obj) {
continue;
}
if (zend_hash_get_current_key_ex(objhash, &key, &key_len, &idx, 0, NULL) == HASH_KEY_IS_STRING) {
const char *class_name, *prop_name;
zend_unmangle_property_name(key, key_len-1, &class_name, &prop_name);
php_wddx_serialize_var(packet, *ent, prop_name, strlen(prop_name)+1 TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
}
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
/* }}} */
/* {{{ php_wddx_serialize_array
*/
static void php_wddx_serialize_array(wddx_packet *packet, zval *arr)
{
zval **ent;
char *key;
uint key_len;
int is_struct = 0, ent_type;
ulong idx;
HashTable *target_hash;
char tmp_buf[WDDX_BUF_LEN];
ulong ind = 0;
int type;
TSRMLS_FETCH();
target_hash = HASH_OF(arr);
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
type = zend_hash_get_current_key(target_hash, &key, &idx, 0);
if (type == HASH_KEY_IS_STRING) {
is_struct = 1;
break;
}
if (idx != ind) {
is_struct = 1;
break;
}
ind++;
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
} else {
snprintf(tmp_buf, sizeof(tmp_buf), WDDX_ARRAY_S, zend_hash_num_elements(target_hash));
php_wddx_add_chunk(packet, tmp_buf);
}
for (zend_hash_internal_pointer_reset(target_hash);
zend_hash_get_current_data(target_hash, (void**)&ent) == SUCCESS;
zend_hash_move_forward(target_hash)) {
if (*ent == arr) {
continue;
}
if (is_struct) {
ent_type = zend_hash_get_current_key_ex(target_hash, &key, &key_len, &idx, 0, NULL);
if (ent_type == HASH_KEY_IS_STRING) {
php_wddx_serialize_var(packet, *ent, key, key_len TSRMLS_CC);
} else {
key_len = slprintf(tmp_buf, sizeof(tmp_buf), "%ld", idx);
php_wddx_serialize_var(packet, *ent, tmp_buf, key_len TSRMLS_CC);
}
} else {
php_wddx_serialize_var(packet, *ent, NULL, 0 TSRMLS_CC);
}
}
if (is_struct) {
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
} else {
php_wddx_add_chunk_static(packet, WDDX_ARRAY_E);
}
}
/* }}} */
/* {{{ php_wddx_serialize_var
*/
void php_wddx_serialize_var(wddx_packet *packet, zval *var, char *name, int name_len TSRMLS_DC)
{
HashTable *ht;
if (name) {
size_t name_esc_len;
char *tmp_buf, *name_esc;
name_esc = php_escape_html_entities(name, name_len, &name_esc_len, 0, ENT_QUOTES, NULL TSRMLS_CC);
tmp_buf = emalloc(name_esc_len + sizeof(WDDX_VAR_S));
snprintf(tmp_buf, name_esc_len + sizeof(WDDX_VAR_S), WDDX_VAR_S, name_esc);
php_wddx_add_chunk(packet, tmp_buf);
efree(tmp_buf);
str_efree(name_esc);
}
switch(Z_TYPE_P(var)) {
case IS_STRING:
php_wddx_serialize_string(packet, var TSRMLS_CC);
break;
case IS_LONG:
case IS_DOUBLE:
php_wddx_serialize_number(packet, var);
break;
case IS_BOOL:
php_wddx_serialize_boolean(packet, var);
break;
case IS_NULL:
php_wddx_serialize_unset(packet);
break;
case IS_ARRAY:
ht = Z_ARRVAL_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_array(packet, var);
ht->nApplyCount--;
break;
case IS_OBJECT:
ht = Z_OBJPROP_P(var);
if (ht->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "WDDX doesn't support circular references");
return;
}
ht->nApplyCount++;
php_wddx_serialize_object(packet, var);
ht->nApplyCount--;
break;
}
if (name) {
php_wddx_add_chunk_static(packet, WDDX_VAR_E);
}
}
/* }}} */
/* {{{ php_wddx_add_var
*/
static void php_wddx_add_var(wddx_packet *packet, zval *name_var)
{
zval **val;
HashTable *target_hash;
TSRMLS_FETCH();
if (Z_TYPE_P(name_var) == IS_STRING) {
if (!EG(active_symbol_table)) {
zend_rebuild_symbol_table(TSRMLS_C);
}
if (zend_hash_find(EG(active_symbol_table), Z_STRVAL_P(name_var),
Z_STRLEN_P(name_var)+1, (void**)&val) != FAILURE) {
php_wddx_serialize_var(packet, *val, Z_STRVAL_P(name_var), Z_STRLEN_P(name_var) TSRMLS_CC);
}
} else if (Z_TYPE_P(name_var) == IS_ARRAY || Z_TYPE_P(name_var) == IS_OBJECT) {
int is_array = Z_TYPE_P(name_var) == IS_ARRAY;
target_hash = HASH_OF(name_var);
if (is_array && target_hash->nApplyCount > 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "recursion detected");
return;
}
zend_hash_internal_pointer_reset(target_hash);
while(zend_hash_get_current_data(target_hash, (void**)&val) == SUCCESS) {
if (is_array) {
target_hash->nApplyCount++;
}
php_wddx_add_var(packet, *val);
if (is_array) {
target_hash->nApplyCount--;
}
zend_hash_move_forward(target_hash);
}
}
}
/* }}} */
/* {{{ php_wddx_push_element
*/
static void php_wddx_push_element(void *user_data, const XML_Char *name, const XML_Char **atts)
{
st_entry ent;
wddx_stack *stack = (wddx_stack *)user_data;
if (!strcmp(name, EL_PACKET)) {
int i;
if (atts) for (i=0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VERSION)) {
/* nothing for now */
}
}
} else if (!strcmp(name, EL_STRING)) {
ent.type = ST_STRING;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BINARY)) {
ent.type = ST_BINARY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_STRING;
Z_STRVAL_P(ent.data) = STR_EMPTY_ALLOC();
Z_STRLEN_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_CHAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_CHAR_CODE) && atts[++i] && atts[i][0]) {
char tmp_buf[2];
snprintf(tmp_buf, sizeof(tmp_buf), "%c", (char)strtol(atts[i], NULL, 16));
php_wddx_process_data(user_data, tmp_buf, strlen(tmp_buf));
break;
}
}
} else if (!strcmp(name, EL_NUMBER)) {
ent.type = ST_NUMBER;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
Z_LVAL_P(ent.data) = 0;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_BOOLEAN)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_VALUE) && atts[++i] && atts[i][0]) {
ent.type = ST_BOOLEAN;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_BOOL;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
php_wddx_process_data(user_data, atts[i], strlen(atts[i]));
break;
}
}
} else if (!strcmp(name, EL_NULL)) {
ent.type = ST_NULL;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
ZVAL_NULL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_ARRAY)) {
ent.type = ST_ARRAY;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_STRUCT)) {
ent.type = ST_STRUCT;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
array_init(ent.data);
INIT_PZVAL(ent.data);
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_VAR)) {
int i;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
if (stack->varname) efree(stack->varname);
stack->varname = estrdup(atts[i]);
break;
}
}
} else if (!strcmp(name, EL_RECORDSET)) {
int i;
ent.type = ST_RECORDSET;
SET_STACK_VARNAME;
MAKE_STD_ZVAL(ent.data);
array_init(ent.data);
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], "fieldNames") && atts[++i] && atts[i][0]) {
zval *tmp;
char *key;
char *p1, *p2, *endp;
endp = (char *)atts[i] + strlen(atts[i]);
p1 = (char *)atts[i];
while ((p2 = php_memnstr(p1, ",", sizeof(",")-1, endp)) != NULL) {
key = estrndup(p1, p2 - p1);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, key, p2 - p1 + 1, tmp);
p1 = p2 + sizeof(",")-1;
efree(key);
}
if (p1 <= endp) {
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(ent.data, p1, endp - p1 + 1, tmp);
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_FIELD)) {
int i;
st_entry ent;
ent.type = ST_FIELD;
ent.varname = NULL;
ent.data = NULL;
if (atts) for (i = 0; atts[i]; i++) {
if (!strcmp(atts[i], EL_NAME) && atts[++i] && atts[i][0]) {
st_entry *recordset;
zval **field;
if (wddx_stack_top(stack, (void**)&recordset) == SUCCESS &&
recordset->type == ST_RECORDSET &&
zend_hash_find(Z_ARRVAL_P(recordset->data), (char*)atts[i], strlen(atts[i])+1, (void**)&field) == SUCCESS) {
ent.data = *field;
}
break;
}
}
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
} else if (!strcmp(name, EL_DATETIME)) {
ent.type = ST_DATETIME;
SET_STACK_VARNAME;
ALLOC_ZVAL(ent.data);
INIT_PZVAL(ent.data);
Z_TYPE_P(ent.data) = IS_LONG;
wddx_stack_push((wddx_stack *)stack, &ent, sizeof(st_entry));
}
}
/* }}} */
/* {{{ php_wddx_pop_element
*/
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
} else {
stack->done = 1;
}
efree(ent1);
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
}
}
/* }}} */
/* {{{ php_wddx_process_data
*/
static void php_wddx_process_data(void *user_data, const XML_Char *s, int len)
{
st_entry *ent;
wddx_stack *stack = (wddx_stack *)user_data;
TSRMLS_FETCH();
if (!wddx_stack_is_empty(stack) && !stack->done) {
wddx_stack_top(stack, (void**)&ent);
switch (ent->type) {
case ST_STRING:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len);
Z_STRLEN_P(ent->data) = len;
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
}
break;
case ST_BINARY:
if (Z_STRLEN_P(ent->data) == 0) {
STR_FREE(Z_STRVAL_P(ent->data));
Z_STRVAL_P(ent->data) = estrndup(s, len + 1);
} else {
Z_STRVAL_P(ent->data) = erealloc(Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data) + len + 1);
memcpy(Z_STRVAL_P(ent->data) + Z_STRLEN_P(ent->data), s, len);
}
Z_STRLEN_P(ent->data) += len;
Z_STRVAL_P(ent->data)[Z_STRLEN_P(ent->data)] = '\0';
break;
case ST_NUMBER:
Z_TYPE_P(ent->data) = IS_STRING;
Z_STRLEN_P(ent->data) = len;
Z_STRVAL_P(ent->data) = estrndup(s, len);
convert_scalar_to_number(ent->data TSRMLS_CC);
break;
case ST_BOOLEAN:
if(!ent->data) {
break;
}
if (!strcmp(s, "true")) {
Z_LVAL_P(ent->data) = 1;
} else if (!strcmp(s, "false")) {
Z_LVAL_P(ent->data) = 0;
} else {
zval_ptr_dtor(&ent->data);
if (ent->varname) {
efree(ent->varname);
ent->varname = NULL;
}
ent->data = NULL;
}
break;
case ST_DATETIME: {
char *tmp;
if (Z_TYPE_P(ent->data) == IS_STRING) {
tmp = safe_emalloc(Z_STRLEN_P(ent->data), 1, (size_t)len + 1);
memcpy(tmp, Z_STRVAL_P(ent->data), Z_STRLEN_P(ent->data));
memcpy(tmp + Z_STRLEN_P(ent->data), s, len);
len += Z_STRLEN_P(ent->data);
efree(Z_STRVAL_P(ent->data));
Z_TYPE_P(ent->data) = IS_LONG;
} else {
tmp = emalloc(len + 1);
memcpy(tmp, s, len);
}
tmp[len] = '\0';
Z_LVAL_P(ent->data) = php_parse_date(tmp, NULL);
/* date out of range < 1969 or > 2038 */
if (Z_LVAL_P(ent->data) == -1) {
ZVAL_STRINGL(ent->data, tmp, len, 0);
} else {
efree(tmp);
}
}
break;
default:
break;
}
}
}
/* }}} */
/* {{{ php_wddx_deserialize_ex
*/
int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value)
{
wddx_stack stack;
XML_Parser parser;
st_entry *ent;
int retval;
wddx_stack_init(&stack);
parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, &stack);
XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element);
XML_SetCharacterDataHandler(parser, php_wddx_process_data);
XML_Parse(parser, value, vallen, 1);
XML_ParserFree(parser);
if (stack.top == 1) {
wddx_stack_top(&stack, (void**)&ent);
*return_value = *(ent->data);
zval_copy_ctor(return_value);
retval = SUCCESS;
} else {
retval = FAILURE;
}
wddx_stack_destroy(&stack);
return retval;
}
/* }}} */
/* {{{ proto string wddx_serialize_value(mixed var [, string comment])
Creates a new packet and serializes the given value */
PHP_FUNCTION(wddx_serialize_value)
{
zval *var;
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|s", &var, &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_serialize_var(packet, var, NULL, 0 TSRMLS_CC);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto string wddx_serialize_vars(mixed var_name [, mixed ...])
Creates a new packet and serializes given variables into a struct */
PHP_FUNCTION(wddx_serialize_vars)
{
int num_args, i;
wddx_packet *packet;
zval ***args = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "+", &args, &num_args) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, NULL, 0);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, *args[i]);
}
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
efree(args);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ php_wddx_constructor
*/
wddx_packet *php_wddx_constructor(void)
{
smart_str *packet;
packet = (smart_str *)emalloc(sizeof(smart_str));
packet->c = NULL;
return packet;
}
/* }}} */
/* {{{ php_wddx_destructor
*/
void php_wddx_destructor(wddx_packet *packet)
{
smart_str_free(packet);
efree(packet);
}
/* }}} */
/* {{{ proto resource wddx_packet_start([string comment])
Starts a WDDX packet with optional comment and returns the packet id */
PHP_FUNCTION(wddx_packet_start)
{
char *comment = NULL;
int comment_len = 0;
wddx_packet *packet;
comment = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &comment, &comment_len) == FAILURE) {
return;
}
packet = php_wddx_constructor();
php_wddx_packet_start(packet, comment, comment_len);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_S);
ZEND_REGISTER_RESOURCE(return_value, packet, le_wddx);
}
/* }}} */
/* {{{ proto string wddx_packet_end(resource packet_id)
Ends specified WDDX packet and returns the string containing the packet */
PHP_FUNCTION(wddx_packet_end)
{
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &packet_id) == FAILURE) {
return;
}
ZEND_FETCH_RESOURCE(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx);
php_wddx_add_chunk_static(packet, WDDX_STRUCT_E);
php_wddx_packet_end(packet);
ZVAL_STRINGL(return_value, packet->c, packet->len, 1);
zend_list_delete(Z_LVAL_P(packet_id));
}
/* }}} */
/* {{{ proto int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...])
Serializes given variables and adds them to packet given by packet_id */
PHP_FUNCTION(wddx_add_vars)
{
int num_args, i;
zval ***args = NULL;
zval *packet_id;
wddx_packet *packet = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r+", &packet_id, &args, &num_args) == FAILURE) {
return;
}
if (!ZEND_FETCH_RESOURCE_NO_RETURN(packet, wddx_packet *, &packet_id, -1, "WDDX packet ID", le_wddx)) {
efree(args);
RETURN_FALSE;
}
if (!packet) {
efree(args);
RETURN_FALSE;
}
for (i=0; i<num_args; i++) {
if (Z_TYPE_PP(args[i]) != IS_ARRAY && Z_TYPE_PP(args[i]) != IS_OBJECT) {
convert_to_string_ex(args[i]);
}
php_wddx_add_var(packet, (*args[i]));
}
efree(args);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed wddx_deserialize(mixed packet)
Deserializes given packet and returns a PHP value */
PHP_FUNCTION(wddx_deserialize)
{
zval *packet;
char *payload;
int payload_len;
php_stream *stream = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z", &packet) == FAILURE) {
return;
}
if (Z_TYPE_P(packet) == IS_STRING) {
payload = Z_STRVAL_P(packet);
payload_len = Z_STRLEN_P(packet);
} else if (Z_TYPE_P(packet) == IS_RESOURCE) {
php_stream_from_zval(stream, &packet);
if (stream) {
payload_len = php_stream_copy_to_mem(stream, &payload, PHP_STREAM_COPY_ALL, 0);
}
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Expecting parameter 1 to be a string or a stream");
return;
}
if (payload_len == 0) {
return;
}
php_wddx_deserialize_ex(payload, payload_len, return_value);
if (stream) {
pefree(payload, 0);
}
}
/* }}} */
#endif /* HAVE_LIBEXPAT */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5259_1 |
crossvul-cpp_data_good_5418_4 | /*
* Copyright (c) 2002-2003 Michael David Adams.
* All rights reserved.
*/
/* __START_OF_JASPER_LICENSE__
*
* JasPer License Version 2.0
*
* Copyright (c) 2001-2006 Michael David Adams
* Copyright (c) 1999-2000 Image Power, Inc.
* Copyright (c) 1999-2000 The University of British Columbia
*
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person (the
* "User") obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* 1. The above copyright notices and this permission notice (which
* includes the disclaimer below) shall be included in all copies or
* substantial portions of the Software.
*
* 2. The name of a copyright holder shall not be used to endorse or
* promote products derived from the Software without specific prior
* written permission.
*
* THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS
* LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER
* THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS
* "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL
* INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING
* FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE
* PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE
* THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY.
* EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS
* BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL
* PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS
* GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE
* ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE
* IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL
* SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES,
* AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL
* SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH
* THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH,
* PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY
* EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*
* __END_OF_JASPER_LICENSE__
*/
#include <assert.h>
#include "jasper/jas_config.h"
#include "jasper/jas_types.h"
#include "jasper/jas_malloc.h"
#include "jasper/jas_debug.h"
#include "jasper/jas_icc.h"
#include "jasper/jas_cm.h"
#include "jasper/jas_stream.h"
#include "jasper/jas_string.h"
#include <stdlib.h>
#include <ctype.h>
#include <inttypes.h>
#define jas_iccputuint8(out, val) jas_iccputuint(out, 1, val)
#define jas_iccputuint16(out, val) jas_iccputuint(out, 2, val)
#define jas_iccputsint32(out, val) jas_iccputsint(out, 4, val)
#define jas_iccputuint32(out, val) jas_iccputuint(out, 4, val)
#define jas_iccputuint64(out, val) jas_iccputuint(out, 8, val)
static jas_iccattrval_t *jas_iccattrval_create0(void);
static int jas_iccgetuint(jas_stream_t *in, int n, jas_ulonglong *val);
static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val);
static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val);
static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val);
static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val);
static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val);
static int jas_iccputuint(jas_stream_t *out, int n, jas_ulonglong val);
static int jas_iccputsint(jas_stream_t *out, int n, jas_longlong val);
static jas_iccprof_t *jas_iccprof_create(void);
static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr);
static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr);
static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab);
static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab);
static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab, jas_iccuint32_t name);
static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab);
static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t name);
static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time);
static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz);
static int jas_icctagtabent_cmp(const void *src, const void *dst);
static void jas_icccurv_destroy(jas_iccattrval_t *attrval);
static int jas_icccurv_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval);
static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt);
static int jas_icccurv_getsize(jas_iccattrval_t *attrval);
static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out);
static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out);
static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval);
static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval);
static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt);
static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval);
static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out);
static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out);
static void jas_icctxt_destroy(jas_iccattrval_t *attrval);
static int jas_icctxt_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval);
static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt);
static int jas_icctxt_getsize(jas_iccattrval_t *attrval);
static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out);
static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out);
static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt);
static int jas_iccxyz_getsize(jas_iccattrval_t *attrval);
static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out);
static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out);
static jas_iccattrtab_t *jas_iccattrtab_create(void);
static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab);
static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents);
static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i,
jas_iccuint32_t name, jas_iccattrval_t *val);
static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i,
jas_iccuint32_t name, jas_iccattrval_t *val);
static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i);
static long jas_iccpadtomult(long x, long y);
static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i,
jas_iccattrname_t *name, jas_iccattrval_t **val);
static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab);
static void jas_icclut16_destroy(jas_iccattrval_t *attrval);
static int jas_icclut16_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval);
static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt);
static int jas_icclut16_getsize(jas_iccattrval_t *attrval);
static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out);
static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out);
static void jas_icclut8_destroy(jas_iccattrval_t *attrval);
static int jas_icclut8_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval);
static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt);
static int jas_icclut8_getsize(jas_iccattrval_t *attrval);
static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out);
static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out);
static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *ctime);
static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz);
static long jas_iccpowi(int x, int n);
static char *jas_iccsigtostr(int sig, char *buf);
jas_iccattrvalinfo_t jas_iccattrvalinfos[] = {
{JAS_ICC_TYPE_CURV, {jas_icccurv_destroy, jas_icccurv_copy,
jas_icccurv_input, jas_icccurv_output, jas_icccurv_getsize,
jas_icccurv_dump}},
{JAS_ICC_TYPE_XYZ, {0, 0, jas_iccxyz_input, jas_iccxyz_output,
jas_iccxyz_getsize, jas_iccxyz_dump}},
{JAS_ICC_TYPE_TXTDESC, {jas_icctxtdesc_destroy,
jas_icctxtdesc_copy, jas_icctxtdesc_input, jas_icctxtdesc_output,
jas_icctxtdesc_getsize, jas_icctxtdesc_dump}},
{JAS_ICC_TYPE_TXT, {jas_icctxt_destroy, jas_icctxt_copy,
jas_icctxt_input, jas_icctxt_output, jas_icctxt_getsize,
jas_icctxt_dump}},
{JAS_ICC_TYPE_LUT8, {jas_icclut8_destroy, jas_icclut8_copy,
jas_icclut8_input, jas_icclut8_output, jas_icclut8_getsize,
jas_icclut8_dump}},
{JAS_ICC_TYPE_LUT16, {jas_icclut16_destroy, jas_icclut16_copy,
jas_icclut16_input, jas_icclut16_output, jas_icclut16_getsize,
jas_icclut16_dump}},
{0, {0, 0, 0, 0, 0, 0}}
};
typedef struct {
jas_iccuint32_t tag;
char *name;
} jas_icctaginfo_t;
/******************************************************************************\
* profile class
\******************************************************************************/
static jas_iccprof_t *jas_iccprof_create()
{
jas_iccprof_t *prof;
prof = 0;
if (!(prof = jas_malloc(sizeof(jas_iccprof_t)))) {
goto error;
}
if (!(prof->attrtab = jas_iccattrtab_create()))
goto error;
memset(&prof->hdr, 0, sizeof(jas_icchdr_t));
prof->tagtab.numents = 0;
prof->tagtab.ents = 0;
return prof;
error:
if (prof)
jas_iccprof_destroy(prof);
return 0;
}
jas_iccprof_t *jas_iccprof_copy(jas_iccprof_t *prof)
{
jas_iccprof_t *newprof;
newprof = 0;
if (!(newprof = jas_iccprof_create()))
goto error;
newprof->hdr = prof->hdr;
newprof->tagtab.numents = 0;
newprof->tagtab.ents = 0;
assert(newprof->attrtab);
jas_iccattrtab_destroy(newprof->attrtab);
if (!(newprof->attrtab = jas_iccattrtab_copy(prof->attrtab)))
goto error;
return newprof;
error:
if (newprof)
jas_iccprof_destroy(newprof);
return 0;
}
void jas_iccprof_destroy(jas_iccprof_t *prof)
{
if (prof->attrtab)
jas_iccattrtab_destroy(prof->attrtab);
if (prof->tagtab.ents)
jas_free(prof->tagtab.ents);
jas_free(prof);
}
void jas_iccprof_dump(jas_iccprof_t *prof, FILE *out)
{
jas_iccattrtab_dump(prof->attrtab, out);
}
jas_iccprof_t *jas_iccprof_load(jas_stream_t *in)
{
jas_iccprof_t *prof;
int numtags;
long curoff;
long reloff;
long prevoff;
jas_iccsig_t type;
jas_iccattrval_t *attrval;
jas_iccattrval_t *prevattrval;
jas_icctagtabent_t *tagtabent;
int i;
int len;
prof = 0;
attrval = 0;
if (!(prof = jas_iccprof_create())) {
goto error;
}
if (jas_iccprof_readhdr(in, &prof->hdr)) {
jas_eprintf("cannot get header\n");
goto error;
}
if (jas_iccprof_gettagtab(in, &prof->tagtab)) {
jas_eprintf("cannot get tab table\n");
goto error;
}
jas_iccprof_sorttagtab(&prof->tagtab);
numtags = prof->tagtab.numents;
curoff = JAS_ICC_HDRLEN + 4 + 12 * numtags;
prevoff = 0;
prevattrval = 0;
for (i = 0; i < numtags; ++i) {
tagtabent = &prof->tagtab.ents[i];
if (tagtabent->off == JAS_CAST(jas_iccuint32_t, prevoff)) {
if (prevattrval) {
if (!(attrval = jas_iccattrval_clone(prevattrval)))
goto error;
if (jas_iccprof_setattr(prof, tagtabent->tag, attrval))
goto error;
jas_iccattrval_destroy(attrval);
attrval = 0;
} else {
#if 0
jas_eprintf("warning: skipping unknown tag type\n");
#endif
}
continue;
}
reloff = tagtabent->off - curoff;
if (reloff > 0) {
if (jas_stream_gobble(in, reloff) != reloff)
goto error;
curoff += reloff;
} else if (reloff < 0) {
/* This should never happen since we read the tagged
element data in a single pass. */
abort();
}
prevoff = curoff;
if (jas_iccgetuint32(in, &type)) {
goto error;
}
if (jas_stream_gobble(in, 4) != 4) {
goto error;
}
curoff += 8;
if (!jas_iccattrvalinfo_lookup(type)) {
#if 0
jas_eprintf("warning: skipping unknown tag type\n");
#endif
prevattrval = 0;
continue;
}
if (!(attrval = jas_iccattrval_create(type))) {
goto error;
}
len = tagtabent->len - 8;
if ((*attrval->ops->input)(attrval, in, len)) {
goto error;
}
curoff += len;
if (jas_iccprof_setattr(prof, tagtabent->tag, attrval)) {
goto error;
}
prevattrval = attrval; /* This is correct, but slimey. */
jas_iccattrval_destroy(attrval);
attrval = 0;
}
return prof;
error:
if (prof)
jas_iccprof_destroy(prof);
if (attrval)
jas_iccattrval_destroy(attrval);
return 0;
}
int jas_iccprof_save(jas_iccprof_t *prof, jas_stream_t *out)
{
long curoff;
long reloff;
long newoff;
int i;
int j;
jas_icctagtabent_t *tagtabent;
jas_icctagtabent_t *sharedtagtabent;
jas_icctagtabent_t *tmptagtabent;
jas_iccuint32_t attrname;
jas_iccattrval_t *attrval;
jas_icctagtab_t *tagtab;
tagtab = &prof->tagtab;
if (!(tagtab->ents = jas_alloc2(prof->attrtab->numattrs,
sizeof(jas_icctagtabent_t))))
goto error;
tagtab->numents = prof->attrtab->numattrs;
curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents;
for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) {
tagtabent = &tagtab->ents[i];
if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval))
goto error;
assert(attrval->ops->output);
tagtabent->tag = attrname;
tagtabent->data = &attrval->data;
sharedtagtabent = 0;
for (j = 0; j < i; ++j) {
tmptagtabent = &tagtab->ents[j];
if (tagtabent->data == tmptagtabent->data) {
sharedtagtabent = tmptagtabent;
break;
}
}
if (sharedtagtabent) {
tagtabent->off = sharedtagtabent->off;
tagtabent->len = sharedtagtabent->len;
tagtabent->first = sharedtagtabent;
} else {
tagtabent->off = curoff;
tagtabent->len = (*attrval->ops->getsize)(attrval) + 8;
tagtabent->first = 0;
if (i < JAS_CAST(int, tagtab->numents - 1)) {
curoff = jas_iccpadtomult(curoff + tagtabent->len, 4);
} else {
curoff += tagtabent->len;
}
}
jas_iccattrval_destroy(attrval);
}
prof->hdr.size = curoff;
if (jas_iccprof_writehdr(out, &prof->hdr))
goto error;
if (jas_iccprof_puttagtab(out, &prof->tagtab))
goto error;
curoff = JAS_ICC_HDRLEN + 4 + 12 * tagtab->numents;
for (i = 0; i < JAS_CAST(int, tagtab->numents);) {
tagtabent = &tagtab->ents[i];
assert(curoff == JAS_CAST(long, tagtabent->off));
if (jas_iccattrtab_get(prof->attrtab, i, &attrname, &attrval))
goto error;
if (jas_iccputuint32(out, attrval->type) || jas_stream_pad(out,
4, 0) != 4)
goto error;
if ((*attrval->ops->output)(attrval, out))
goto error;
jas_iccattrval_destroy(attrval);
curoff += tagtabent->len;
++i;
while (i < JAS_CAST(int, tagtab->numents) &&
tagtab->ents[i].first)
++i;
newoff = (i < JAS_CAST(int, tagtab->numents)) ?
tagtab->ents[i].off : prof->hdr.size;
reloff = newoff - curoff;
assert(reloff >= 0);
if (reloff > 0) {
if (jas_stream_pad(out, reloff, 0) != reloff)
goto error;
curoff += reloff;
}
}
return 0;
error:
/* XXX - need to free some resources here */
return -1;
}
static int jas_iccprof_writehdr(jas_stream_t *out, jas_icchdr_t *hdr)
{
if (jas_iccputuint32(out, hdr->size) ||
jas_iccputuint32(out, hdr->cmmtype) ||
jas_iccputuint32(out, hdr->version) ||
jas_iccputuint32(out, hdr->clas) ||
jas_iccputuint32(out, hdr->colorspc) ||
jas_iccputuint32(out, hdr->refcolorspc) ||
jas_iccputtime(out, &hdr->ctime) ||
jas_iccputuint32(out, hdr->magic) ||
jas_iccputuint32(out, hdr->platform) ||
jas_iccputuint32(out, hdr->flags) ||
jas_iccputuint32(out, hdr->maker) ||
jas_iccputuint32(out, hdr->model) ||
jas_iccputuint64(out, hdr->attr) ||
jas_iccputuint32(out, hdr->intent) ||
jas_iccputxyz(out, &hdr->illum) ||
jas_iccputuint32(out, hdr->creator) ||
jas_stream_pad(out, 44, 0) != 44)
return -1;
return 0;
}
static int jas_iccprof_puttagtab(jas_stream_t *out, jas_icctagtab_t *tagtab)
{
int i;
jas_icctagtabent_t *tagtabent;
if (jas_iccputuint32(out, tagtab->numents))
goto error;
for (i = 0; i < JAS_CAST(int, tagtab->numents); ++i) {
tagtabent = &tagtab->ents[i];
if (jas_iccputuint32(out, tagtabent->tag) ||
jas_iccputuint32(out, tagtabent->off) ||
jas_iccputuint32(out, tagtabent->len))
goto error;
}
return 0;
error:
return -1;
}
static int jas_iccprof_readhdr(jas_stream_t *in, jas_icchdr_t *hdr)
{
if (jas_iccgetuint32(in, &hdr->size) ||
jas_iccgetuint32(in, &hdr->cmmtype) ||
jas_iccgetuint32(in, &hdr->version) ||
jas_iccgetuint32(in, &hdr->clas) ||
jas_iccgetuint32(in, &hdr->colorspc) ||
jas_iccgetuint32(in, &hdr->refcolorspc) ||
jas_iccgettime(in, &hdr->ctime) ||
jas_iccgetuint32(in, &hdr->magic) ||
jas_iccgetuint32(in, &hdr->platform) ||
jas_iccgetuint32(in, &hdr->flags) ||
jas_iccgetuint32(in, &hdr->maker) ||
jas_iccgetuint32(in, &hdr->model) ||
jas_iccgetuint64(in, &hdr->attr) ||
jas_iccgetuint32(in, &hdr->intent) ||
jas_iccgetxyz(in, &hdr->illum) ||
jas_iccgetuint32(in, &hdr->creator) ||
jas_stream_gobble(in, 44) != 44)
return -1;
return 0;
}
static int jas_iccprof_gettagtab(jas_stream_t *in, jas_icctagtab_t *tagtab)
{
int i;
jas_icctagtabent_t *tagtabent;
if (tagtab->ents) {
jas_free(tagtab->ents);
tagtab->ents = 0;
}
if (jas_iccgetuint32(in, &tagtab->numents))
goto error;
if (!(tagtab->ents = jas_alloc2(tagtab->numents,
sizeof(jas_icctagtabent_t))))
goto error;
tagtabent = tagtab->ents;
for (i = 0; i < JAS_CAST(long, tagtab->numents); ++i) {
if (jas_iccgetuint32(in, &tagtabent->tag) ||
jas_iccgetuint32(in, &tagtabent->off) ||
jas_iccgetuint32(in, &tagtabent->len))
goto error;
++tagtabent;
}
return 0;
error:
if (tagtab->ents) {
jas_free(tagtab->ents);
tagtab->ents = 0;
}
return -1;
}
jas_iccattrval_t *jas_iccprof_getattr(jas_iccprof_t *prof,
jas_iccattrname_t name)
{
int i;
jas_iccattrval_t *attrval;
if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) < 0)
goto error;
if (!(attrval = jas_iccattrval_clone(prof->attrtab->attrs[i].val)))
goto error;
return attrval;
error:
return 0;
}
int jas_iccprof_setattr(jas_iccprof_t *prof, jas_iccattrname_t name,
jas_iccattrval_t *val)
{
int i;
if ((i = jas_iccattrtab_lookup(prof->attrtab, name)) >= 0) {
if (val) {
if (jas_iccattrtab_replace(prof->attrtab, i, name, val))
goto error;
} else {
jas_iccattrtab_delete(prof->attrtab, i);
}
} else {
if (val) {
if (jas_iccattrtab_add(prof->attrtab, -1, name, val))
goto error;
} else {
/* NOP */
}
}
return 0;
error:
return -1;
}
int jas_iccprof_gethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr)
{
*hdr = prof->hdr;
return 0;
}
int jas_iccprof_sethdr(jas_iccprof_t *prof, jas_icchdr_t *hdr)
{
prof->hdr = *hdr;
return 0;
}
static void jas_iccprof_sorttagtab(jas_icctagtab_t *tagtab)
{
qsort(tagtab->ents, tagtab->numents, sizeof(jas_icctagtabent_t),
jas_icctagtabent_cmp);
}
static int jas_icctagtabent_cmp(const void *src, const void *dst)
{
jas_icctagtabent_t *srctagtabent = JAS_CAST(jas_icctagtabent_t *, src);
jas_icctagtabent_t *dsttagtabent = JAS_CAST(jas_icctagtabent_t *, dst);
if (srctagtabent->off > dsttagtabent->off) {
return 1;
} else if (srctagtabent->off < dsttagtabent->off) {
return -1;
}
return 0;
}
static jas_iccattrvalinfo_t *jas_iccattrvalinfo_lookup(jas_iccsig_t type)
{
jas_iccattrvalinfo_t *info;
info = jas_iccattrvalinfos;
for (info = jas_iccattrvalinfos; info->type; ++info) {
if (info->type == type) {
return info;
}
}
return 0;
}
static int jas_iccgettime(jas_stream_t *in, jas_icctime_t *time)
{
if (jas_iccgetuint16(in, &time->year) ||
jas_iccgetuint16(in, &time->month) ||
jas_iccgetuint16(in, &time->day) ||
jas_iccgetuint16(in, &time->hour) ||
jas_iccgetuint16(in, &time->min) ||
jas_iccgetuint16(in, &time->sec)) {
return -1;
}
return 0;
}
static int jas_iccgetxyz(jas_stream_t *in, jas_iccxyz_t *xyz)
{
if (jas_iccgetsint32(in, &xyz->x) ||
jas_iccgetsint32(in, &xyz->y) ||
jas_iccgetsint32(in, &xyz->z)) {
return -1;
}
return 0;
}
static int jas_iccputtime(jas_stream_t *out, jas_icctime_t *time)
{
jas_iccputuint16(out, time->year);
jas_iccputuint16(out, time->month);
jas_iccputuint16(out, time->day);
jas_iccputuint16(out, time->hour);
jas_iccputuint16(out, time->min);
jas_iccputuint16(out, time->sec);
return 0;
}
static int jas_iccputxyz(jas_stream_t *out, jas_iccxyz_t *xyz)
{
jas_iccputuint32(out, xyz->x);
jas_iccputuint32(out, xyz->y);
jas_iccputuint32(out, xyz->z);
return 0;
}
/******************************************************************************\
* attribute table class
\******************************************************************************/
static jas_iccattrtab_t *jas_iccattrtab_create()
{
jas_iccattrtab_t *tab;
tab = 0;
if (!(tab = jas_malloc(sizeof(jas_iccattrtab_t))))
goto error;
tab->maxattrs = 0;
tab->numattrs = 0;
tab->attrs = 0;
if (jas_iccattrtab_resize(tab, 32))
goto error;
return tab;
error:
if (tab)
jas_iccattrtab_destroy(tab);
return 0;
}
static jas_iccattrtab_t *jas_iccattrtab_copy(jas_iccattrtab_t *attrtab)
{
jas_iccattrtab_t *newattrtab;
int i;
if (!(newattrtab = jas_iccattrtab_create()))
goto error;
for (i = 0; i < attrtab->numattrs; ++i) {
if (jas_iccattrtab_add(newattrtab, i, attrtab->attrs[i].name,
attrtab->attrs[i].val))
goto error;
}
return newattrtab;
error:
return 0;
}
static void jas_iccattrtab_destroy(jas_iccattrtab_t *tab)
{
if (tab->attrs) {
while (tab->numattrs > 0) {
jas_iccattrtab_delete(tab, 0);
}
jas_free(tab->attrs);
}
jas_free(tab);
}
void jas_iccattrtab_dump(jas_iccattrtab_t *attrtab, FILE *out)
{
int i;
jas_iccattr_t *attr;
jas_iccattrval_t *attrval;
jas_iccattrvalinfo_t *info;
char buf[16];
fprintf(out, "numattrs=%d\n", attrtab->numattrs);
fprintf(out, "---\n");
for (i = 0; i < attrtab->numattrs; ++i) {
attr = &attrtab->attrs[i];
attrval = attr->val;
info = jas_iccattrvalinfo_lookup(attrval->type);
if (!info) abort();
fprintf(out, "attrno=%d; attrname=\"%s\"(0x%08"PRIxFAST32"); attrtype=\"%s\"(0x%08"PRIxFAST32")\n",
i,
jas_iccsigtostr(attr->name, &buf[0]),
attr->name,
jas_iccsigtostr(attrval->type, &buf[8]),
attrval->type
);
jas_iccattrval_dump(attrval, out);
fprintf(out, "---\n");
}
}
static int jas_iccattrtab_resize(jas_iccattrtab_t *tab, int maxents)
{
jas_iccattr_t *newattrs;
assert(maxents >= tab->numattrs);
newattrs = tab->attrs ? jas_realloc2(tab->attrs, maxents,
sizeof(jas_iccattr_t)) : jas_alloc2(maxents, sizeof(jas_iccattr_t));
if (!newattrs) {
return -1;
}
tab->attrs = newattrs;
tab->maxattrs = maxents;
return 0;
}
static int jas_iccattrtab_add(jas_iccattrtab_t *attrtab, int i,
jas_iccuint32_t name, jas_iccattrval_t *val)
{
int n;
jas_iccattr_t *attr;
jas_iccattrval_t *tmpattrval;
tmpattrval = 0;
if (i < 0) {
i = attrtab->numattrs;
}
assert(i >= 0 && i <= attrtab->numattrs);
if (attrtab->numattrs >= attrtab->maxattrs) {
if (jas_iccattrtab_resize(attrtab, attrtab->numattrs + 32)) {
goto error;
}
}
if (!(tmpattrval = jas_iccattrval_clone(val)))
goto error;
n = attrtab->numattrs - i;
if (n > 0)
memmove(&attrtab->attrs[i + 1], &attrtab->attrs[i],
n * sizeof(jas_iccattr_t));
attr = &attrtab->attrs[i];
attr->name = name;
attr->val = tmpattrval;
++attrtab->numattrs;
return 0;
error:
if (tmpattrval)
jas_iccattrval_destroy(tmpattrval);
return -1;
}
static int jas_iccattrtab_replace(jas_iccattrtab_t *attrtab, int i,
jas_iccuint32_t name, jas_iccattrval_t *val)
{
jas_iccattrval_t *newval;
jas_iccattr_t *attr;
if (!(newval = jas_iccattrval_clone(val)))
goto error;
attr = &attrtab->attrs[i];
jas_iccattrval_destroy(attr->val);
attr->name = name;
attr->val = newval;
return 0;
error:
return -1;
}
static void jas_iccattrtab_delete(jas_iccattrtab_t *attrtab, int i)
{
int n;
jas_iccattrval_destroy(attrtab->attrs[i].val);
if ((n = attrtab->numattrs - i - 1) > 0)
memmove(&attrtab->attrs[i], &attrtab->attrs[i + 1],
n * sizeof(jas_iccattr_t));
--attrtab->numattrs;
}
static int jas_iccattrtab_get(jas_iccattrtab_t *attrtab, int i,
jas_iccattrname_t *name, jas_iccattrval_t **val)
{
jas_iccattr_t *attr;
if (i < 0 || i >= attrtab->numattrs)
goto error;
attr = &attrtab->attrs[i];
*name = attr->name;
if (!(*val = jas_iccattrval_clone(attr->val)))
goto error;
return 0;
error:
return -1;
}
static int jas_iccattrtab_lookup(jas_iccattrtab_t *attrtab,
jas_iccuint32_t name)
{
int i;
jas_iccattr_t *attr;
for (i = 0; i < attrtab->numattrs; ++i) {
attr = &attrtab->attrs[i];
if (attr->name == name)
return i;
}
return -1;
}
/******************************************************************************\
* attribute value class
\******************************************************************************/
jas_iccattrval_t *jas_iccattrval_create(jas_iccuint32_t type)
{
jas_iccattrval_t *attrval;
jas_iccattrvalinfo_t *info;
if (!(info = jas_iccattrvalinfo_lookup(type)))
goto error;
if (!(attrval = jas_iccattrval_create0()))
goto error;
attrval->ops = &info->ops;
attrval->type = type;
++attrval->refcnt;
memset(&attrval->data, 0, sizeof(attrval->data));
return attrval;
error:
return 0;
}
jas_iccattrval_t *jas_iccattrval_clone(jas_iccattrval_t *attrval)
{
++attrval->refcnt;
return attrval;
}
void jas_iccattrval_destroy(jas_iccattrval_t *attrval)
{
#if 0
jas_eprintf("refcnt=%d\n", attrval->refcnt);
#endif
if (--attrval->refcnt <= 0) {
if (attrval->ops->destroy)
(*attrval->ops->destroy)(attrval);
jas_free(attrval);
}
}
void jas_iccattrval_dump(jas_iccattrval_t *attrval, FILE *out)
{
char buf[8];
jas_iccsigtostr(attrval->type, buf);
fprintf(out, "refcnt = %d; type = 0x%08"PRIxFAST32" %s\n", attrval->refcnt,
attrval->type, jas_iccsigtostr(attrval->type, &buf[0]));
if (attrval->ops->dump) {
(*attrval->ops->dump)(attrval, out);
}
}
int jas_iccattrval_allowmodify(jas_iccattrval_t **attrvalx)
{
jas_iccattrval_t *newattrval;
jas_iccattrval_t *attrval = *attrvalx;
newattrval = 0;
if (attrval->refcnt > 1) {
if (!(newattrval = jas_iccattrval_create0()))
goto error;
newattrval->ops = attrval->ops;
newattrval->type = attrval->type;
++newattrval->refcnt;
if (newattrval->ops->copy) {
if ((*newattrval->ops->copy)(newattrval, attrval))
goto error;
} else {
memcpy(&newattrval->data, &attrval->data,
sizeof(newattrval->data));
}
*attrvalx = newattrval;
}
return 0;
error:
if (newattrval) {
jas_free(newattrval);
}
return -1;
}
static jas_iccattrval_t *jas_iccattrval_create0()
{
jas_iccattrval_t *attrval;
if (!(attrval = jas_malloc(sizeof(jas_iccattrval_t))))
return 0;
memset(attrval, 0, sizeof(jas_iccattrval_t));
attrval->refcnt = 0;
attrval->ops = 0;
attrval->type = 0;
return attrval;
}
/******************************************************************************\
*
\******************************************************************************/
static int jas_iccxyz_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int len)
{
if (len != 4 * 3) abort();
return jas_iccgetxyz(in, &attrval->data.xyz);
}
static int jas_iccxyz_output(jas_iccattrval_t *attrval, jas_stream_t *out)
{
jas_iccxyz_t *xyz = &attrval->data.xyz;
if (jas_iccputuint32(out, xyz->x) ||
jas_iccputuint32(out, xyz->y) ||
jas_iccputuint32(out, xyz->z))
return -1;
return 0;
}
static int jas_iccxyz_getsize(jas_iccattrval_t *attrval)
{
/* Avoid compiler warnings about unused parameters. */
attrval = 0;
return 12;
}
static void jas_iccxyz_dump(jas_iccattrval_t *attrval, FILE *out)
{
jas_iccxyz_t *xyz = &attrval->data.xyz;
fprintf(out, "(%f, %f, %f)\n", xyz->x / 65536.0, xyz->y / 65536.0, xyz->z / 65536.0);
}
/******************************************************************************\
* attribute table class
\******************************************************************************/
static void jas_icccurv_destroy(jas_iccattrval_t *attrval)
{
jas_icccurv_t *curv = &attrval->data.curv;
if (curv->ents) {
jas_free(curv->ents);
curv->ents = 0;
}
}
static int jas_icccurv_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval)
{
/* Avoid compiler warnings about unused parameters. */
attrval = 0;
othattrval = 0;
/* Not yet implemented. */
abort();
return -1;
}
static int jas_icccurv_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt)
{
jas_icccurv_t *curv = &attrval->data.curv;
unsigned int i;
curv->numents = 0;
curv->ents = 0;
if (jas_iccgetuint32(in, &curv->numents))
goto error;
if (!(curv->ents = jas_alloc2(curv->numents, sizeof(jas_iccuint16_t))))
goto error;
for (i = 0; i < curv->numents; ++i) {
if (jas_iccgetuint16(in, &curv->ents[i]))
goto error;
}
if (JAS_CAST(int, 4 + 2 * curv->numents) != cnt)
goto error;
return 0;
error:
jas_icccurv_destroy(attrval);
return -1;
}
static int jas_icccurv_getsize(jas_iccattrval_t *attrval)
{
jas_icccurv_t *curv = &attrval->data.curv;
return 4 + 2 * curv->numents;
}
static int jas_icccurv_output(jas_iccattrval_t *attrval, jas_stream_t *out)
{
jas_icccurv_t *curv = &attrval->data.curv;
unsigned int i;
if (jas_iccputuint32(out, curv->numents))
goto error;
for (i = 0; i < curv->numents; ++i) {
if (jas_iccputuint16(out, curv->ents[i]))
goto error;
}
return 0;
error:
return -1;
}
static void jas_icccurv_dump(jas_iccattrval_t *attrval, FILE *out)
{
int i;
jas_icccurv_t *curv = &attrval->data.curv;
fprintf(out, "number of entries = %"PRIuFAST32"\n", curv->numents);
if (curv->numents == 1) {
fprintf(out, "gamma = %f\n", curv->ents[0] / 256.0);
} else {
for (i = 0; i < JAS_CAST(int, curv->numents); ++i) {
if (i < 3 || i >= JAS_CAST(int, curv->numents) - 3) {
fprintf(out, "entry[%d] = %f\n", i, curv->ents[i] / 65535.0);
}
}
}
}
/******************************************************************************\
*
\******************************************************************************/
static void jas_icctxtdesc_destroy(jas_iccattrval_t *attrval)
{
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
if (txtdesc->ascdata) {
jas_free(txtdesc->ascdata);
txtdesc->ascdata = 0;
}
if (txtdesc->ucdata) {
jas_free(txtdesc->ucdata);
txtdesc->ucdata = 0;
}
}
static int jas_icctxtdesc_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval)
{
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
/* Avoid compiler warnings about unused parameters. */
attrval = 0;
othattrval = 0;
txtdesc = 0;
/* Not yet implemented. */
abort();
return -1;
}
static int jas_icctxtdesc_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt)
{
int n;
int c;
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
txtdesc->ascdata = 0;
txtdesc->ucdata = 0;
if (jas_iccgetuint32(in, &txtdesc->asclen))
goto error;
if (!(txtdesc->ascdata = jas_malloc(txtdesc->asclen)))
goto error;
if (jas_stream_read(in, txtdesc->ascdata, txtdesc->asclen) !=
JAS_CAST(int, txtdesc->asclen))
goto error;
txtdesc->ascdata[txtdesc->asclen - 1] = '\0';
if (jas_iccgetuint32(in, &txtdesc->uclangcode) ||
jas_iccgetuint32(in, &txtdesc->uclen))
goto error;
if (!(txtdesc->ucdata = jas_alloc2(txtdesc->uclen, 2)))
goto error;
if (jas_stream_read(in, txtdesc->ucdata, txtdesc->uclen * 2) !=
JAS_CAST(int, txtdesc->uclen * 2))
goto error;
if (jas_iccgetuint16(in, &txtdesc->sccode))
goto error;
if ((c = jas_stream_getc(in)) == EOF)
goto error;
txtdesc->maclen = c;
if (jas_stream_read(in, txtdesc->macdata, 67) != 67)
goto error;
txtdesc->asclen = JAS_CAST(jas_iccuint32_t, strlen(txtdesc->ascdata) + 1);
#define WORKAROUND_BAD_PROFILES
#ifdef WORKAROUND_BAD_PROFILES
n = txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67;
if (n > cnt) {
return -1;
}
if (n < cnt) {
if (jas_stream_gobble(in, cnt - n) != cnt - n)
goto error;
}
#else
if (txtdesc->asclen + txtdesc->uclen * 2 + 15 + 67 != cnt)
return -1;
#endif
return 0;
error:
jas_icctxtdesc_destroy(attrval);
return -1;
}
static int jas_icctxtdesc_getsize(jas_iccattrval_t *attrval)
{
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
return JAS_CAST(int, strlen(txtdesc->ascdata) + 1 + txtdesc->uclen * 2 +
15 + 67);
}
static int jas_icctxtdesc_output(jas_iccattrval_t *attrval, jas_stream_t *out)
{
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
if (jas_iccputuint32(out, txtdesc->asclen) ||
jas_stream_puts(out, txtdesc->ascdata) ||
jas_stream_putc(out, 0) == EOF ||
jas_iccputuint32(out, txtdesc->uclangcode) ||
jas_iccputuint32(out, txtdesc->uclen) ||
jas_stream_write(out, txtdesc->ucdata, txtdesc->uclen * 2) != JAS_CAST(int, txtdesc->uclen * 2) ||
jas_iccputuint16(out, txtdesc->sccode) ||
jas_stream_putc(out, txtdesc->maclen) == EOF)
goto error;
if (txtdesc->maclen > 0) {
if (jas_stream_write(out, txtdesc->macdata, 67) != 67)
goto error;
} else {
if (jas_stream_pad(out, 67, 0) != 67)
goto error;
}
return 0;
error:
return -1;
}
static void jas_icctxtdesc_dump(jas_iccattrval_t *attrval, FILE *out)
{
jas_icctxtdesc_t *txtdesc = &attrval->data.txtdesc;
fprintf(out, "ascii = \"%s\"\n", txtdesc->ascdata);
fprintf(out, "uclangcode = %"PRIuFAST32"; uclen = %"PRIuFAST32"\n",
txtdesc->uclangcode, txtdesc->uclen);
fprintf(out, "sccode = %"PRIuFAST16"\n", txtdesc->sccode);
fprintf(out, "maclen = %d\n", txtdesc->maclen);
}
/******************************************************************************\
*
\******************************************************************************/
static void jas_icctxt_destroy(jas_iccattrval_t *attrval)
{
jas_icctxt_t *txt = &attrval->data.txt;
if (txt->string) {
jas_free(txt->string);
txt->string = 0;
}
}
static int jas_icctxt_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval)
{
jas_icctxt_t *txt = &attrval->data.txt;
jas_icctxt_t *othtxt = &othattrval->data.txt;
if (!(txt->string = jas_strdup(othtxt->string)))
return -1;
return 0;
}
static int jas_icctxt_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt)
{
jas_icctxt_t *txt = &attrval->data.txt;
txt->string = 0;
if (!(txt->string = jas_malloc(cnt)))
goto error;
if (jas_stream_read(in, txt->string, cnt) != cnt)
goto error;
txt->string[cnt - 1] = '\0';
if (JAS_CAST(int, strlen(txt->string)) + 1 != cnt)
goto error;
return 0;
error:
jas_icctxt_destroy(attrval);
return -1;
}
static int jas_icctxt_getsize(jas_iccattrval_t *attrval)
{
jas_icctxt_t *txt = &attrval->data.txt;
return JAS_CAST(int, strlen(txt->string) + 1);
}
static int jas_icctxt_output(jas_iccattrval_t *attrval, jas_stream_t *out)
{
jas_icctxt_t *txt = &attrval->data.txt;
if (jas_stream_puts(out, txt->string) ||
jas_stream_putc(out, 0) == EOF)
return -1;
return 0;
}
static void jas_icctxt_dump(jas_iccattrval_t *attrval, FILE *out)
{
jas_icctxt_t *txt = &attrval->data.txt;
fprintf(out, "string = \"%s\"\n", txt->string);
}
/******************************************************************************\
*
\******************************************************************************/
static void jas_icclut8_destroy(jas_iccattrval_t *attrval)
{
jas_icclut8_t *lut8 = &attrval->data.lut8;
if (lut8->clut) {
jas_free(lut8->clut);
lut8->clut = 0;
}
if (lut8->intabs) {
jas_free(lut8->intabs);
lut8->intabs = 0;
}
if (lut8->intabsbuf) {
jas_free(lut8->intabsbuf);
lut8->intabsbuf = 0;
}
if (lut8->outtabs) {
jas_free(lut8->outtabs);
lut8->outtabs = 0;
}
if (lut8->outtabsbuf) {
jas_free(lut8->outtabsbuf);
lut8->outtabsbuf = 0;
}
}
static int jas_icclut8_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval)
{
jas_icclut8_t *lut8 = &attrval->data.lut8;
/* Avoid compiler warnings about unused parameters. */
attrval = 0;
othattrval = 0;
lut8 = 0;
abort();
return -1;
}
static int jas_icclut8_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt)
{
int i;
int j;
int clutsize;
jas_icclut8_t *lut8 = &attrval->data.lut8;
lut8->clut = 0;
lut8->intabs = 0;
lut8->intabsbuf = 0;
lut8->outtabs = 0;
lut8->outtabsbuf = 0;
if (jas_iccgetuint8(in, &lut8->numinchans) ||
jas_iccgetuint8(in, &lut8->numoutchans) ||
jas_iccgetuint8(in, &lut8->clutlen) ||
jas_stream_getc(in) == EOF)
goto error;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
if (jas_iccgetsint32(in, &lut8->e[i][j]))
goto error;
}
}
if (jas_iccgetuint16(in, &lut8->numintabents) ||
jas_iccgetuint16(in, &lut8->numouttabents))
goto error;
clutsize = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
if (!(lut8->clut = jas_alloc2(clutsize, sizeof(jas_iccuint8_t))) ||
!(lut8->intabsbuf = jas_alloc3(lut8->numinchans,
lut8->numintabents, sizeof(jas_iccuint8_t))) ||
!(lut8->intabs = jas_alloc2(lut8->numinchans,
sizeof(jas_iccuint8_t *))))
goto error;
for (i = 0; i < lut8->numinchans; ++i)
lut8->intabs[i] = &lut8->intabsbuf[i * lut8->numintabents];
if (!(lut8->outtabsbuf = jas_alloc3(lut8->numoutchans,
lut8->numouttabents, sizeof(jas_iccuint8_t))) ||
!(lut8->outtabs = jas_alloc2(lut8->numoutchans,
sizeof(jas_iccuint8_t *))))
goto error;
for (i = 0; i < lut8->numoutchans; ++i)
lut8->outtabs[i] = &lut8->outtabsbuf[i * lut8->numouttabents];
for (i = 0; i < lut8->numinchans; ++i) {
for (j = 0; j < JAS_CAST(int, lut8->numintabents); ++j) {
if (jas_iccgetuint8(in, &lut8->intabs[i][j]))
goto error;
}
}
for (i = 0; i < lut8->numoutchans; ++i) {
for (j = 0; j < JAS_CAST(int, lut8->numouttabents); ++j) {
if (jas_iccgetuint8(in, &lut8->outtabs[i][j]))
goto error;
}
}
for (i = 0; i < clutsize; ++i) {
if (jas_iccgetuint8(in, &lut8->clut[i]))
goto error;
}
if (JAS_CAST(int, 44 + lut8->numinchans * lut8->numintabents +
lut8->numoutchans * lut8->numouttabents +
jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans) !=
cnt)
goto error;
return 0;
error:
jas_icclut8_destroy(attrval);
return -1;
}
static int jas_icclut8_getsize(jas_iccattrval_t *attrval)
{
jas_icclut8_t *lut8 = &attrval->data.lut8;
return 44 + lut8->numinchans * lut8->numintabents +
lut8->numoutchans * lut8->numouttabents +
jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
}
static int jas_icclut8_output(jas_iccattrval_t *attrval, jas_stream_t *out)
{
jas_icclut8_t *lut8 = &attrval->data.lut8;
int i;
int j;
int n;
lut8->clut = 0;
lut8->intabs = 0;
lut8->intabsbuf = 0;
lut8->outtabs = 0;
lut8->outtabsbuf = 0;
if (jas_stream_putc(out, lut8->numinchans) == EOF ||
jas_stream_putc(out, lut8->numoutchans) == EOF ||
jas_stream_putc(out, lut8->clutlen) == EOF ||
jas_stream_putc(out, 0) == EOF)
goto error;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
if (jas_iccputsint32(out, lut8->e[i][j]))
goto error;
}
}
if (jas_iccputuint16(out, lut8->numintabents) ||
jas_iccputuint16(out, lut8->numouttabents))
goto error;
n = lut8->numinchans * lut8->numintabents;
for (i = 0; i < n; ++i) {
if (jas_iccputuint8(out, lut8->intabsbuf[i]))
goto error;
}
n = lut8->numoutchans * lut8->numouttabents;
for (i = 0; i < n; ++i) {
if (jas_iccputuint8(out, lut8->outtabsbuf[i]))
goto error;
}
n = jas_iccpowi(lut8->clutlen, lut8->numinchans) * lut8->numoutchans;
for (i = 0; i < n; ++i) {
if (jas_iccputuint8(out, lut8->clut[i]))
goto error;
}
return 0;
error:
return -1;
}
static void jas_icclut8_dump(jas_iccattrval_t *attrval, FILE *out)
{
jas_icclut8_t *lut8 = &attrval->data.lut8;
int i;
int j;
fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n",
lut8->numinchans, lut8->numoutchans, lut8->clutlen);
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
fprintf(out, "e[%d][%d]=%f ", i, j, lut8->e[i][j] / 65536.0);
}
fprintf(out, "\n");
}
fprintf(out, "numintabents=%"PRIuFAST16", numouttabents=%"PRIuFAST16"\n",
lut8->numintabents, lut8->numouttabents);
}
/******************************************************************************\
*
\******************************************************************************/
static void jas_icclut16_destroy(jas_iccattrval_t *attrval)
{
jas_icclut16_t *lut16 = &attrval->data.lut16;
if (lut16->clut) {
jas_free(lut16->clut);
lut16->clut = 0;
}
if (lut16->intabs) {
jas_free(lut16->intabs);
lut16->intabs = 0;
}
if (lut16->intabsbuf) {
jas_free(lut16->intabsbuf);
lut16->intabsbuf = 0;
}
if (lut16->outtabs) {
jas_free(lut16->outtabs);
lut16->outtabs = 0;
}
if (lut16->outtabsbuf) {
jas_free(lut16->outtabsbuf);
lut16->outtabsbuf = 0;
}
}
static int jas_icclut16_copy(jas_iccattrval_t *attrval,
jas_iccattrval_t *othattrval)
{
/* Avoid compiler warnings about unused parameters. */
attrval = 0;
othattrval = 0;
/* Not yet implemented. */
abort();
return -1;
}
static int jas_icclut16_input(jas_iccattrval_t *attrval, jas_stream_t *in,
int cnt)
{
int i;
int j;
int clutsize;
jas_icclut16_t *lut16 = &attrval->data.lut16;
lut16->clut = 0;
lut16->intabs = 0;
lut16->intabsbuf = 0;
lut16->outtabs = 0;
lut16->outtabsbuf = 0;
if (jas_iccgetuint8(in, &lut16->numinchans) ||
jas_iccgetuint8(in, &lut16->numoutchans) ||
jas_iccgetuint8(in, &lut16->clutlen) ||
jas_stream_getc(in) == EOF)
goto error;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
if (jas_iccgetsint32(in, &lut16->e[i][j]))
goto error;
}
}
if (jas_iccgetuint16(in, &lut16->numintabents) ||
jas_iccgetuint16(in, &lut16->numouttabents))
goto error;
clutsize = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans;
if (!(lut16->clut = jas_alloc2(clutsize, sizeof(jas_iccuint16_t))) ||
!(lut16->intabsbuf = jas_alloc3(lut16->numinchans,
lut16->numintabents, sizeof(jas_iccuint16_t))) ||
!(lut16->intabs = jas_alloc2(lut16->numinchans,
sizeof(jas_iccuint16_t *))))
goto error;
for (i = 0; i < lut16->numinchans; ++i)
lut16->intabs[i] = &lut16->intabsbuf[i * lut16->numintabents];
if (!(lut16->outtabsbuf = jas_alloc3(lut16->numoutchans,
lut16->numouttabents, sizeof(jas_iccuint16_t))) ||
!(lut16->outtabs = jas_alloc2(lut16->numoutchans,
sizeof(jas_iccuint16_t *))))
goto error;
for (i = 0; i < lut16->numoutchans; ++i)
lut16->outtabs[i] = &lut16->outtabsbuf[i * lut16->numouttabents];
for (i = 0; i < lut16->numinchans; ++i) {
for (j = 0; j < JAS_CAST(int, lut16->numintabents); ++j) {
if (jas_iccgetuint16(in, &lut16->intabs[i][j]))
goto error;
}
}
for (i = 0; i < lut16->numoutchans; ++i) {
for (j = 0; j < JAS_CAST(int, lut16->numouttabents); ++j) {
if (jas_iccgetuint16(in, &lut16->outtabs[i][j]))
goto error;
}
}
for (i = 0; i < clutsize; ++i) {
if (jas_iccgetuint16(in, &lut16->clut[i]))
goto error;
}
if (JAS_CAST(int, 44 + 2 * (lut16->numinchans * lut16->numintabents +
lut16->numoutchans * lut16->numouttabents +
jas_iccpowi(lut16->clutlen, lut16->numinchans) *
lut16->numoutchans)) != cnt)
goto error;
return 0;
error:
jas_icclut16_destroy(attrval);
return -1;
}
static int jas_icclut16_getsize(jas_iccattrval_t *attrval)
{
jas_icclut16_t *lut16 = &attrval->data.lut16;
return 44 + 2 * (lut16->numinchans * lut16->numintabents +
lut16->numoutchans * lut16->numouttabents +
jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans);
}
static int jas_icclut16_output(jas_iccattrval_t *attrval, jas_stream_t *out)
{
jas_icclut16_t *lut16 = &attrval->data.lut16;
int i;
int j;
int n;
if (jas_stream_putc(out, lut16->numinchans) == EOF ||
jas_stream_putc(out, lut16->numoutchans) == EOF ||
jas_stream_putc(out, lut16->clutlen) == EOF ||
jas_stream_putc(out, 0) == EOF)
goto error;
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
if (jas_iccputsint32(out, lut16->e[i][j]))
goto error;
}
}
if (jas_iccputuint16(out, lut16->numintabents) ||
jas_iccputuint16(out, lut16->numouttabents))
goto error;
n = lut16->numinchans * lut16->numintabents;
for (i = 0; i < n; ++i) {
if (jas_iccputuint16(out, lut16->intabsbuf[i]))
goto error;
}
n = lut16->numoutchans * lut16->numouttabents;
for (i = 0; i < n; ++i) {
if (jas_iccputuint16(out, lut16->outtabsbuf[i]))
goto error;
}
n = jas_iccpowi(lut16->clutlen, lut16->numinchans) * lut16->numoutchans;
for (i = 0; i < n; ++i) {
if (jas_iccputuint16(out, lut16->clut[i]))
goto error;
}
return 0;
error:
return -1;
}
static void jas_icclut16_dump(jas_iccattrval_t *attrval, FILE *out)
{
jas_icclut16_t *lut16 = &attrval->data.lut16;
int i;
int j;
fprintf(out, "numinchans=%d, numoutchans=%d, clutlen=%d\n",
lut16->numinchans, lut16->numoutchans, lut16->clutlen);
for (i = 0; i < 3; ++i) {
for (j = 0; j < 3; ++j) {
fprintf(out, "e[%d][%d]=%f ", i, j, lut16->e[i][j] / 65536.0);
}
fprintf(out, "\n");
}
fprintf(out, "numintabents=%"PRIuFAST16", numouttabents=%"PRIuFAST16"\n",
lut16->numintabents, lut16->numouttabents);
}
/******************************************************************************\
*
\******************************************************************************/
static int jas_iccgetuint(jas_stream_t *in, int n, jas_ulonglong *val)
{
int i;
int c;
jas_ulonglong v;
v = 0;
for (i = n; i > 0; --i) {
if ((c = jas_stream_getc(in)) == EOF)
return -1;
v = (v << 8) | c;
}
*val = v;
return 0;
}
static int jas_iccgetuint8(jas_stream_t *in, jas_iccuint8_t *val)
{
int c;
if ((c = jas_stream_getc(in)) == EOF)
return -1;
*val = c;
return 0;
}
static int jas_iccgetuint16(jas_stream_t *in, jas_iccuint16_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 2, &tmp))
return -1;
*val = tmp;
return 0;
}
static int jas_iccgetsint32(jas_stream_t *in, jas_iccsint32_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 4, &tmp))
return -1;
*val = (tmp & 0x80000000) ? (-JAS_CAST(jas_longlong, (((~tmp) &
0x7fffffff) + 1))) : JAS_CAST(jas_longlong, tmp);
return 0;
}
static int jas_iccgetuint32(jas_stream_t *in, jas_iccuint32_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 4, &tmp))
return -1;
*val = tmp;
return 0;
}
static int jas_iccgetuint64(jas_stream_t *in, jas_iccuint64_t *val)
{
jas_ulonglong tmp;
if (jas_iccgetuint(in, 8, &tmp))
return -1;
*val = tmp;
return 0;
}
static int jas_iccputuint(jas_stream_t *out, int n, jas_ulonglong val)
{
int i;
int c;
for (i = n; i > 0; --i) {
c = (val >> (8 * (i - 1))) & 0xff;
if (jas_stream_putc(out, c) == EOF)
return -1;
}
return 0;
}
static int jas_iccputsint(jas_stream_t *out, int n, jas_longlong val)
{
jas_ulonglong tmp;
tmp = (val < 0) ? (abort(), 0) : val;
return jas_iccputuint(out, n, tmp);
}
/******************************************************************************\
*
\******************************************************************************/
static char *jas_iccsigtostr(int sig, char *buf)
{
int n;
int c;
char *bufptr;
bufptr = buf;
for (n = 4; n > 0; --n) {
c = (sig >> 24) & 0xff;
if (isalpha(c) || isdigit(c)) {
*bufptr++ = c;
}
sig <<= 8;
}
*bufptr = '\0';
return buf;
}
static long jas_iccpadtomult(long x, long y)
{
return ((x + y - 1) / y) * y;
}
static long jas_iccpowi(int x, int n)
{
long y;
y = 1;
while (--n >= 0)
y *= x;
return y;
}
jas_iccprof_t *jas_iccprof_createfrombuf(jas_uchar *buf, int len)
{
jas_stream_t *in;
jas_iccprof_t *prof;
if (!(in = jas_stream_memopen(JAS_CAST(char *, buf), len)))
goto error;
if (!(prof = jas_iccprof_load(in)))
goto error;
jas_stream_close(in);
return prof;
error:
if (in)
jas_stream_close(in);
return 0;
}
jas_iccprof_t *jas_iccprof_createfromclrspc(int clrspc)
{
jas_iccprof_t *prof;
switch (clrspc) {
case JAS_CLRSPC_SRGB:
prof = jas_iccprof_createfrombuf(jas_iccprofdata_srgb,
jas_iccprofdata_srgblen);
break;
case JAS_CLRSPC_SGRAY:
prof = jas_iccprof_createfrombuf(jas_iccprofdata_sgray,
jas_iccprofdata_sgraylen);
break;
default:
prof = 0;
break;
}
return prof;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5418_4 |
crossvul-cpp_data_bad_5718_1 | /*
* Bridge multicast support.
*
* Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <linux/err.h>
#include <linux/if_ether.h>
#include <linux/igmp.h>
#include <linux/jhash.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include <linux/netdevice.h>
#include <linux/netfilter_bridge.h>
#include <linux/random.h>
#include <linux/rculist.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/timer.h>
#include <linux/inetdevice.h>
#include <net/ip.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <net/ipv6.h>
#include <net/mld.h>
#include <net/ip6_checksum.h>
#endif
#include "br_private.h"
static void br_multicast_start_querier(struct net_bridge *br);
unsigned int br_mdb_rehash_seq;
static inline int br_ip_equal(const struct br_ip *a, const struct br_ip *b)
{
if (a->proto != b->proto)
return 0;
if (a->vid != b->vid)
return 0;
switch (a->proto) {
case htons(ETH_P_IP):
return a->u.ip4 == b->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return ipv6_addr_equal(&a->u.ip6, &b->u.ip6);
#endif
}
return 0;
}
static inline int __br_ip4_hash(struct net_bridge_mdb_htable *mdb, __be32 ip,
__u16 vid)
{
return jhash_2words((__force u32)ip, vid, mdb->secret) & (mdb->max - 1);
}
#if IS_ENABLED(CONFIG_IPV6)
static inline int __br_ip6_hash(struct net_bridge_mdb_htable *mdb,
const struct in6_addr *ip,
__u16 vid)
{
return jhash_2words(ipv6_addr_hash(ip), vid,
mdb->secret) & (mdb->max - 1);
}
#endif
static inline int br_ip_hash(struct net_bridge_mdb_htable *mdb,
struct br_ip *ip)
{
switch (ip->proto) {
case htons(ETH_P_IP):
return __br_ip4_hash(mdb, ip->u.ip4, ip->vid);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return __br_ip6_hash(mdb, &ip->u.ip6, ip->vid);
#endif
}
return 0;
}
static struct net_bridge_mdb_entry *__br_mdb_ip_get(
struct net_bridge_mdb_htable *mdb, struct br_ip *dst, int hash)
{
struct net_bridge_mdb_entry *mp;
hlist_for_each_entry_rcu(mp, &mdb->mhash[hash], hlist[mdb->ver]) {
if (br_ip_equal(&mp->addr, dst))
return mp;
}
return NULL;
}
struct net_bridge_mdb_entry *br_mdb_ip_get(struct net_bridge_mdb_htable *mdb,
struct br_ip *dst)
{
if (!mdb)
return NULL;
return __br_mdb_ip_get(mdb, dst, br_ip_hash(mdb, dst));
}
static struct net_bridge_mdb_entry *br_mdb_ip4_get(
struct net_bridge_mdb_htable *mdb, __be32 dst, __u16 vid)
{
struct br_ip br_dst;
br_dst.u.ip4 = dst;
br_dst.proto = htons(ETH_P_IP);
br_dst.vid = vid;
return br_mdb_ip_get(mdb, &br_dst);
}
#if IS_ENABLED(CONFIG_IPV6)
static struct net_bridge_mdb_entry *br_mdb_ip6_get(
struct net_bridge_mdb_htable *mdb, const struct in6_addr *dst,
__u16 vid)
{
struct br_ip br_dst;
br_dst.u.ip6 = *dst;
br_dst.proto = htons(ETH_P_IPV6);
br_dst.vid = vid;
return br_mdb_ip_get(mdb, &br_dst);
}
#endif
struct net_bridge_mdb_entry *br_mdb_get(struct net_bridge *br,
struct sk_buff *skb, u16 vid)
{
struct net_bridge_mdb_htable *mdb = rcu_dereference(br->mdb);
struct br_ip ip;
if (br->multicast_disabled)
return NULL;
if (BR_INPUT_SKB_CB(skb)->igmp)
return NULL;
ip.proto = skb->protocol;
ip.vid = vid;
switch (skb->protocol) {
case htons(ETH_P_IP):
ip.u.ip4 = ip_hdr(skb)->daddr;
break;
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
ip.u.ip6 = ipv6_hdr(skb)->daddr;
break;
#endif
default:
return NULL;
}
return br_mdb_ip_get(mdb, &ip);
}
static void br_mdb_free(struct rcu_head *head)
{
struct net_bridge_mdb_htable *mdb =
container_of(head, struct net_bridge_mdb_htable, rcu);
struct net_bridge_mdb_htable *old = mdb->old;
mdb->old = NULL;
kfree(old->mhash);
kfree(old);
}
static int br_mdb_copy(struct net_bridge_mdb_htable *new,
struct net_bridge_mdb_htable *old,
int elasticity)
{
struct net_bridge_mdb_entry *mp;
int maxlen;
int len;
int i;
for (i = 0; i < old->max; i++)
hlist_for_each_entry(mp, &old->mhash[i], hlist[old->ver])
hlist_add_head(&mp->hlist[new->ver],
&new->mhash[br_ip_hash(new, &mp->addr)]);
if (!elasticity)
return 0;
maxlen = 0;
for (i = 0; i < new->max; i++) {
len = 0;
hlist_for_each_entry(mp, &new->mhash[i], hlist[new->ver])
len++;
if (len > maxlen)
maxlen = len;
}
return maxlen > elasticity ? -EINVAL : 0;
}
void br_multicast_free_pg(struct rcu_head *head)
{
struct net_bridge_port_group *p =
container_of(head, struct net_bridge_port_group, rcu);
kfree(p);
}
static void br_multicast_free_group(struct rcu_head *head)
{
struct net_bridge_mdb_entry *mp =
container_of(head, struct net_bridge_mdb_entry, rcu);
kfree(mp);
}
static void br_multicast_group_expired(unsigned long data)
{
struct net_bridge_mdb_entry *mp = (void *)data;
struct net_bridge *br = mp->br;
struct net_bridge_mdb_htable *mdb;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || timer_pending(&mp->timer))
goto out;
mp->mglist = false;
if (mp->ports)
goto out;
mdb = mlock_dereference(br->mdb, br);
hlist_del_rcu(&mp->hlist[mdb->ver]);
mdb->size--;
call_rcu_bh(&mp->rcu, br_multicast_free_group);
out:
spin_unlock(&br->multicast_lock);
}
static void br_multicast_del_pg(struct net_bridge *br,
struct net_bridge_port_group *pg)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, &pg->addr);
if (WARN_ON(!mp))
return;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p != pg)
continue;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
if (!mp->ports && !mp->mglist &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
return;
}
WARN_ON(1);
}
static void br_multicast_port_group_expired(unsigned long data)
{
struct net_bridge_port_group *pg = (void *)data;
struct net_bridge *br = pg->port->br;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || timer_pending(&pg->timer) ||
hlist_unhashed(&pg->mglist) || pg->state & MDB_PERMANENT)
goto out;
br_multicast_del_pg(br, pg);
out:
spin_unlock(&br->multicast_lock);
}
static int br_mdb_rehash(struct net_bridge_mdb_htable __rcu **mdbp, int max,
int elasticity)
{
struct net_bridge_mdb_htable *old = rcu_dereference_protected(*mdbp, 1);
struct net_bridge_mdb_htable *mdb;
int err;
mdb = kmalloc(sizeof(*mdb), GFP_ATOMIC);
if (!mdb)
return -ENOMEM;
mdb->max = max;
mdb->old = old;
mdb->mhash = kzalloc(max * sizeof(*mdb->mhash), GFP_ATOMIC);
if (!mdb->mhash) {
kfree(mdb);
return -ENOMEM;
}
mdb->size = old ? old->size : 0;
mdb->ver = old ? old->ver ^ 1 : 0;
if (!old || elasticity)
get_random_bytes(&mdb->secret, sizeof(mdb->secret));
else
mdb->secret = old->secret;
if (!old)
goto out;
err = br_mdb_copy(mdb, old, elasticity);
if (err) {
kfree(mdb->mhash);
kfree(mdb);
return err;
}
br_mdb_rehash_seq++;
call_rcu_bh(&mdb->rcu, br_mdb_free);
out:
rcu_assign_pointer(*mdbp, mdb);
return 0;
}
static struct sk_buff *br_ip4_multicast_alloc_query(struct net_bridge *br,
__be32 group)
{
struct sk_buff *skb;
struct igmphdr *ih;
struct ethhdr *eth;
struct iphdr *iph;
skb = netdev_alloc_skb_ip_align(br->dev, sizeof(*eth) + sizeof(*iph) +
sizeof(*ih) + 4);
if (!skb)
goto out;
skb->protocol = htons(ETH_P_IP);
skb_reset_mac_header(skb);
eth = eth_hdr(skb);
memcpy(eth->h_source, br->dev->dev_addr, 6);
eth->h_dest[0] = 1;
eth->h_dest[1] = 0;
eth->h_dest[2] = 0x5e;
eth->h_dest[3] = 0;
eth->h_dest[4] = 0;
eth->h_dest[5] = 1;
eth->h_proto = htons(ETH_P_IP);
skb_put(skb, sizeof(*eth));
skb_set_network_header(skb, skb->len);
iph = ip_hdr(skb);
iph->version = 4;
iph->ihl = 6;
iph->tos = 0xc0;
iph->tot_len = htons(sizeof(*iph) + sizeof(*ih) + 4);
iph->id = 0;
iph->frag_off = htons(IP_DF);
iph->ttl = 1;
iph->protocol = IPPROTO_IGMP;
iph->saddr = br->multicast_query_use_ifaddr ?
inet_select_addr(br->dev, 0, RT_SCOPE_LINK) : 0;
iph->daddr = htonl(INADDR_ALLHOSTS_GROUP);
((u8 *)&iph[1])[0] = IPOPT_RA;
((u8 *)&iph[1])[1] = 4;
((u8 *)&iph[1])[2] = 0;
((u8 *)&iph[1])[3] = 0;
ip_send_check(iph);
skb_put(skb, 24);
skb_set_transport_header(skb, skb->len);
ih = igmp_hdr(skb);
ih->type = IGMP_HOST_MEMBERSHIP_QUERY;
ih->code = (group ? br->multicast_last_member_interval :
br->multicast_query_response_interval) /
(HZ / IGMP_TIMER_SCALE);
ih->group = group;
ih->csum = 0;
ih->csum = ip_compute_csum((void *)ih, sizeof(struct igmphdr));
skb_put(skb, sizeof(*ih));
__skb_pull(skb, sizeof(*eth));
out:
return skb;
}
#if IS_ENABLED(CONFIG_IPV6)
static struct sk_buff *br_ip6_multicast_alloc_query(struct net_bridge *br,
const struct in6_addr *group)
{
struct sk_buff *skb;
struct ipv6hdr *ip6h;
struct mld_msg *mldq;
struct ethhdr *eth;
u8 *hopopt;
unsigned long interval;
skb = netdev_alloc_skb_ip_align(br->dev, sizeof(*eth) + sizeof(*ip6h) +
8 + sizeof(*mldq));
if (!skb)
goto out;
skb->protocol = htons(ETH_P_IPV6);
/* Ethernet header */
skb_reset_mac_header(skb);
eth = eth_hdr(skb);
memcpy(eth->h_source, br->dev->dev_addr, 6);
eth->h_proto = htons(ETH_P_IPV6);
skb_put(skb, sizeof(*eth));
/* IPv6 header + HbH option */
skb_set_network_header(skb, skb->len);
ip6h = ipv6_hdr(skb);
*(__force __be32 *)ip6h = htonl(0x60000000);
ip6h->payload_len = htons(8 + sizeof(*mldq));
ip6h->nexthdr = IPPROTO_HOPOPTS;
ip6h->hop_limit = 1;
ipv6_addr_set(&ip6h->daddr, htonl(0xff020000), 0, 0, htonl(1));
if (ipv6_dev_get_saddr(dev_net(br->dev), br->dev, &ip6h->daddr, 0,
&ip6h->saddr)) {
kfree_skb(skb);
return NULL;
}
ipv6_eth_mc_map(&ip6h->daddr, eth->h_dest);
hopopt = (u8 *)(ip6h + 1);
hopopt[0] = IPPROTO_ICMPV6; /* next hdr */
hopopt[1] = 0; /* length of HbH */
hopopt[2] = IPV6_TLV_ROUTERALERT; /* Router Alert */
hopopt[3] = 2; /* Length of RA Option */
hopopt[4] = 0; /* Type = 0x0000 (MLD) */
hopopt[5] = 0;
hopopt[6] = IPV6_TLV_PAD1; /* Pad1 */
hopopt[7] = IPV6_TLV_PAD1; /* Pad1 */
skb_put(skb, sizeof(*ip6h) + 8);
/* ICMPv6 */
skb_set_transport_header(skb, skb->len);
mldq = (struct mld_msg *) icmp6_hdr(skb);
interval = ipv6_addr_any(group) ?
br->multicast_query_response_interval :
br->multicast_last_member_interval;
mldq->mld_type = ICMPV6_MGM_QUERY;
mldq->mld_code = 0;
mldq->mld_cksum = 0;
mldq->mld_maxdelay = htons((u16)jiffies_to_msecs(interval));
mldq->mld_reserved = 0;
mldq->mld_mca = *group;
/* checksum */
mldq->mld_cksum = csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr,
sizeof(*mldq), IPPROTO_ICMPV6,
csum_partial(mldq,
sizeof(*mldq), 0));
skb_put(skb, sizeof(*mldq));
__skb_pull(skb, sizeof(*eth));
out:
return skb;
}
#endif
static struct sk_buff *br_multicast_alloc_query(struct net_bridge *br,
struct br_ip *addr)
{
switch (addr->proto) {
case htons(ETH_P_IP):
return br_ip4_multicast_alloc_query(br, addr->u.ip4);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return br_ip6_multicast_alloc_query(br, &addr->u.ip6);
#endif
}
return NULL;
}
static struct net_bridge_mdb_entry *br_multicast_get_group(
struct net_bridge *br, struct net_bridge_port *port,
struct br_ip *group, int hash)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
unsigned int count = 0;
unsigned int max;
int elasticity;
int err;
mdb = rcu_dereference_protected(br->mdb, 1);
hlist_for_each_entry(mp, &mdb->mhash[hash], hlist[mdb->ver]) {
count++;
if (unlikely(br_ip_equal(group, &mp->addr)))
return mp;
}
elasticity = 0;
max = mdb->max;
if (unlikely(count > br->hash_elasticity && count)) {
if (net_ratelimit())
br_info(br, "Multicast hash table "
"chain limit reached: %s\n",
port ? port->dev->name : br->dev->name);
elasticity = br->hash_elasticity;
}
if (mdb->size >= max) {
max *= 2;
if (unlikely(max > br->hash_max)) {
br_warn(br, "Multicast hash table maximum of %d "
"reached, disabling snooping: %s\n",
br->hash_max,
port ? port->dev->name : br->dev->name);
err = -E2BIG;
disable:
br->multicast_disabled = 1;
goto err;
}
}
if (max > mdb->max || elasticity) {
if (mdb->old) {
if (net_ratelimit())
br_info(br, "Multicast hash table "
"on fire: %s\n",
port ? port->dev->name : br->dev->name);
err = -EEXIST;
goto err;
}
err = br_mdb_rehash(&br->mdb, max, elasticity);
if (err) {
br_warn(br, "Cannot rehash multicast "
"hash table, disabling snooping: %s, %d, %d\n",
port ? port->dev->name : br->dev->name,
mdb->size, err);
goto disable;
}
err = -EAGAIN;
goto err;
}
return NULL;
err:
mp = ERR_PTR(err);
return mp;
}
struct net_bridge_mdb_entry *br_multicast_new_group(struct net_bridge *br,
struct net_bridge_port *port, struct br_ip *group)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
int hash;
int err;
mdb = rcu_dereference_protected(br->mdb, 1);
if (!mdb) {
err = br_mdb_rehash(&br->mdb, BR_HASH_SIZE, 0);
if (err)
return ERR_PTR(err);
goto rehash;
}
hash = br_ip_hash(mdb, group);
mp = br_multicast_get_group(br, port, group, hash);
switch (PTR_ERR(mp)) {
case 0:
break;
case -EAGAIN:
rehash:
mdb = rcu_dereference_protected(br->mdb, 1);
hash = br_ip_hash(mdb, group);
break;
default:
goto out;
}
mp = kzalloc(sizeof(*mp), GFP_ATOMIC);
if (unlikely(!mp))
return ERR_PTR(-ENOMEM);
mp->br = br;
mp->addr = *group;
hlist_add_head_rcu(&mp->hlist[mdb->ver], &mdb->mhash[hash]);
mdb->size++;
out:
return mp;
}
struct net_bridge_port_group *br_multicast_new_port_group(
struct net_bridge_port *port,
struct br_ip *group,
struct net_bridge_port_group __rcu *next,
unsigned char state)
{
struct net_bridge_port_group *p;
p = kzalloc(sizeof(*p), GFP_ATOMIC);
if (unlikely(!p))
return NULL;
p->addr = *group;
p->port = port;
p->state = state;
rcu_assign_pointer(p->next, next);
hlist_add_head(&p->mglist, &port->mglist);
setup_timer(&p->timer, br_multicast_port_group_expired,
(unsigned long)p);
return p;
}
static int br_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
int err;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
goto err;
if (!port) {
mp->mglist = true;
goto out;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
goto out;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = br_multicast_new_port_group(port, group, *pp, MDB_TEMPORARY);
if (unlikely(!p))
goto err;
rcu_assign_pointer(*pp, p);
br_mdb_notify(br->dev, port, group, RTM_NEWMDB);
out:
err = 0;
err:
spin_unlock(&br->multicast_lock);
return err;
}
static int br_ip4_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
__be32 group,
__u16 vid)
{
struct br_ip br_group;
if (ipv4_is_local_multicast(group))
return 0;
br_group.u.ip4 = group;
br_group.proto = htons(ETH_P_IP);
br_group.vid = vid;
return br_multicast_add_group(br, port, &br_group);
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_add_group(struct net_bridge *br,
struct net_bridge_port *port,
const struct in6_addr *group,
__u16 vid)
{
struct br_ip br_group;
if (!ipv6_is_transient_multicast(group))
return 0;
br_group.u.ip6 = *group;
br_group.proto = htons(ETH_P_IPV6);
br_group.vid = vid;
return br_multicast_add_group(br, port, &br_group);
}
#endif
static void br_multicast_router_expired(unsigned long data)
{
struct net_bridge_port *port = (void *)data;
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (port->multicast_router != 1 ||
timer_pending(&port->multicast_router_timer) ||
hlist_unhashed(&port->rlist))
goto out;
hlist_del_init_rcu(&port->rlist);
out:
spin_unlock(&br->multicast_lock);
}
static void br_multicast_local_router_expired(unsigned long data)
{
}
static void br_multicast_querier_expired(unsigned long data)
{
struct net_bridge *br = (void *)data;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || br->multicast_disabled)
goto out;
br_multicast_start_querier(br);
out:
spin_unlock(&br->multicast_lock);
}
static void __br_multicast_send_query(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *ip)
{
struct sk_buff *skb;
skb = br_multicast_alloc_query(br, ip);
if (!skb)
return;
if (port) {
__skb_push(skb, sizeof(struct ethhdr));
skb->dev = port->dev;
NF_HOOK(NFPROTO_BRIDGE, NF_BR_LOCAL_OUT, skb, NULL, skb->dev,
dev_queue_xmit);
} else
netif_rx(skb);
}
static void br_multicast_send_query(struct net_bridge *br,
struct net_bridge_port *port, u32 sent)
{
unsigned long time;
struct br_ip br_group;
if (!netif_running(br->dev) || br->multicast_disabled ||
!br->multicast_querier ||
timer_pending(&br->multicast_querier_timer))
return;
memset(&br_group.u, 0, sizeof(br_group.u));
br_group.proto = htons(ETH_P_IP);
__br_multicast_send_query(br, port, &br_group);
#if IS_ENABLED(CONFIG_IPV6)
br_group.proto = htons(ETH_P_IPV6);
__br_multicast_send_query(br, port, &br_group);
#endif
time = jiffies;
time += sent < br->multicast_startup_query_count ?
br->multicast_startup_query_interval :
br->multicast_query_interval;
mod_timer(port ? &port->multicast_query_timer :
&br->multicast_query_timer, time);
}
static void br_multicast_port_query_expired(unsigned long data)
{
struct net_bridge_port *port = (void *)data;
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (port->state == BR_STATE_DISABLED ||
port->state == BR_STATE_BLOCKING)
goto out;
if (port->multicast_startup_queries_sent <
br->multicast_startup_query_count)
port->multicast_startup_queries_sent++;
br_multicast_send_query(port->br, port,
port->multicast_startup_queries_sent);
out:
spin_unlock(&br->multicast_lock);
}
void br_multicast_add_port(struct net_bridge_port *port)
{
port->multicast_router = 1;
setup_timer(&port->multicast_router_timer, br_multicast_router_expired,
(unsigned long)port);
setup_timer(&port->multicast_query_timer,
br_multicast_port_query_expired, (unsigned long)port);
}
void br_multicast_del_port(struct net_bridge_port *port)
{
del_timer_sync(&port->multicast_router_timer);
}
static void __br_multicast_enable_port(struct net_bridge_port *port)
{
port->multicast_startup_queries_sent = 0;
if (try_to_del_timer_sync(&port->multicast_query_timer) >= 0 ||
del_timer(&port->multicast_query_timer))
mod_timer(&port->multicast_query_timer, jiffies);
}
void br_multicast_enable_port(struct net_bridge_port *port)
{
struct net_bridge *br = port->br;
spin_lock(&br->multicast_lock);
if (br->multicast_disabled || !netif_running(br->dev))
goto out;
__br_multicast_enable_port(port);
out:
spin_unlock(&br->multicast_lock);
}
void br_multicast_disable_port(struct net_bridge_port *port)
{
struct net_bridge *br = port->br;
struct net_bridge_port_group *pg;
struct hlist_node *n;
spin_lock(&br->multicast_lock);
hlist_for_each_entry_safe(pg, n, &port->mglist, mglist)
br_multicast_del_pg(br, pg);
if (!hlist_unhashed(&port->rlist))
hlist_del_init_rcu(&port->rlist);
del_timer(&port->multicast_router_timer);
del_timer(&port->multicast_query_timer);
spin_unlock(&br->multicast_lock);
}
static int br_ip4_multicast_igmp3_report(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct igmpv3_report *ih;
struct igmpv3_grec *grec;
int i;
int len;
int num;
int type;
int err = 0;
__be32 group;
u16 vid = 0;
if (!pskb_may_pull(skb, sizeof(*ih)))
return -EINVAL;
br_vlan_get_tag(skb, &vid);
ih = igmpv3_report_hdr(skb);
num = ntohs(ih->ngrec);
len = sizeof(*ih);
for (i = 0; i < num; i++) {
len += sizeof(*grec);
if (!pskb_may_pull(skb, len))
return -EINVAL;
grec = (void *)(skb->data + len - sizeof(*grec));
group = grec->grec_mca;
type = grec->grec_type;
len += ntohs(grec->grec_nsrcs) * 4;
if (!pskb_may_pull(skb, len))
return -EINVAL;
/* We treat this as an IGMPv2 report for now. */
switch (type) {
case IGMPV3_MODE_IS_INCLUDE:
case IGMPV3_MODE_IS_EXCLUDE:
case IGMPV3_CHANGE_TO_INCLUDE:
case IGMPV3_CHANGE_TO_EXCLUDE:
case IGMPV3_ALLOW_NEW_SOURCES:
case IGMPV3_BLOCK_OLD_SOURCES:
break;
default:
continue;
}
err = br_ip4_multicast_add_group(br, port, group, vid);
if (err)
break;
}
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_mld2_report(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct icmp6hdr *icmp6h;
struct mld2_grec *grec;
int i;
int len;
int num;
int err = 0;
u16 vid = 0;
if (!pskb_may_pull(skb, sizeof(*icmp6h)))
return -EINVAL;
br_vlan_get_tag(skb, &vid);
icmp6h = icmp6_hdr(skb);
num = ntohs(icmp6h->icmp6_dataun.un_data16[1]);
len = sizeof(*icmp6h);
for (i = 0; i < num; i++) {
__be16 *nsrcs, _nsrcs;
nsrcs = skb_header_pointer(skb,
len + offsetof(struct mld2_grec,
grec_nsrcs),
sizeof(_nsrcs), &_nsrcs);
if (!nsrcs)
return -EINVAL;
if (!pskb_may_pull(skb,
len + sizeof(*grec) +
sizeof(struct in6_addr) * ntohs(*nsrcs)))
return -EINVAL;
grec = (struct mld2_grec *)(skb->data + len);
len += sizeof(*grec) +
sizeof(struct in6_addr) * ntohs(*nsrcs);
/* We treat these as MLDv1 reports for now. */
switch (grec->grec_type) {
case MLD2_MODE_IS_INCLUDE:
case MLD2_MODE_IS_EXCLUDE:
case MLD2_CHANGE_TO_INCLUDE:
case MLD2_CHANGE_TO_EXCLUDE:
case MLD2_ALLOW_NEW_SOURCES:
case MLD2_BLOCK_OLD_SOURCES:
break;
default:
continue;
}
err = br_ip6_multicast_add_group(br, port, &grec->grec_mca,
vid);
if (!err)
break;
}
return err;
}
#endif
/*
* Add port to router_list
* list is maintained ordered by pointer value
* and locked by br->multicast_lock and RCU
*/
static void br_multicast_add_router(struct net_bridge *br,
struct net_bridge_port *port)
{
struct net_bridge_port *p;
struct hlist_node *slot = NULL;
hlist_for_each_entry(p, &br->router_list, rlist) {
if ((unsigned long) port >= (unsigned long) p)
break;
slot = &p->rlist;
}
if (slot)
hlist_add_after_rcu(slot, &port->rlist);
else
hlist_add_head_rcu(&port->rlist, &br->router_list);
}
static void br_multicast_mark_router(struct net_bridge *br,
struct net_bridge_port *port)
{
unsigned long now = jiffies;
if (!port) {
if (br->multicast_router == 1)
mod_timer(&br->multicast_router_timer,
now + br->multicast_querier_interval);
return;
}
if (port->multicast_router != 1)
return;
if (!hlist_unhashed(&port->rlist))
goto timer;
br_multicast_add_router(br, port);
timer:
mod_timer(&port->multicast_router_timer,
now + br->multicast_querier_interval);
}
static void br_multicast_query_received(struct net_bridge *br,
struct net_bridge_port *port,
int saddr)
{
if (saddr)
mod_timer(&br->multicast_querier_timer,
jiffies + br->multicast_querier_interval);
else if (timer_pending(&br->multicast_querier_timer))
return;
br_multicast_mark_router(br, port);
}
static int br_ip4_multicast_query(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
const struct iphdr *iph = ip_hdr(skb);
struct igmphdr *ih = igmp_hdr(skb);
struct net_bridge_mdb_entry *mp;
struct igmpv3_query *ih3;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long max_delay;
unsigned long now = jiffies;
__be32 group;
int err = 0;
u16 vid = 0;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
br_multicast_query_received(br, port, !!iph->saddr);
group = ih->group;
if (skb->len == sizeof(*ih)) {
max_delay = ih->code * (HZ / IGMP_TIMER_SCALE);
if (!max_delay) {
max_delay = 10 * HZ;
group = 0;
}
} else {
if (!pskb_may_pull(skb, sizeof(struct igmpv3_query))) {
err = -EINVAL;
goto out;
}
ih3 = igmpv3_query_hdr(skb);
if (ih3->nsrcs)
goto out;
max_delay = ih3->code ?
IGMPV3_MRC(ih3->code) * (HZ / IGMP_TIMER_SCALE) : 1;
}
if (!group)
goto out;
br_vlan_get_tag(skb, &vid);
mp = br_mdb_ip4_get(mlock_dereference(br->mdb, br), group, vid);
if (!mp)
goto out;
setup_timer(&mp->timer, br_multicast_group_expired, (unsigned long)mp);
mod_timer(&mp->timer, now + br->multicast_membership_interval);
mp->timer_armed = true;
max_delay *= br->multicast_last_member_count;
if (mp->mglist &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, now + max_delay) :
try_to_del_timer_sync(&mp->timer) >= 0))
mod_timer(&mp->timer, now + max_delay);
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (timer_pending(&p->timer) ?
time_after(p->timer.expires, now + max_delay) :
try_to_del_timer_sync(&p->timer) >= 0)
mod_timer(&p->timer, now + max_delay);
}
out:
spin_unlock(&br->multicast_lock);
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_ip6_multicast_query(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
const struct ipv6hdr *ip6h = ipv6_hdr(skb);
struct mld_msg *mld;
struct net_bridge_mdb_entry *mp;
struct mld2_query *mld2q;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
unsigned long max_delay;
unsigned long now = jiffies;
const struct in6_addr *group = NULL;
int err = 0;
u16 vid = 0;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED))
goto out;
br_multicast_query_received(br, port, !ipv6_addr_any(&ip6h->saddr));
if (skb->len == sizeof(*mld)) {
if (!pskb_may_pull(skb, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *) icmp6_hdr(skb);
max_delay = msecs_to_jiffies(ntohs(mld->mld_maxdelay));
if (max_delay)
group = &mld->mld_mca;
} else if (skb->len >= sizeof(*mld2q)) {
if (!pskb_may_pull(skb, sizeof(*mld2q))) {
err = -EINVAL;
goto out;
}
mld2q = (struct mld2_query *)icmp6_hdr(skb);
if (!mld2q->mld2q_nsrcs)
group = &mld2q->mld2q_mca;
max_delay = mld2q->mld2q_mrc ? MLDV2_MRC(ntohs(mld2q->mld2q_mrc)) : 1;
}
if (!group)
goto out;
br_vlan_get_tag(skb, &vid);
mp = br_mdb_ip6_get(mlock_dereference(br->mdb, br), group, vid);
if (!mp)
goto out;
setup_timer(&mp->timer, br_multicast_group_expired, (unsigned long)mp);
mod_timer(&mp->timer, now + br->multicast_membership_interval);
mp->timer_armed = true;
max_delay *= br->multicast_last_member_count;
if (mp->mglist &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, now + max_delay) :
try_to_del_timer_sync(&mp->timer) >= 0))
mod_timer(&mp->timer, now + max_delay);
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (timer_pending(&p->timer) ?
time_after(p->timer.expires, now + max_delay) :
try_to_del_timer_sync(&p->timer) >= 0)
mod_timer(&p->timer, now + max_delay);
}
out:
spin_unlock(&br->multicast_lock);
return err;
}
#endif
static void br_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
struct br_ip *group)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
unsigned long now;
unsigned long time;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) ||
(port && port->state == BR_STATE_DISABLED) ||
timer_pending(&br->multicast_querier_timer))
goto out;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, group);
if (!mp)
goto out;
if (br->multicast_querier &&
!timer_pending(&br->multicast_querier_timer)) {
__br_multicast_send_query(br, port, &mp->addr);
time = jiffies + br->multicast_last_member_count *
br->multicast_last_member_interval;
mod_timer(port ? &port->multicast_query_timer :
&br->multicast_query_timer, time);
for (p = mlock_dereference(mp->ports, br);
p != NULL;
p = mlock_dereference(p->next, br)) {
if (p->port != port)
continue;
if (!hlist_unhashed(&p->mglist) &&
(timer_pending(&p->timer) ?
time_after(p->timer.expires, time) :
try_to_del_timer_sync(&p->timer) >= 0)) {
mod_timer(&p->timer, time);
}
break;
}
}
if (port && (port->flags & BR_MULTICAST_FAST_LEAVE)) {
struct net_bridge_port_group __rcu **pp;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port != port)
continue;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
br_mdb_notify(br->dev, port, group, RTM_DELMDB);
if (!mp->ports && !mp->mglist && mp->timer_armed &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
}
goto out;
}
now = jiffies;
time = now + br->multicast_last_member_count *
br->multicast_last_member_interval;
if (!port) {
if (mp->mglist && mp->timer_armed &&
(timer_pending(&mp->timer) ?
time_after(mp->timer.expires, time) :
try_to_del_timer_sync(&mp->timer) >= 0)) {
mod_timer(&mp->timer, time);
}
}
out:
spin_unlock(&br->multicast_lock);
}
static void br_ip4_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
__be32 group,
__u16 vid)
{
struct br_ip br_group;
if (ipv4_is_local_multicast(group))
return;
br_group.u.ip4 = group;
br_group.proto = htons(ETH_P_IP);
br_group.vid = vid;
br_multicast_leave_group(br, port, &br_group);
}
#if IS_ENABLED(CONFIG_IPV6)
static void br_ip6_multicast_leave_group(struct net_bridge *br,
struct net_bridge_port *port,
const struct in6_addr *group,
__u16 vid)
{
struct br_ip br_group;
if (!ipv6_is_transient_multicast(group))
return;
br_group.u.ip6 = *group;
br_group.proto = htons(ETH_P_IPV6);
br_group.vid = vid;
br_multicast_leave_group(br, port, &br_group);
}
#endif
static int br_multicast_ipv4_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct sk_buff *skb2 = skb;
const struct iphdr *iph;
struct igmphdr *ih;
unsigned int len;
unsigned int offset;
int err;
u16 vid = 0;
/* We treat OOM as packet loss for now. */
if (!pskb_may_pull(skb, sizeof(*iph)))
return -EINVAL;
iph = ip_hdr(skb);
if (iph->ihl < 5 || iph->version != 4)
return -EINVAL;
if (!pskb_may_pull(skb, ip_hdrlen(skb)))
return -EINVAL;
iph = ip_hdr(skb);
if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl)))
return -EINVAL;
if (iph->protocol != IPPROTO_IGMP) {
if (!ipv4_is_local_multicast(iph->daddr))
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
return 0;
}
len = ntohs(iph->tot_len);
if (skb->len < len || len < ip_hdrlen(skb))
return -EINVAL;
if (skb->len > len) {
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return -ENOMEM;
err = pskb_trim_rcsum(skb2, len);
if (err)
goto err_out;
}
len -= ip_hdrlen(skb2);
offset = skb_network_offset(skb2) + ip_hdrlen(skb2);
__skb_pull(skb2, offset);
skb_reset_transport_header(skb2);
err = -EINVAL;
if (!pskb_may_pull(skb2, sizeof(*ih)))
goto out;
switch (skb2->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_fold(skb2->csum))
break;
/* fall through */
case CHECKSUM_NONE:
skb2->csum = 0;
if (skb_checksum_complete(skb2))
goto out;
}
err = 0;
br_vlan_get_tag(skb2, &vid);
BR_INPUT_SKB_CB(skb)->igmp = 1;
ih = igmp_hdr(skb2);
switch (ih->type) {
case IGMP_HOST_MEMBERSHIP_REPORT:
case IGMPV2_HOST_MEMBERSHIP_REPORT:
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
err = br_ip4_multicast_add_group(br, port, ih->group, vid);
break;
case IGMPV3_HOST_MEMBERSHIP_REPORT:
err = br_ip4_multicast_igmp3_report(br, port, skb2);
break;
case IGMP_HOST_MEMBERSHIP_QUERY:
err = br_ip4_multicast_query(br, port, skb2);
break;
case IGMP_HOST_LEAVE_MESSAGE:
br_ip4_multicast_leave_group(br, port, ih->group, vid);
break;
}
out:
__skb_push(skb2, offset);
err_out:
if (skb2 != skb)
kfree_skb(skb2);
return err;
}
#if IS_ENABLED(CONFIG_IPV6)
static int br_multicast_ipv6_rcv(struct net_bridge *br,
struct net_bridge_port *port,
struct sk_buff *skb)
{
struct sk_buff *skb2;
const struct ipv6hdr *ip6h;
u8 icmp6_type;
u8 nexthdr;
__be16 frag_off;
unsigned int len;
int offset;
int err;
u16 vid = 0;
if (!pskb_may_pull(skb, sizeof(*ip6h)))
return -EINVAL;
ip6h = ipv6_hdr(skb);
/*
* We're interested in MLD messages only.
* - Version is 6
* - MLD has always Router Alert hop-by-hop option
* - But we do not support jumbrograms.
*/
if (ip6h->version != 6 ||
ip6h->nexthdr != IPPROTO_HOPOPTS ||
ip6h->payload_len == 0)
return 0;
len = ntohs(ip6h->payload_len) + sizeof(*ip6h);
if (skb->len < len)
return -EINVAL;
nexthdr = ip6h->nexthdr;
offset = ipv6_skip_exthdr(skb, sizeof(*ip6h), &nexthdr, &frag_off);
if (offset < 0 || nexthdr != IPPROTO_ICMPV6)
return 0;
/* Okay, we found ICMPv6 header */
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
return -ENOMEM;
err = -EINVAL;
if (!pskb_may_pull(skb2, offset + sizeof(struct icmp6hdr)))
goto out;
len -= offset - skb_network_offset(skb2);
__skb_pull(skb2, offset);
skb_reset_transport_header(skb2);
skb_postpull_rcsum(skb2, skb_network_header(skb2),
skb_network_header_len(skb2));
icmp6_type = icmp6_hdr(skb2)->icmp6_type;
switch (icmp6_type) {
case ICMPV6_MGM_QUERY:
case ICMPV6_MGM_REPORT:
case ICMPV6_MGM_REDUCTION:
case ICMPV6_MLD2_REPORT:
break;
default:
err = 0;
goto out;
}
/* Okay, we found MLD message. Check further. */
if (skb2->len > len) {
err = pskb_trim_rcsum(skb2, len);
if (err)
goto out;
err = -EINVAL;
}
ip6h = ipv6_hdr(skb2);
switch (skb2->ip_summed) {
case CHECKSUM_COMPLETE:
if (!csum_ipv6_magic(&ip6h->saddr, &ip6h->daddr, skb2->len,
IPPROTO_ICMPV6, skb2->csum))
break;
/*FALLTHROUGH*/
case CHECKSUM_NONE:
skb2->csum = ~csum_unfold(csum_ipv6_magic(&ip6h->saddr,
&ip6h->daddr,
skb2->len,
IPPROTO_ICMPV6, 0));
if (__skb_checksum_complete(skb2))
goto out;
}
err = 0;
br_vlan_get_tag(skb, &vid);
BR_INPUT_SKB_CB(skb)->igmp = 1;
switch (icmp6_type) {
case ICMPV6_MGM_REPORT:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
BR_INPUT_SKB_CB(skb)->mrouters_only = 1;
err = br_ip6_multicast_add_group(br, port, &mld->mld_mca, vid);
break;
}
case ICMPV6_MLD2_REPORT:
err = br_ip6_multicast_mld2_report(br, port, skb2);
break;
case ICMPV6_MGM_QUERY:
err = br_ip6_multicast_query(br, port, skb2);
break;
case ICMPV6_MGM_REDUCTION:
{
struct mld_msg *mld;
if (!pskb_may_pull(skb2, sizeof(*mld))) {
err = -EINVAL;
goto out;
}
mld = (struct mld_msg *)skb_transport_header(skb2);
br_ip6_multicast_leave_group(br, port, &mld->mld_mca, vid);
}
}
out:
kfree_skb(skb2);
return err;
}
#endif
int br_multicast_rcv(struct net_bridge *br, struct net_bridge_port *port,
struct sk_buff *skb)
{
BR_INPUT_SKB_CB(skb)->igmp = 0;
BR_INPUT_SKB_CB(skb)->mrouters_only = 0;
if (br->multicast_disabled)
return 0;
switch (skb->protocol) {
case htons(ETH_P_IP):
return br_multicast_ipv4_rcv(br, port, skb);
#if IS_ENABLED(CONFIG_IPV6)
case htons(ETH_P_IPV6):
return br_multicast_ipv6_rcv(br, port, skb);
#endif
}
return 0;
}
static void br_multicast_query_expired(unsigned long data)
{
struct net_bridge *br = (void *)data;
spin_lock(&br->multicast_lock);
if (br->multicast_startup_queries_sent <
br->multicast_startup_query_count)
br->multicast_startup_queries_sent++;
br_multicast_send_query(br, NULL, br->multicast_startup_queries_sent);
spin_unlock(&br->multicast_lock);
}
void br_multicast_init(struct net_bridge *br)
{
br->hash_elasticity = 4;
br->hash_max = 512;
br->multicast_router = 1;
br->multicast_querier = 0;
br->multicast_query_use_ifaddr = 0;
br->multicast_last_member_count = 2;
br->multicast_startup_query_count = 2;
br->multicast_last_member_interval = HZ;
br->multicast_query_response_interval = 10 * HZ;
br->multicast_startup_query_interval = 125 * HZ / 4;
br->multicast_query_interval = 125 * HZ;
br->multicast_querier_interval = 255 * HZ;
br->multicast_membership_interval = 260 * HZ;
spin_lock_init(&br->multicast_lock);
setup_timer(&br->multicast_router_timer,
br_multicast_local_router_expired, 0);
setup_timer(&br->multicast_querier_timer,
br_multicast_querier_expired, (unsigned long)br);
setup_timer(&br->multicast_query_timer, br_multicast_query_expired,
(unsigned long)br);
}
void br_multicast_open(struct net_bridge *br)
{
br->multicast_startup_queries_sent = 0;
if (br->multicast_disabled)
return;
mod_timer(&br->multicast_query_timer, jiffies);
}
void br_multicast_stop(struct net_bridge *br)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct hlist_node *n;
u32 ver;
int i;
del_timer_sync(&br->multicast_router_timer);
del_timer_sync(&br->multicast_querier_timer);
del_timer_sync(&br->multicast_query_timer);
spin_lock_bh(&br->multicast_lock);
mdb = mlock_dereference(br->mdb, br);
if (!mdb)
goto out;
br->mdb = NULL;
ver = mdb->ver;
for (i = 0; i < mdb->max; i++) {
hlist_for_each_entry_safe(mp, n, &mdb->mhash[i],
hlist[ver]) {
del_timer(&mp->timer);
mp->timer_armed = false;
call_rcu_bh(&mp->rcu, br_multicast_free_group);
}
}
if (mdb->old) {
spin_unlock_bh(&br->multicast_lock);
rcu_barrier_bh();
spin_lock_bh(&br->multicast_lock);
WARN_ON(mdb->old);
}
mdb->old = mdb;
call_rcu_bh(&mdb->rcu, br_mdb_free);
out:
spin_unlock_bh(&br->multicast_lock);
}
int br_multicast_set_router(struct net_bridge *br, unsigned long val)
{
int err = -ENOENT;
spin_lock_bh(&br->multicast_lock);
if (!netif_running(br->dev))
goto unlock;
switch (val) {
case 0:
case 2:
del_timer(&br->multicast_router_timer);
/* fall through */
case 1:
br->multicast_router = val;
err = 0;
break;
default:
err = -EINVAL;
break;
}
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
int br_multicast_set_port_router(struct net_bridge_port *p, unsigned long val)
{
struct net_bridge *br = p->br;
int err = -ENOENT;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev) || p->state == BR_STATE_DISABLED)
goto unlock;
switch (val) {
case 0:
case 1:
case 2:
p->multicast_router = val;
err = 0;
if (val < 2 && !hlist_unhashed(&p->rlist))
hlist_del_init_rcu(&p->rlist);
if (val == 1)
break;
del_timer(&p->multicast_router_timer);
if (val == 0)
break;
br_multicast_add_router(br, p);
break;
default:
err = -EINVAL;
break;
}
unlock:
spin_unlock(&br->multicast_lock);
return err;
}
static void br_multicast_start_querier(struct net_bridge *br)
{
struct net_bridge_port *port;
br_multicast_open(br);
list_for_each_entry(port, &br->port_list, list) {
if (port->state == BR_STATE_DISABLED ||
port->state == BR_STATE_BLOCKING)
continue;
__br_multicast_enable_port(port);
}
}
int br_multicast_toggle(struct net_bridge *br, unsigned long val)
{
int err = 0;
struct net_bridge_mdb_htable *mdb;
spin_lock_bh(&br->multicast_lock);
if (br->multicast_disabled == !val)
goto unlock;
br->multicast_disabled = !val;
if (br->multicast_disabled)
goto unlock;
if (!netif_running(br->dev))
goto unlock;
mdb = mlock_dereference(br->mdb, br);
if (mdb) {
if (mdb->old) {
err = -EEXIST;
rollback:
br->multicast_disabled = !!val;
goto unlock;
}
err = br_mdb_rehash(&br->mdb, mdb->max,
br->hash_elasticity);
if (err)
goto rollback;
}
br_multicast_start_querier(br);
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
int br_multicast_set_querier(struct net_bridge *br, unsigned long val)
{
val = !!val;
spin_lock_bh(&br->multicast_lock);
if (br->multicast_querier == val)
goto unlock;
br->multicast_querier = val;
if (val)
br_multicast_start_querier(br);
unlock:
spin_unlock_bh(&br->multicast_lock);
return 0;
}
int br_multicast_set_hash_max(struct net_bridge *br, unsigned long val)
{
int err = -ENOENT;
u32 old;
struct net_bridge_mdb_htable *mdb;
spin_lock(&br->multicast_lock);
if (!netif_running(br->dev))
goto unlock;
err = -EINVAL;
if (!is_power_of_2(val))
goto unlock;
mdb = mlock_dereference(br->mdb, br);
if (mdb && val < mdb->size)
goto unlock;
err = 0;
old = br->hash_max;
br->hash_max = val;
if (mdb) {
if (mdb->old) {
err = -EEXIST;
rollback:
br->hash_max = old;
goto unlock;
}
err = br_mdb_rehash(&br->mdb, br->hash_max,
br->hash_elasticity);
if (err)
goto rollback;
}
unlock:
spin_unlock(&br->multicast_lock);
return err;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5718_1 |
crossvul-cpp_data_bad_3581_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3581_0 |
crossvul-cpp_data_bad_4716_0 | /*
* reflection.c: Routines for creating an image at runtime.
*
* Author:
* Paolo Molaro (lupus@ximian.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*
*/
#include <config.h>
#include "mono/utils/mono-digest.h"
#include "mono/utils/mono-membar.h"
#include "mono/metadata/reflection.h"
#include "mono/metadata/tabledefs.h"
#include "mono/metadata/metadata-internals.h"
#include <mono/metadata/profiler-private.h>
#include "mono/metadata/class-internals.h"
#include "mono/metadata/gc-internal.h"
#include "mono/metadata/tokentype.h"
#include "mono/metadata/domain-internals.h"
#include "mono/metadata/opcodes.h"
#include "mono/metadata/assembly.h"
#include "mono/metadata/object-internals.h"
#include <mono/metadata/exception.h>
#include <mono/metadata/marshal.h>
#include <mono/metadata/security-manager.h>
#include <stdio.h>
#include <glib.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include "image.h"
#include "cil-coff.h"
#include "mono-endian.h"
#include <mono/metadata/gc-internal.h>
#include <mono/metadata/mempool-internals.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/utils/mono-string.h>
#include <mono/utils/mono-error-internals.h>
#if HAVE_SGEN_GC
static void* reflection_info_desc = NULL;
#define MOVING_GC_REGISTER(addr) do { \
if (!reflection_info_desc) { \
gsize bmap = 1; \
reflection_info_desc = mono_gc_make_descr_from_bitmap (&bmap, 1); \
} \
mono_gc_register_root ((char*)(addr), sizeof (gpointer), reflection_info_desc); \
} while (0)
#else
#define MOVING_GC_REGISTER(addr)
#endif
typedef struct {
char *p;
char *buf;
char *end;
} SigBuffer;
#define TEXT_OFFSET 512
#define CLI_H_SIZE 136
#define FILE_ALIGN 512
#define VIRT_ALIGN 8192
#define START_TEXT_RVA 0x00002000
typedef struct {
MonoReflectionILGen *ilgen;
MonoReflectionType *rtype;
MonoArray *parameters;
MonoArray *generic_params;
MonoGenericContainer *generic_container;
MonoArray *pinfo;
MonoArray *opt_types;
guint32 attrs;
guint32 iattrs;
guint32 call_conv;
guint32 *table_idx; /* note: it's a pointer */
MonoArray *code;
MonoObject *type;
MonoString *name;
MonoBoolean init_locals;
MonoBoolean skip_visibility;
MonoArray *return_modreq;
MonoArray *return_modopt;
MonoArray *param_modreq;
MonoArray *param_modopt;
MonoArray *permissions;
MonoMethod *mhandle;
guint32 nrefs;
gpointer *refs;
/* for PInvoke */
int charset, extra_flags, native_cc;
MonoString *dll, *dllentry;
} ReflectionMethodBuilder;
typedef struct {
guint32 owner;
MonoReflectionGenericParam *gparam;
} GenericParamTableEntry;
const unsigned char table_sizes [MONO_TABLE_NUM] = {
MONO_MODULE_SIZE,
MONO_TYPEREF_SIZE,
MONO_TYPEDEF_SIZE,
0,
MONO_FIELD_SIZE,
0,
MONO_METHOD_SIZE,
0,
MONO_PARAM_SIZE,
MONO_INTERFACEIMPL_SIZE,
MONO_MEMBERREF_SIZE, /* 0x0A */
MONO_CONSTANT_SIZE,
MONO_CUSTOM_ATTR_SIZE,
MONO_FIELD_MARSHAL_SIZE,
MONO_DECL_SECURITY_SIZE,
MONO_CLASS_LAYOUT_SIZE,
MONO_FIELD_LAYOUT_SIZE, /* 0x10 */
MONO_STAND_ALONE_SIGNATURE_SIZE,
MONO_EVENT_MAP_SIZE,
0,
MONO_EVENT_SIZE,
MONO_PROPERTY_MAP_SIZE,
0,
MONO_PROPERTY_SIZE,
MONO_METHOD_SEMA_SIZE,
MONO_METHODIMPL_SIZE,
MONO_MODULEREF_SIZE, /* 0x1A */
MONO_TYPESPEC_SIZE,
MONO_IMPLMAP_SIZE,
MONO_FIELD_RVA_SIZE,
0,
0,
MONO_ASSEMBLY_SIZE, /* 0x20 */
MONO_ASSEMBLY_PROCESSOR_SIZE,
MONO_ASSEMBLYOS_SIZE,
MONO_ASSEMBLYREF_SIZE,
MONO_ASSEMBLYREFPROC_SIZE,
MONO_ASSEMBLYREFOS_SIZE,
MONO_FILE_SIZE,
MONO_EXP_TYPE_SIZE,
MONO_MANIFEST_SIZE,
MONO_NESTED_CLASS_SIZE,
MONO_GENERICPARAM_SIZE, /* 0x2A */
MONO_METHODSPEC_SIZE,
MONO_GENPARCONSTRAINT_SIZE
};
#ifndef DISABLE_REFLECTION_EMIT
static guint32 mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec);
static guint32 mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec);
static guint32 mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *cb);
static guint32 mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper);
static void ensure_runtime_vtable (MonoClass *klass);
static gpointer resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context);
static guint32 mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method);
static guint32 encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context);
static gpointer register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly);
static void reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb);
static void reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb);
#endif
static guint32 mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type);
static guint32 mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec);
static void mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly);
static guint32 encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo);
static guint32 encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type);
static char* type_get_qualified_name (MonoType *type, MonoAssembly *ass);
static void encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf);
static void get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types);
static MonoObject *mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob);
static MonoReflectionType *mono_reflection_type_get_underlying_system_type (MonoReflectionType* t);
static MonoType* mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve);
static MonoReflectionType* mono_reflection_type_resolve_user_types (MonoReflectionType *type);
static gboolean is_sre_array (MonoClass *class);
static gboolean is_sre_byref (MonoClass *class);
static gboolean is_sre_pointer (MonoClass *class);
static gboolean is_sre_method_builder (MonoClass *class);
static gboolean is_sre_ctor_builder (MonoClass *class);
static gboolean is_sr_mono_method (MonoClass *class);
static gboolean is_sr_mono_cmethod (MonoClass *class);
static gboolean is_sr_mono_generic_method (MonoClass *class);
static gboolean is_sr_mono_generic_cmethod (MonoClass *class);
static gboolean is_sr_mono_field (MonoClass *class);
static gboolean is_sr_mono_property (MonoClass *class);
static gboolean is_sre_method_on_tb_inst (MonoClass *class);
static gboolean is_sre_ctor_on_tb_inst (MonoClass *class);
static guint32 mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method);
static guint32 mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m);
static MonoMethod * inflate_method (MonoReflectionGenericClass *type, MonoObject *obj);
#define RESOLVE_TYPE(type) do { type = (void*)mono_reflection_type_resolve_user_types ((MonoReflectionType*)type); } while (0)
#define RESOLVE_ARRAY_TYPE_ELEMENT(array, index) do { \
MonoReflectionType *__type = mono_array_get (array, MonoReflectionType*, index); \
__type = mono_reflection_type_resolve_user_types (__type); \
mono_array_set (arr, MonoReflectionType*, index, __type); \
} while (0)
#define mono_type_array_get_and_resolve(array, index) mono_reflection_type_get_handle ((MonoReflectionType*)mono_array_get (array, gpointer, index))
void
mono_reflection_init (void)
{
}
static void
sigbuffer_init (SigBuffer *buf, int size)
{
buf->buf = g_malloc (size);
buf->p = buf->buf;
buf->end = buf->buf + size;
}
static void
sigbuffer_make_room (SigBuffer *buf, int size)
{
if (buf->end - buf->p < size) {
int new_size = buf->end - buf->buf + size + 32;
char *p = g_realloc (buf->buf, new_size);
size = buf->p - buf->buf;
buf->buf = p;
buf->p = p + size;
buf->end = buf->buf + new_size;
}
}
static void
sigbuffer_add_value (SigBuffer *buf, guint32 val)
{
sigbuffer_make_room (buf, 6);
mono_metadata_encode_value (val, buf->p, &buf->p);
}
static void
sigbuffer_add_byte (SigBuffer *buf, guint8 val)
{
sigbuffer_make_room (buf, 1);
buf->p [0] = val;
buf->p++;
}
static void
sigbuffer_add_mem (SigBuffer *buf, char *p, guint32 size)
{
sigbuffer_make_room (buf, size);
memcpy (buf->p, p, size);
buf->p += size;
}
static void
sigbuffer_free (SigBuffer *buf)
{
g_free (buf->buf);
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mp_g_alloc:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc (image, size);
else
return g_malloc (size);
}
#endif /* !DISABLE_REFLECTION_EMIT */
/**
* image_g_alloc0:
*
* Allocate memory from the @image mempool if it is non-NULL. Otherwise, allocate memory
* from the C heap.
*/
static gpointer
image_g_malloc0 (MonoImage *image, guint size)
{
if (image)
return mono_image_alloc0 (image, size);
else
return g_malloc0 (size);
}
#ifndef DISABLE_REFLECTION_EMIT
static char*
image_strdup (MonoImage *image, const char *s)
{
if (image)
return mono_image_strdup (image, s);
else
return g_strdup (s);
}
#endif
#define image_g_new(image,struct_type, n_structs) \
((struct_type *) image_g_malloc (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
#define image_g_new0(image,struct_type, n_structs) \
((struct_type *) image_g_malloc0 (image, ((gsize) sizeof (struct_type)) * ((gsize) (n_structs))))
static void
alloc_table (MonoDynamicTable *table, guint nrows)
{
table->rows = nrows;
g_assert (table->columns);
if (nrows + 1 >= table->alloc_rows) {
while (nrows + 1 >= table->alloc_rows) {
if (table->alloc_rows == 0)
table->alloc_rows = 16;
else
table->alloc_rows *= 2;
}
table->values = g_renew (guint32, table->values, (table->alloc_rows) * table->columns);
}
}
static void
make_room_in_stream (MonoDynamicStream *stream, int size)
{
if (size <= stream->alloc_size)
return;
while (stream->alloc_size <= size) {
if (stream->alloc_size < 4096)
stream->alloc_size = 4096;
else
stream->alloc_size *= 2;
}
stream->data = g_realloc (stream->data, stream->alloc_size);
}
static guint32
string_heap_insert (MonoDynamicStream *sh, const char *str)
{
guint32 idx;
guint32 len;
gpointer oldkey, oldval;
if (g_hash_table_lookup_extended (sh->hash, str, &oldkey, &oldval))
return GPOINTER_TO_UINT (oldval);
len = strlen (str) + 1;
idx = sh->index;
make_room_in_stream (sh, idx + len);
/*
* We strdup the string even if we already copy them in sh->data
* so that the string pointers in the hash remain valid even if
* we need to realloc sh->data. We may want to avoid that later.
*/
g_hash_table_insert (sh->hash, g_strdup (str), GUINT_TO_POINTER (idx));
memcpy (sh->data + idx, str, len);
sh->index += len;
return idx;
}
static guint32
string_heap_insert_mstring (MonoDynamicStream *sh, MonoString *str)
{
char *name = mono_string_to_utf8 (str);
guint32 idx;
idx = string_heap_insert (sh, name);
g_free (name);
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
string_heap_init (MonoDynamicStream *sh)
{
sh->index = 0;
sh->alloc_size = 4096;
sh->data = g_malloc (4096);
sh->hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
string_heap_insert (sh, "");
}
#endif
static guint32
mono_image_add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memcpy (stream->data + stream->index, data, len);
idx = stream->index;
stream->index += len;
/*
* align index? Not without adding an additional param that controls it since
* we may store a blob value in pieces.
*/
return idx;
}
static guint32
mono_image_add_stream_zero (MonoDynamicStream *stream, guint32 len)
{
guint32 idx;
make_room_in_stream (stream, stream->index + len);
memset (stream->data + stream->index, 0, len);
idx = stream->index;
stream->index += len;
return idx;
}
static void
stream_data_align (MonoDynamicStream *stream)
{
char buf [4] = {0};
guint32 count = stream->index % 4;
/* we assume the stream data will be aligned */
if (count)
mono_image_add_stream_data (stream, buf, 4 - count);
}
#ifndef DISABLE_REFLECTION_EMIT
static int
mono_blob_entry_hash (const char* str)
{
guint len, h;
const char *end;
len = mono_metadata_decode_blob_size (str, &str);
if (len > 0) {
end = str + len;
h = *str;
for (str += 1; str < end; str++)
h = (h << 5) - h + *str;
return h;
} else {
return 0;
}
}
static gboolean
mono_blob_entry_equal (const char *str1, const char *str2) {
int len, len2;
const char *end1;
const char *end2;
len = mono_metadata_decode_blob_size (str1, &end1);
len2 = mono_metadata_decode_blob_size (str2, &end2);
if (len != len2)
return 0;
return memcmp (end1, end2, len) == 0;
}
#endif
static guint32
add_to_blob_cached (MonoDynamicImage *assembly, char *b1, int s1, char *b2, int s2)
{
guint32 idx;
char *copy;
gpointer oldkey, oldval;
copy = g_malloc (s1+s2);
memcpy (copy, b1, s1);
memcpy (copy + s1, b2, s2);
if (g_hash_table_lookup_extended (assembly->blob_cache, copy, &oldkey, &oldval)) {
g_free (copy);
idx = GPOINTER_TO_UINT (oldval);
} else {
idx = mono_image_add_stream_data (&assembly->blob, b1, s1);
mono_image_add_stream_data (&assembly->blob, b2, s2);
g_hash_table_insert (assembly->blob_cache, copy, GUINT_TO_POINTER (idx));
}
return idx;
}
static guint32
sigbuffer_add_to_blob_cached (MonoDynamicImage *assembly, SigBuffer *buf)
{
char blob_size [8];
char *b = blob_size;
guint32 size = buf->p - buf->buf;
/* store length */
g_assert (size <= (buf->end - buf->buf));
mono_metadata_encode_value (size, b, &b);
return add_to_blob_cached (assembly, blob_size, b-blob_size, buf->buf, size);
}
/*
* Copy len * nelem bytes from val to dest, swapping bytes to LE if necessary.
* dest may be misaligned.
*/
static void
swap_with_size (char *dest, const char* val, int len, int nelem) {
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
int elem;
for (elem = 0; elem < nelem; ++elem) {
switch (len) {
case 1:
*dest = *val;
break;
case 2:
dest [0] = val [1];
dest [1] = val [0];
break;
case 4:
dest [0] = val [3];
dest [1] = val [2];
dest [2] = val [1];
dest [3] = val [0];
break;
case 8:
dest [0] = val [7];
dest [1] = val [6];
dest [2] = val [5];
dest [3] = val [4];
dest [4] = val [3];
dest [5] = val [2];
dest [6] = val [1];
dest [7] = val [0];
break;
default:
g_assert_not_reached ();
}
dest += len;
val += len;
}
#else
memcpy (dest, val, len * nelem);
#endif
}
static guint32
add_mono_string_to_blob_cached (MonoDynamicImage *assembly, MonoString *str)
{
char blob_size [64];
char *b = blob_size;
guint32 idx = 0, len;
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
return idx;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoClass *
default_class_from_mono_type (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_OBJECT:
return mono_defaults.object_class;
case MONO_TYPE_VOID:
return mono_defaults.void_class;
case MONO_TYPE_BOOLEAN:
return mono_defaults.boolean_class;
case MONO_TYPE_CHAR:
return mono_defaults.char_class;
case MONO_TYPE_I1:
return mono_defaults.sbyte_class;
case MONO_TYPE_U1:
return mono_defaults.byte_class;
case MONO_TYPE_I2:
return mono_defaults.int16_class;
case MONO_TYPE_U2:
return mono_defaults.uint16_class;
case MONO_TYPE_I4:
return mono_defaults.int32_class;
case MONO_TYPE_U4:
return mono_defaults.uint32_class;
case MONO_TYPE_I:
return mono_defaults.int_class;
case MONO_TYPE_U:
return mono_defaults.uint_class;
case MONO_TYPE_I8:
return mono_defaults.int64_class;
case MONO_TYPE_U8:
return mono_defaults.uint64_class;
case MONO_TYPE_R4:
return mono_defaults.single_class;
case MONO_TYPE_R8:
return mono_defaults.double_class;
case MONO_TYPE_STRING:
return mono_defaults.string_class;
default:
g_warning ("default_class_from_mono_type: implement me 0x%02x\n", type->type);
g_assert_not_reached ();
}
return NULL;
}
#endif
static void
encode_generic_class (MonoDynamicImage *assembly, MonoGenericClass *gclass, SigBuffer *buf)
{
int i;
MonoGenericInst *class_inst;
MonoClass *klass;
g_assert (gclass);
class_inst = gclass->context.class_inst;
sigbuffer_add_value (buf, MONO_TYPE_GENERICINST);
klass = gclass->container_class;
sigbuffer_add_value (buf, klass->byval_arg.type);
sigbuffer_add_value (buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
sigbuffer_add_value (buf, class_inst->type_argc);
for (i = 0; i < class_inst->type_argc; ++i)
encode_type (assembly, class_inst->type_argv [i], buf);
}
static void
encode_type (MonoDynamicImage *assembly, MonoType *type, SigBuffer *buf)
{
if (!type) {
g_assert_not_reached ();
return;
}
if (type->byref)
sigbuffer_add_value (buf, MONO_TYPE_BYREF);
switch (type->type){
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
sigbuffer_add_value (buf, type->type);
break;
case MONO_TYPE_PTR:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, type->data.type, buf);
break;
case MONO_TYPE_SZARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.klass->byval_arg, buf);
break;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS: {
MonoClass *k = mono_class_from_mono_type (type);
if (k->generic_container) {
MonoGenericClass *gclass = mono_metadata_lookup_generic_class (k, k->generic_container->context.class_inst, TRUE);
encode_generic_class (assembly, gclass, buf);
} else {
/*
* Make sure we use the correct type.
*/
sigbuffer_add_value (buf, k->byval_arg.type);
/*
* ensure only non-byref gets passed to mono_image_typedef_or_ref(),
* otherwise two typerefs could point to the same type, leading to
* verification errors.
*/
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, &k->byval_arg));
}
break;
}
case MONO_TYPE_ARRAY:
sigbuffer_add_value (buf, type->type);
encode_type (assembly, &type->data.array->eklass->byval_arg, buf);
sigbuffer_add_value (buf, type->data.array->rank);
sigbuffer_add_value (buf, 0); /* FIXME: set to 0 for now */
sigbuffer_add_value (buf, 0);
break;
case MONO_TYPE_GENERICINST:
encode_generic_class (assembly, type->data.generic_class, buf);
break;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
sigbuffer_add_value (buf, type->type);
sigbuffer_add_value (buf, mono_type_get_generic_param_num (type));
break;
default:
g_error ("need to encode type %x", type->type);
}
}
static void
encode_reflection_type (MonoDynamicImage *assembly, MonoReflectionType *type, SigBuffer *buf)
{
if (!type) {
sigbuffer_add_value (buf, MONO_TYPE_VOID);
return;
}
encode_type (assembly, mono_reflection_type_get_handle (type), buf);
}
static void
encode_custom_modifiers (MonoDynamicImage *assembly, MonoArray *modreq, MonoArray *modopt, SigBuffer *buf)
{
int i;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_REQD);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
sigbuffer_add_byte (buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (buf, mono_image_typedef_or_ref (assembly, mod));
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
method_encode_signature (MonoDynamicImage *assembly, MonoMethodSignature *sig)
{
SigBuffer buf;
int i;
guint32 nparams = sig->param_count;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
idx = sig->call_convention;
if (sig->hasthis)
idx |= 0x20; /* hasthis */
if (sig->generic_param_count)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (sig->generic_param_count)
sigbuffer_add_value (&buf, sig->generic_param_count);
sigbuffer_add_value (&buf, nparams);
encode_type (assembly, sig->ret, &buf);
for (i = 0; i < nparams; ++i) {
if (i == sig->sentinelpos)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
encode_type (assembly, sig->params [i], &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
method_builder_encode_signature (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
/*
* FIXME: reuse code from method_encode_signature().
*/
SigBuffer buf;
int i;
guint32 nparams = mb->parameters ? mono_array_length (mb->parameters): 0;
guint32 ngparams = mb->generic_params ? mono_array_length (mb->generic_params): 0;
guint32 notypes = mb->opt_types ? mono_array_length (mb->opt_types): 0;
guint32 idx;
sigbuffer_init (&buf, 32);
/* LAMESPEC: all the call conv spec is foobared */
idx = mb->call_conv & 0x60; /* has-this, explicit-this */
if (mb->call_conv & 2)
idx |= 0x5; /* vararg */
if (!(mb->attrs & METHOD_ATTRIBUTE_STATIC))
idx |= 0x20; /* hasthis */
if (ngparams)
idx |= 0x10; /* generic */
sigbuffer_add_byte (&buf, idx);
if (ngparams)
sigbuffer_add_value (&buf, ngparams);
sigbuffer_add_value (&buf, nparams + notypes);
encode_custom_modifiers (assembly, mb->return_modreq, mb->return_modopt, &buf);
encode_reflection_type (assembly, mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoArray *modreq = NULL;
MonoArray *modopt = NULL;
MonoReflectionType *pt;
if (mb->param_modreq && (i < mono_array_length (mb->param_modreq)))
modreq = mono_array_get (mb->param_modreq, MonoArray*, i);
if (mb->param_modopt && (i < mono_array_length (mb->param_modopt)))
modopt = mono_array_get (mb->param_modopt, MonoArray*, i);
encode_custom_modifiers (assembly, modreq, modopt, &buf);
pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
if (notypes)
sigbuffer_add_byte (&buf, MONO_TYPE_SENTINEL);
for (i = 0; i < notypes; ++i) {
MonoReflectionType *pt;
pt = mono_array_get (mb->opt_types, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_locals (MonoDynamicImage *assembly, MonoReflectionILGen *ilgen)
{
MonoDynamicTable *table;
guint32 *values;
guint32 idx, sig_idx;
guint nl = mono_array_length (ilgen->locals);
SigBuffer buf;
int i;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, nl);
for (i = 0; i < nl; ++i) {
MonoReflectionLocalBuilder *lb = mono_array_get (ilgen->locals, MonoReflectionLocalBuilder*, i);
if (lb->is_pinned)
sigbuffer_add_value (&buf, MONO_TYPE_PINNED);
encode_reflection_type (assembly, (MonoReflectionType*)lb->type, &buf);
}
sig_idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
if (assembly->standalonesig_cache == NULL)
assembly->standalonesig_cache = g_hash_table_new (NULL, NULL);
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx)));
if (idx)
return idx;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] = sig_idx;
g_hash_table_insert (assembly->standalonesig_cache, GUINT_TO_POINTER (sig_idx), GUINT_TO_POINTER (idx));
return idx;
}
static guint32
method_count_clauses (MonoReflectionILGen *ilgen)
{
guint32 num_clauses = 0;
int i;
MonoILExceptionInfo *ex_info;
for (i = 0; i < mono_array_length (ilgen->ex_handlers); ++i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers)
num_clauses += mono_array_length (ex_info->handlers);
else
num_clauses++;
}
return num_clauses;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoExceptionClause*
method_encode_clauses (MonoImage *image, MonoDynamicImage *assembly, MonoReflectionILGen *ilgen, guint32 num_clauses)
{
MonoExceptionClause *clauses;
MonoExceptionClause *clause;
MonoILExceptionInfo *ex_info;
MonoILExceptionBlock *ex_block;
guint32 finally_start;
int i, j, clause_index;;
clauses = image_g_new0 (image, MonoExceptionClause, num_clauses);
clause_index = 0;
for (i = mono_array_length (ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo*)mono_array_addr (ilgen->ex_handlers, MonoILExceptionInfo, i);
finally_start = ex_info->start + ex_info->len;
if (!ex_info->handlers)
continue;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
clause = &(clauses [clause_index]);
clause->flags = ex_block->type;
clause->try_offset = ex_info->start;
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
clause->try_len = finally_start - ex_info->start;
else
clause->try_len = ex_info->len;
clause->handler_offset = ex_block->start;
clause->handler_len = ex_block->len;
if (ex_block->extype) {
clause->data.catch_class = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
clause->data.filter_offset = ex_block->filter_offset;
else
clause->data.filter_offset = 0;
}
finally_start = ex_block->start + ex_block->len;
clause_index ++;
}
}
return clauses;
}
#endif /* !DISABLE_REFLECTION_EMIT */
static guint32
method_encode_code (MonoDynamicImage *assembly, ReflectionMethodBuilder *mb)
{
char flags = 0;
guint32 idx;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_exception = 0;
gint maybe_small;
guint32 fat_flags;
char fat_header [12];
guint32 int_value;
guint16 short_value;
guint32 local_sig = 0;
guint32 header_size = 12;
MonoArray *code;
if ((mb->attrs & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT)) ||
(mb->iattrs & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME)))
return 0;
/*if (mb->name)
g_print ("Encode method %s\n", mono_string_to_utf8 (mb->name));*/
if (mb->ilgen) {
code = mb->ilgen->code;
code_size = mb->ilgen->code_len;
max_stack = mb->ilgen->max_stack;
num_locals = mb->ilgen->locals ? mono_array_length (mb->ilgen->locals) : 0;
if (mb->ilgen->ex_handlers)
num_exception = method_count_clauses (mb->ilgen);
} else {
code = mb->code;
if (code == NULL){
char *name = mono_string_to_utf8 (mb->name);
char *str = g_strdup_printf ("Method %s does not have any IL associated", name);
MonoException *exception = mono_get_exception_argument (NULL, "a method does not have any IL associated");
g_free (str);
g_free (name);
mono_raise_exception (exception);
}
code_size = mono_array_length (code);
max_stack = 8; /* we probably need to run a verifier on the code... */
}
stream_data_align (&assembly->code);
/* check for exceptions, maxstack, locals */
maybe_small = (max_stack <= 8) && (!num_locals) && (!num_exception);
if (maybe_small) {
if (code_size < 64 && !(code_size & 1)) {
flags = (code_size << 2) | 0x2;
} else if (code_size < 32 && (code_size & 1)) {
flags = (code_size << 2) | 0x6; /* LAMESPEC: see metadata.c */
} else {
goto fat_header;
}
idx = mono_image_add_stream_data (&assembly->code, &flags, 1);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 1));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
return assembly->text_rva + idx;
}
fat_header:
if (num_locals)
local_sig = MONO_TOKEN_SIGNATURE | encode_locals (assembly, mb->ilgen);
/*
* FIXME: need to set also the header size in fat_flags.
* (and more sects and init locals flags)
*/
fat_flags = 0x03;
if (num_exception)
fat_flags |= METHOD_HEADER_MORE_SECTS;
if (mb->init_locals)
fat_flags |= METHOD_HEADER_INIT_LOCALS;
fat_header [0] = fat_flags;
fat_header [1] = (header_size / 4 ) << 4;
short_value = GUINT16_TO_LE (max_stack);
memcpy (fat_header + 2, &short_value, 2);
int_value = GUINT32_TO_LE (code_size);
memcpy (fat_header + 4, &int_value, 4);
int_value = GUINT32_TO_LE (local_sig);
memcpy (fat_header + 8, &int_value, 4);
idx = mono_image_add_stream_data (&assembly->code, fat_header, 12);
/* add to the fixup todo list */
if (mb->ilgen && mb->ilgen->num_token_fixups)
mono_g_hash_table_insert (assembly->token_fixups, mb->ilgen, GUINT_TO_POINTER (idx + 12));
mono_image_add_stream_data (&assembly->code, mono_array_addr (code, char, 0), code_size);
if (num_exception) {
unsigned char sheader [4];
MonoILExceptionInfo * ex_info;
MonoILExceptionBlock * ex_block;
int j;
stream_data_align (&assembly->code);
/* always use fat format for now */
sheader [0] = METHOD_HEADER_SECTION_FAT_FORMAT | METHOD_HEADER_SECTION_EHTABLE;
num_exception *= 6 * sizeof (guint32);
num_exception += 4; /* include the size of the header */
sheader [1] = num_exception & 0xff;
sheader [2] = (num_exception >> 8) & 0xff;
sheader [3] = (num_exception >> 16) & 0xff;
mono_image_add_stream_data (&assembly->code, (char*)sheader, 4);
/* fat header, so we are already aligned */
/* reverse order */
for (i = mono_array_length (mb->ilgen->ex_handlers) - 1; i >= 0; --i) {
ex_info = (MonoILExceptionInfo *)mono_array_addr (mb->ilgen->ex_handlers, MonoILExceptionInfo, i);
if (ex_info->handlers) {
int finally_start = ex_info->start + ex_info->len;
for (j = 0; j < mono_array_length (ex_info->handlers); ++j) {
guint32 val;
ex_block = (MonoILExceptionBlock*)mono_array_addr (ex_info->handlers, MonoILExceptionBlock, j);
/* the flags */
val = GUINT32_TO_LE (ex_block->type);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* try offset */
val = GUINT32_TO_LE (ex_info->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* need fault, too, probably */
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FINALLY)
val = GUINT32_TO_LE (finally_start - ex_info->start);
else
val = GUINT32_TO_LE (ex_info->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler offset */
val = GUINT32_TO_LE (ex_block->start);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/* handler len */
val = GUINT32_TO_LE (ex_block->len);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
finally_start = ex_block->start + ex_block->len;
if (ex_block->extype) {
val = mono_metadata_token_from_dor (mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)ex_block->extype)));
} else {
if (ex_block->type == MONO_EXCEPTION_CLAUSE_FILTER)
val = ex_block->filter_offset;
else
val = 0;
}
val = GUINT32_TO_LE (val);
mono_image_add_stream_data (&assembly->code, (char*)&val, sizeof (guint32));
/*g_print ("out clause %d: from %d len=%d, handler at %d, %d, finally_start=%d, ex_info->start=%d, ex_info->len=%d, ex_block->type=%d, j=%d, i=%d\n",
clause.flags, clause.try_offset, clause.try_len, clause.handler_offset, clause.handler_len, finally_start, ex_info->start, ex_info->len, ex_block->type, j, i);*/
}
} else {
g_error ("No clauses for ex info block %d", i);
}
}
}
return assembly->text_rva + idx;
}
static guint32
find_index_in_table (MonoDynamicImage *assembly, int table_idx, int col, guint32 token)
{
int i;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [table_idx];
g_assert (col < table->columns);
values = table->values + table->columns;
for (i = 1; i <= table->rows; ++i) {
if (values [col] == token)
return i;
values += table->columns;
}
return 0;
}
/*
* LOCKING: Acquires the loader lock.
*/
static MonoCustomAttrInfo*
lookup_custom_attr (MonoImage *image, gpointer member)
{
MonoCustomAttrInfo* res;
res = mono_image_property_lookup (image, member, MONO_PROP_DYNAMIC_CATTR);
if (!res)
return NULL;
return g_memdup (res, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * res->num_attrs);
}
static gboolean
custom_attr_visible (MonoImage *image, MonoReflectionCustomAttr *cattr)
{
/* FIXME: Need to do more checks */
if (cattr->ctor->method && (cattr->ctor->method->klass->image != image)) {
int visibility = cattr->ctor->method->klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if ((visibility != TYPE_ATTRIBUTE_PUBLIC) && (visibility != TYPE_ATTRIBUTE_NESTED_PUBLIC))
return FALSE;
}
return TRUE;
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_builders (MonoImage *alloc_img, MonoImage *image, MonoArray *cattrs)
{
int i, index, count, not_visible;
MonoCustomAttrInfo *ainfo;
MonoReflectionCustomAttr *cattr;
if (!cattrs)
return NULL;
/* FIXME: check in assembly the Run flag is set */
count = mono_array_length (cattrs);
/* Skip nonpublic attributes since MS.NET seems to do the same */
/* FIXME: This needs to be done more globally */
not_visible = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (!custom_attr_visible (image, cattr))
not_visible ++;
}
count -= not_visible;
ainfo = image_g_malloc0 (alloc_img, MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * count);
ainfo->image = image;
ainfo->num_attrs = count;
ainfo->cached = alloc_img != NULL;
index = 0;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
if (custom_attr_visible (image, cattr)) {
unsigned char *saved = mono_image_alloc (image, mono_array_length (cattr->data));
memcpy (saved, mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
ainfo->attrs [index].ctor = cattr->ctor->method;
ainfo->attrs [index].data = saved;
ainfo->attrs [index].data_size = mono_array_length (cattr->data);
index ++;
}
}
return ainfo;
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* LOCKING: Acquires the loader lock.
*/
static void
mono_save_custom_attrs (MonoImage *image, void *obj, MonoArray *cattrs)
{
MonoCustomAttrInfo *ainfo, *tmp;
if (!cattrs || !mono_array_length (cattrs))
return;
ainfo = mono_custom_attrs_from_builders (image, image, cattrs);
mono_loader_lock ();
tmp = mono_image_property_lookup (image, obj, MONO_PROP_DYNAMIC_CATTR);
if (tmp)
mono_custom_attrs_free (tmp);
mono_image_property_insert (image, obj, MONO_PROP_DYNAMIC_CATTR, ainfo);
mono_loader_unlock ();
}
#endif
void
mono_custom_attrs_free (MonoCustomAttrInfo *ainfo)
{
if (!ainfo->cached)
g_free (ainfo);
}
/*
* idx is the table index of the object
* type is one of MONO_CUSTOM_ATTR_*
*/
static void
mono_image_add_cattrs (MonoDynamicImage *assembly, guint32 idx, guint32 type, MonoArray *cattrs)
{
MonoDynamicTable *table;
MonoReflectionCustomAttr *cattr;
guint32 *values;
guint32 count, i, token;
char blob_size [6];
char *p = blob_size;
/* it is legal to pass a NULL cattrs: we avoid to use the if in a lot of places */
if (!cattrs)
return;
count = mono_array_length (cattrs);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_CUSTOM_ATTR_SIZE;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= type;
for (i = 0; i < count; ++i) {
cattr = (MonoReflectionCustomAttr*)mono_array_get (cattrs, gpointer, i);
values [MONO_CUSTOM_ATTR_PARENT] = idx;
token = mono_image_create_token (assembly, (MonoObject*)cattr->ctor, FALSE, FALSE);
type = mono_metadata_token_index (token);
type <<= MONO_CUSTOM_ATTR_TYPE_BITS;
switch (mono_metadata_token_table (token)) {
case MONO_TABLE_METHOD:
type |= MONO_CUSTOM_ATTR_TYPE_METHODDEF;
break;
case MONO_TABLE_MEMBERREF:
type |= MONO_CUSTOM_ATTR_TYPE_MEMBERREF;
break;
default:
g_warning ("got wrong token in custom attr");
continue;
}
values [MONO_CUSTOM_ATTR_TYPE] = type;
p = blob_size;
mono_metadata_encode_value (mono_array_length (cattr->data), p, &p);
values [MONO_CUSTOM_ATTR_VALUE] = add_to_blob_cached (assembly, blob_size, p - blob_size,
mono_array_addr (cattr->data, char, 0), mono_array_length (cattr->data));
values += MONO_CUSTOM_ATTR_SIZE;
++table->next_idx;
}
}
static void
mono_image_add_decl_security (MonoDynamicImage *assembly, guint32 parent_token, MonoArray *permissions)
{
MonoDynamicTable *table;
guint32 *values;
guint32 count, i, idx;
MonoReflectionPermissionSet *perm;
if (!permissions)
return;
count = mono_array_length (permissions);
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
table->rows += count;
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (permissions); ++i) {
perm = (MonoReflectionPermissionSet*)mono_array_addr (permissions, MonoReflectionPermissionSet, i);
values = table->values + table->next_idx * MONO_DECL_SECURITY_SIZE;
idx = mono_metadata_token_index (parent_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
switch (mono_metadata_token_table (parent_token)) {
case MONO_TABLE_TYPEDEF:
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
break;
case MONO_TABLE_METHOD:
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
break;
case MONO_TABLE_ASSEMBLY:
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
break;
default:
g_assert_not_reached ();
}
values [MONO_DECL_SECURITY_ACTION] = perm->action;
values [MONO_DECL_SECURITY_PARENT] = idx;
values [MONO_DECL_SECURITY_PERMISSIONSET] = add_mono_string_to_blob_cached (assembly, perm->pset);
++table->next_idx;
}
}
/*
* Fill in the MethodDef and ParamDef tables for a method.
* This is used for both normal methods and constructors.
*/
static void
mono_image_basic_method (ReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint i, count;
/* room in this table is already allocated */
table = &assembly->tables [MONO_TABLE_METHOD];
*mb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->method_to_table_idx, mb->mhandle, GUINT_TO_POINTER ((*mb->table_idx)));
values = table->values + *mb->table_idx * MONO_METHOD_SIZE;
values [MONO_METHOD_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
values [MONO_METHOD_FLAGS] = mb->attrs;
values [MONO_METHOD_IMPLFLAGS] = mb->iattrs;
values [MONO_METHOD_SIGNATURE] = method_builder_encode_signature (assembly, mb);
values [MONO_METHOD_RVA] = method_encode_code (assembly, mb);
table = &assembly->tables [MONO_TABLE_PARAM];
values [MONO_METHOD_PARAMLIST] = table->next_idx;
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_METHOD, *mb->table_idx), mb->permissions);
if (mb->pinfo) {
MonoDynamicTable *mtable;
guint32 *mvalues;
mtable = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
mvalues = mtable->values + mtable->next_idx * MONO_FIELD_MARSHAL_SIZE;
count = 0;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
if (mono_array_get (mb->pinfo, gpointer, i))
count++;
}
table->rows += count;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_PARAM_SIZE;
for (i = 0; i < mono_array_length (mb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (mb->pinfo, MonoReflectionParamBuilder*, i))) {
values [MONO_PARAM_FLAGS] = pb->attrs;
values [MONO_PARAM_SEQUENCE] = i;
if (pb->name != NULL) {
values [MONO_PARAM_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
} else {
values [MONO_PARAM_NAME] = 0;
}
values += MONO_PARAM_SIZE;
if (pb->marshal_info) {
mtable->rows++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_FIELD_MARSHAL_SIZE;
mvalues [MONO_FIELD_MARSHAL_PARENT] = (table->next_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_PARAMDEF;
mvalues [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, pb->marshal_info);
}
pb->table_idx = table->next_idx++;
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
guint32 field_type = 0;
mtable = &assembly->tables [MONO_TABLE_CONSTANT];
mtable->rows ++;
alloc_table (mtable, mtable->rows);
mvalues = mtable->values + mtable->rows * MONO_CONSTANT_SIZE;
mvalues [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_PARAM | (pb->table_idx << MONO_HASCONSTANT_BITS);
mvalues [MONO_CONSTANT_VALUE] = encode_constant (assembly, pb->def_value, &field_type);
mvalues [MONO_CONSTANT_TYPE] = field_type;
mvalues [MONO_CONSTANT_PADDING] = 0;
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT
static void
reflection_methodbuilder_from_method_builder (ReflectionMethodBuilder *rmb, MonoReflectionMethodBuilder *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_reflection_type_resolve_user_types ((MonoReflectionType*)mb->rtype);
rmb->parameters = mb->parameters;
rmb->generic_params = mb->generic_params;
rmb->generic_container = mb->generic_container;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = mb->code;
rmb->type = mb->type;
rmb->name = mb->name;
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = mb->return_modreq;
rmb->return_modopt = mb->return_modopt;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
if (mb->dll) {
rmb->charset = mb->charset;
rmb->extra_flags = mb->extra_flags;
rmb->native_cc = mb->native_cc;
rmb->dllentry = mb->dllentry;
rmb->dll = mb->dll;
}
}
static void
reflection_methodbuilder_from_ctor_builder (ReflectionMethodBuilder *rmb, MonoReflectionCtorBuilder *mb)
{
const char *name = mb->attrs & METHOD_ATTRIBUTE_STATIC ? ".cctor": ".ctor";
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mono_type_get_object (mono_domain_get (), &mono_defaults.void_class->byval_arg);
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = mb->pinfo;
rmb->attrs = mb->attrs;
rmb->iattrs = mb->iattrs;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = mb->type;
rmb->name = mono_string_new (mono_domain_get (), name);
rmb->table_idx = &mb->table_idx;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = FALSE;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = mb->param_modreq;
rmb->param_modopt = mb->param_modopt;
rmb->permissions = mb->permissions;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
static void
reflection_methodbuilder_from_dynamic_method (ReflectionMethodBuilder *rmb, MonoReflectionDynamicMethod *mb)
{
memset (rmb, 0, sizeof (ReflectionMethodBuilder));
rmb->ilgen = mb->ilgen;
rmb->rtype = mb->rtype;
rmb->parameters = mb->parameters;
rmb->generic_params = NULL;
rmb->generic_container = NULL;
rmb->opt_types = NULL;
rmb->pinfo = NULL;
rmb->attrs = mb->attrs;
rmb->iattrs = 0;
rmb->call_conv = mb->call_conv;
rmb->code = NULL;
rmb->type = (MonoObject *) mb->owner;
rmb->name = mb->name;
rmb->table_idx = NULL;
rmb->init_locals = mb->init_locals;
rmb->skip_visibility = mb->skip_visibility;
rmb->return_modreq = NULL;
rmb->return_modopt = NULL;
rmb->param_modreq = NULL;
rmb->param_modopt = NULL;
rmb->permissions = NULL;
rmb->mhandle = mb->mhandle;
rmb->nrefs = 0;
rmb->refs = NULL;
}
#endif
static void
mono_image_add_methodimpl (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)mb->type;
MonoDynamicTable *table;
guint32 *values;
guint32 tok;
if (!mb->override_method)
return;
table = &assembly->tables [MONO_TABLE_METHODIMPL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_METHODIMPL_SIZE;
values [MONO_METHODIMPL_CLASS] = tb->table_idx;
values [MONO_METHODIMPL_BODY] = MONO_METHODDEFORREF_METHODDEF | (mb->table_idx << MONO_METHODDEFORREF_BITS);
tok = mono_image_create_token (assembly, (MonoObject*)mb->override_method, FALSE, FALSE);
switch (mono_metadata_token_table (tok)) {
case MONO_TABLE_MEMBERREF:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
tok = (mono_metadata_token_index (tok) << MONO_METHODDEFORREF_BITS ) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
values [MONO_METHODIMPL_DECLARATION] = tok;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
mono_image_get_method_info (MonoReflectionMethodBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
ReflectionMethodBuilder rmb;
int i;
reflection_methodbuilder_from_method_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
if (mb->dll) { /* It's a P/Invoke method */
guint32 moduleref;
/* map CharSet values to on-disk values */
int ncharset = (mb->charset ? (mb->charset - 1) * 2 : 0);
int extra_flags = mb->extra_flags;
table = &assembly->tables [MONO_TABLE_IMPLMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_IMPLMAP_SIZE;
values [MONO_IMPLMAP_FLAGS] = (mb->native_cc << 8) | ncharset | extra_flags;
values [MONO_IMPLMAP_MEMBER] = (mb->table_idx << 1) | 1; /* memberforwarded: method */
if (mb->dllentry)
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->dllentry);
else
values [MONO_IMPLMAP_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->name);
moduleref = string_heap_insert_mstring (&assembly->sheap, mb->dll);
if (!(values [MONO_IMPLMAP_SCOPE] = find_index_in_table (assembly, MONO_TABLE_MODULEREF, MONO_MODULEREF_NAME, moduleref))) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
table->rows ++;
alloc_table (table, table->rows);
table->values [table->rows * MONO_MODULEREF_SIZE + MONO_MODULEREF_NAME] = moduleref;
values [MONO_IMPLMAP_SCOPE] = table->rows;
}
}
if (mb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (mb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (mb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_METHOD | (mb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (mb->generic_params, gpointer, i), owner, assembly);
}
}
}
static void
mono_image_get_ctor_info (MonoDomain *domain, MonoReflectionCtorBuilder *mb, MonoDynamicImage *assembly)
{
ReflectionMethodBuilder rmb;
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mono_image_basic_method (&rmb, assembly);
mb->table_idx = *rmb.table_idx;
}
#endif
static char*
type_get_fully_qualified_name (MonoType *type)
{
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
static char*
type_get_qualified_name (MonoType *type, MonoAssembly *ass) {
MonoClass *klass;
MonoAssembly *ta;
klass = mono_class_from_mono_type (type);
if (!klass)
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
ta = klass->image->assembly;
if (ta->dynamic || (ta == ass)) {
if (klass->generic_class || klass->generic_container)
/* For generic type definitions, we want T, while REFLECTION returns T<K> */
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_FULL_NAME);
else
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_REFLECTION);
}
return mono_type_get_name_full (type, MONO_TYPE_NAME_FORMAT_ASSEMBLY_QUALIFIED);
}
#ifndef DISABLE_REFLECTION_EMIT
/*field_image is the image to which the eventual custom mods have been encoded against*/
static guint32
fieldref_encode_signature (MonoDynamicImage *assembly, MonoImage *field_image, MonoType *type)
{
SigBuffer buf;
guint32 idx, i, token;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
/* encode custom attributes before the type */
if (type->num_mods) {
for (i = 0; i < type->num_mods; ++i) {
if (field_image) {
MonoClass *class = mono_class_get (field_image, type->modifiers [i].token);
g_assert (class);
token = mono_image_typedef_or_ref (assembly, &class->byval_arg);
} else {
token = type->modifiers [i].token;
}
if (type->modifiers [i].required)
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_REQD);
else
sigbuffer_add_byte (&buf, MONO_TYPE_CMOD_OPT);
sigbuffer_add_value (&buf, token);
}
}
encode_type (assembly, type, &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
#endif
static guint32
field_encode_signature (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
SigBuffer buf;
guint32 idx;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
encode_custom_modifiers (assembly, fb->modreq, fb->modopt, &buf);
/* encode custom attributes before the type */
encode_reflection_type (assembly, (MonoReflectionType*)fb->type, &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
encode_constant (MonoDynamicImage *assembly, MonoObject *val, guint32 *ret_type) {
char blob_size [64];
char *b = blob_size;
char *p, *box_val;
char* buf;
guint32 idx = 0, len = 0, dummy = 0;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
guint32 fpa_double [2];
guint32 *fpa_p;
#endif
#endif
p = buf = g_malloc (64);
if (!val) {
*ret_type = MONO_TYPE_CLASS;
len = 4;
box_val = (char*)&dummy;
} else {
box_val = ((char*)val) + sizeof (MonoObject);
*ret_type = val->vtable->klass->byval_arg.type;
}
handle_enum:
switch (*ret_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
len = 1;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
len = 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
len = 4;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
len = 8;
break;
case MONO_TYPE_R8:
len = 8;
#ifdef ARM_FPU_FPA
#if G_BYTE_ORDER == G_LITTLE_ENDIAN
fpa_p = (guint32*)box_val;
fpa_double [0] = fpa_p [1];
fpa_double [1] = fpa_p [0];
box_val = (char*)fpa_double;
#endif
#endif
break;
case MONO_TYPE_VALUETYPE:
if (val->vtable->klass->enumtype) {
*ret_type = mono_class_enum_basetype (val->vtable->klass)->type;
goto handle_enum;
} else
g_error ("we can't encode valuetypes");
case MONO_TYPE_CLASS:
break;
case MONO_TYPE_STRING: {
MonoString *str = (MonoString*)val;
/* there is no signature */
len = str->length * 2;
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, swapped, len);
g_free (swapped);
}
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, (char*)mono_string_chars (str), len);
#endif
g_free (buf);
return idx;
}
case MONO_TYPE_GENERICINST:
*ret_type = val->vtable->klass->generic_class->container_class->byval_arg.type;
goto handle_enum;
default:
g_error ("we don't encode constant type 0x%02x yet", *ret_type);
}
/* there is no signature */
mono_metadata_encode_value (len, b, &b);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
idx = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
swap_with_size (blob_size, box_val, len, 1);
mono_image_add_stream_data (&assembly->blob, blob_size, len);
#else
idx = add_to_blob_cached (assembly, blob_size, b-blob_size, box_val, len);
#endif
g_free (buf);
return idx;
}
static guint32
encode_marshal_blob (MonoDynamicImage *assembly, MonoReflectionMarshal *minfo) {
char *str;
SigBuffer buf;
guint32 idx, len;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, minfo->type);
switch (minfo->type) {
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
sigbuffer_add_value (&buf, minfo->count);
break;
case MONO_NATIVE_LPARRAY:
if (minfo->eltype || minfo->has_size) {
sigbuffer_add_value (&buf, minfo->eltype);
if (minfo->has_size) {
sigbuffer_add_value (&buf, minfo->param_num != -1? minfo->param_num: 0);
sigbuffer_add_value (&buf, minfo->count != -1? minfo->count: 0);
/* LAMESPEC: ElemMult is undocumented */
sigbuffer_add_value (&buf, minfo->param_num != -1? 1: 0);
}
}
break;
case MONO_NATIVE_SAFEARRAY:
if (minfo->eltype)
sigbuffer_add_value (&buf, minfo->eltype);
break;
case MONO_NATIVE_CUSTOM:
if (minfo->guid) {
str = mono_string_to_utf8 (minfo->guid);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
/* native type name */
sigbuffer_add_value (&buf, 0);
/* custom marshaler type name */
if (minfo->marshaltype || minfo->marshaltyperef) {
if (minfo->marshaltyperef)
str = type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
else
str = mono_string_to_utf8 (minfo->marshaltype);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
/* FIXME: Actually a bug, since this field is required. Punting for now ... */
sigbuffer_add_value (&buf, 0);
}
if (minfo->mcookie) {
str = mono_string_to_utf8 (minfo->mcookie);
len = strlen (str);
sigbuffer_add_value (&buf, len);
sigbuffer_add_mem (&buf, str, len);
g_free (str);
} else {
sigbuffer_add_value (&buf, 0);
}
break;
default:
break;
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_field_info (MonoReflectionFieldBuilder *fb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
/* maybe this fixup should be done in the C# code */
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL)
fb->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
table = &assembly->tables [MONO_TABLE_FIELD];
fb->table_idx = table->next_idx ++;
g_hash_table_insert (assembly->field_to_table_idx, fb->handle, GUINT_TO_POINTER (fb->table_idx));
values = table->values + fb->table_idx * MONO_FIELD_SIZE;
values [MONO_FIELD_NAME] = string_heap_insert_mstring (&assembly->sheap, fb->name);
values [MONO_FIELD_FLAGS] = fb->attrs;
values [MONO_FIELD_SIGNATURE] = field_encode_signature (assembly, fb);
if (fb->offset != -1) {
table = &assembly->tables [MONO_TABLE_FIELDLAYOUT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_LAYOUT_SIZE;
values [MONO_FIELD_LAYOUT_FIELD] = fb->table_idx;
values [MONO_FIELD_LAYOUT_OFFSET] = fb->offset;
}
if (fb->attrs & FIELD_ATTRIBUTE_LITERAL) {
guint32 field_type = 0;
table = &assembly->tables [MONO_TABLE_CONSTANT];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CONSTANT_SIZE;
values [MONO_CONSTANT_PARENT] = MONO_HASCONSTANT_FIEDDEF | (fb->table_idx << MONO_HASCONSTANT_BITS);
values [MONO_CONSTANT_VALUE] = encode_constant (assembly, fb->def_value, &field_type);
values [MONO_CONSTANT_TYPE] = field_type;
values [MONO_CONSTANT_PADDING] = 0;
}
if (fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) {
guint32 rva_idx;
table = &assembly->tables [MONO_TABLE_FIELDRVA];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_RVA_SIZE;
values [MONO_FIELD_RVA_FIELD] = fb->table_idx;
/*
* We store it in the code section because it's simpler for now.
*/
if (fb->rva_data) {
if (mono_array_length (fb->rva_data) >= 10)
stream_data_align (&assembly->code);
rva_idx = mono_image_add_stream_data (&assembly->code, mono_array_addr (fb->rva_data, char, 0), mono_array_length (fb->rva_data));
} else
rva_idx = mono_image_add_stream_zero (&assembly->code, mono_class_value_size (fb->handle->parent, NULL));
values [MONO_FIELD_RVA_RVA] = rva_idx + assembly->text_rva;
}
if (fb->marshal_info) {
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_FIELD_MARSHAL_SIZE;
values [MONO_FIELD_MARSHAL_PARENT] = (fb->table_idx << MONO_HAS_FIELD_MARSHAL_BITS) | MONO_HAS_FIELD_MARSHAL_FIELDSREF;
values [MONO_FIELD_MARSHAL_NATIVE_TYPE] = encode_marshal_blob (assembly, fb->marshal_info);
}
}
static guint32
property_encode_signature (MonoDynamicImage *assembly, MonoReflectionPropertyBuilder *fb)
{
SigBuffer buf;
guint32 nparams = 0;
MonoReflectionMethodBuilder *mb = fb->get_method;
MonoReflectionMethodBuilder *smb = fb->set_method;
guint32 idx, i;
if (mb && mb->parameters)
nparams = mono_array_length (mb->parameters);
if (!mb && smb && smb->parameters)
nparams = mono_array_length (smb->parameters) - 1;
sigbuffer_init (&buf, 32);
sigbuffer_add_byte (&buf, 0x08);
sigbuffer_add_value (&buf, nparams);
if (mb) {
encode_reflection_type (assembly, (MonoReflectionType*)mb->rtype, &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (mb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else if (smb && smb->parameters) {
/* the property type is the last param */
encode_reflection_type (assembly, mono_array_get (smb->parameters, MonoReflectionType*, nparams), &buf);
for (i = 0; i < nparams; ++i) {
MonoReflectionType *pt = mono_array_get (smb->parameters, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
} else {
encode_reflection_type (assembly, (MonoReflectionType*)fb->type, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static void
mono_image_get_property_info (MonoReflectionPropertyBuilder *pb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* PROPERTYMAP (info already filled in _get_type_info ())
* PROPERTY (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
*/
table = &assembly->tables [MONO_TABLE_PROPERTY];
pb->table_idx = table->next_idx ++;
values = table->values + pb->table_idx * MONO_PROPERTY_SIZE;
values [MONO_PROPERTY_NAME] = string_heap_insert_mstring (&assembly->sheap, pb->name);
values [MONO_PROPERTY_FLAGS] = pb->attrs;
values [MONO_PROPERTY_TYPE] = property_encode_signature (assembly, pb);
/* FIXME: we still don't handle 'other' methods */
if (pb->get_method) num_methods ++;
if (pb->set_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (pb->get_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_GETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->get_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
if (pb->set_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_SETTER;
values [MONO_METHOD_SEMA_METHOD] = pb->set_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (pb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_PROPERTY;
}
}
static void
mono_image_get_event_info (MonoReflectionEventBuilder *eb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint num_methods = 0;
guint32 semaidx;
/*
* we need to set things in the following tables:
* EVENTMAP (info already filled in _get_type_info ())
* EVENT (rows already preallocated in _get_type_info ())
* METHOD (method info already done with the generic method code)
* METHODSEMANTICS
*/
table = &assembly->tables [MONO_TABLE_EVENT];
eb->table_idx = table->next_idx ++;
values = table->values + eb->table_idx * MONO_EVENT_SIZE;
values [MONO_EVENT_NAME] = string_heap_insert_mstring (&assembly->sheap, eb->name);
values [MONO_EVENT_FLAGS] = eb->attrs;
values [MONO_EVENT_TYPE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (eb->type));
/*
* FIXME: we still don't handle 'other' methods
*/
if (eb->add_method) num_methods ++;
if (eb->remove_method) num_methods ++;
if (eb->raise_method) num_methods ++;
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
table->rows += num_methods;
alloc_table (table, table->rows);
if (eb->add_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_ADD_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->add_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->remove_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_REMOVE_ON;
values [MONO_METHOD_SEMA_METHOD] = eb->remove_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
if (eb->raise_method) {
semaidx = table->next_idx ++;
values = table->values + semaidx * MONO_METHOD_SEMA_SIZE;
values [MONO_METHOD_SEMA_SEMANTICS] = METHOD_SEMANTIC_FIRE;
values [MONO_METHOD_SEMA_METHOD] = eb->raise_method->table_idx;
values [MONO_METHOD_SEMA_ASSOCIATION] = (eb->table_idx << MONO_HAS_SEMANTICS_BITS) | MONO_HAS_SEMANTICS_EVENT;
}
}
static void
encode_constraints (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 num_constraints, i;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAMCONSTRAINT];
num_constraints = gparam->iface_constraints ?
mono_array_length (gparam->iface_constraints) : 0;
table->rows += num_constraints;
if (gparam->base_type)
table->rows++;
alloc_table (table, table->rows);
if (gparam->base_type) {
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (gparam->base_type));
}
for (i = 0; i < num_constraints; i++) {
MonoReflectionType *constraint = mono_array_get (
gparam->iface_constraints, gpointer, i);
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENPARCONSTRAINT_SIZE;
values [MONO_GENPARCONSTRAINT_GENERICPAR] = owner;
values [MONO_GENPARCONSTRAINT_CONSTRAINT] = mono_image_typedef_or_ref (
assembly, mono_reflection_type_get_handle (constraint));
}
}
static void
mono_image_get_generic_param_info (MonoReflectionGenericParam *gparam, guint32 owner, MonoDynamicImage *assembly)
{
GenericParamTableEntry *entry;
/*
* The GenericParam table must be sorted according to the `owner' field.
* We need to do this sorting prior to writing the GenericParamConstraint
* table, since we have to use the final GenericParam table indices there
* and they must also be sorted.
*/
entry = g_new0 (GenericParamTableEntry, 1);
entry->owner = owner;
/* FIXME: track where gen_params should be freed and remove the GC root as well */
MOVING_GC_REGISTER (&entry->gparam);
entry->gparam = gparam;
g_ptr_array_add (assembly->gen_params, entry);
}
static void
write_generic_param_entry (MonoDynamicImage *assembly, GenericParamTableEntry *entry)
{
MonoDynamicTable *table;
MonoGenericParam *param;
guint32 *values;
guint32 table_idx;
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table_idx = table->next_idx ++;
values = table->values + table_idx * MONO_GENERICPARAM_SIZE;
param = mono_reflection_type_get_handle ((MonoReflectionType*)entry->gparam)->data.generic_param;
values [MONO_GENERICPARAM_OWNER] = entry->owner;
values [MONO_GENERICPARAM_FLAGS] = entry->gparam->attrs;
values [MONO_GENERICPARAM_NUMBER] = mono_generic_param_num (param);
values [MONO_GENERICPARAM_NAME] = string_heap_insert (&assembly->sheap, mono_generic_param_info (param)->name);
mono_image_add_cattrs (assembly, table_idx, MONO_CUSTOM_ATTR_GENERICPAR, entry->gparam->cattrs);
encode_constraints (entry->gparam, table_idx, assembly);
}
static guint32
resolution_scope_from_image (MonoDynamicImage *assembly, MonoImage *image)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
guint32 cols [MONO_ASSEMBLY_SIZE];
const char *pubkey;
guint32 publen;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, image))))
return token;
if (image->assembly->dynamic && (image->assembly == assembly->image.assembly)) {
table = &assembly->tables [MONO_TABLE_MODULEREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_MODULEREF_SIZE;
values [MONO_MODULEREF_NAME] = string_heap_insert (&assembly->sheap, image->module_name);
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_MODULEREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
if (image->assembly->dynamic)
/* FIXME: */
memset (cols, 0, sizeof (cols));
else {
/* image->assembly->image is the manifest module */
image = image->assembly->image;
mono_metadata_decode_row (&image->tables [MONO_TABLE_ASSEMBLY], 0, cols, MONO_ASSEMBLY_SIZE);
}
table = &assembly->tables [MONO_TABLE_ASSEMBLYREF];
token = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + token * MONO_ASSEMBLYREF_SIZE;
values [MONO_ASSEMBLYREF_NAME] = string_heap_insert (&assembly->sheap, image->assembly_name);
values [MONO_ASSEMBLYREF_MAJOR_VERSION] = cols [MONO_ASSEMBLY_MAJOR_VERSION];
values [MONO_ASSEMBLYREF_MINOR_VERSION] = cols [MONO_ASSEMBLY_MINOR_VERSION];
values [MONO_ASSEMBLYREF_BUILD_NUMBER] = cols [MONO_ASSEMBLY_BUILD_NUMBER];
values [MONO_ASSEMBLYREF_REV_NUMBER] = cols [MONO_ASSEMBLY_REV_NUMBER];
values [MONO_ASSEMBLYREF_FLAGS] = 0;
values [MONO_ASSEMBLYREF_CULTURE] = 0;
values [MONO_ASSEMBLYREF_HASH_VALUE] = 0;
if (strcmp ("", image->assembly->aname.culture)) {
values [MONO_ASSEMBLYREF_CULTURE] = string_heap_insert (&assembly->sheap,
image->assembly->aname.culture);
}
if ((pubkey = mono_image_get_public_key (image, &publen))) {
guchar pubtoken [9];
pubtoken [0] = 8;
mono_digest_get_public_token (pubtoken + 1, (guchar*)pubkey, publen);
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = mono_image_add_stream_data (&assembly->blob, (char*)pubtoken, 9);
} else {
values [MONO_ASSEMBLYREF_PUBLIC_KEY] = 0;
}
token <<= MONO_RESOLTION_SCOPE_BITS;
token |= MONO_RESOLTION_SCOPE_ASSEMBLYREF;
g_hash_table_insert (assembly->handleref, image, GUINT_TO_POINTER (token));
return token;
}
static guint32
create_typespec (MonoDynamicImage *assembly, MonoType *type)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token;
SigBuffer buf;
if ((token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type))))
return token;
sigbuffer_init (&buf, 32);
switch (type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_GENERICINST:
encode_type (assembly, type, &buf);
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE: {
MonoClass *k = mono_class_from_mono_type (type);
if (!k || !k->generic_container) {
sigbuffer_free (&buf);
return 0;
}
encode_type (assembly, type, &buf);
break;
}
default:
sigbuffer_free (&buf);
return 0;
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
static guint32
mono_image_typedef_or_ref_full (MonoDynamicImage *assembly, MonoType *type, gboolean try_typespec)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, scope, enclosing;
MonoClass *klass;
/* if the type requires a typespec, we must try that first*/
if (try_typespec && (token = create_typespec (assembly, type)))
return token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typeref, type));
if (token)
return token;
klass = mono_class_from_mono_type (type);
if (!klass)
klass = mono_class_from_mono_type (type);
/*
* If it's in the same module and not a generic type parameter:
*/
if ((klass->image == &assembly->image) && (type->type != MONO_TYPE_VAR) &&
(type->type != MONO_TYPE_MVAR)) {
MonoReflectionTypeBuilder *tb = klass->reflection_info;
token = MONO_TYPEDEFORREF_TYPEDEF | (tb->table_idx << MONO_TYPEDEFORREF_BITS);
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), klass->reflection_info);
return token;
}
if (klass->nested_in) {
enclosing = mono_image_typedef_or_ref_full (assembly, &klass->nested_in->byval_arg, FALSE);
/* get the typeref idx of the enclosing type */
enclosing >>= MONO_TYPEDEFORREF_BITS;
scope = (enclosing << MONO_RESOLTION_SCOPE_BITS) | MONO_RESOLTION_SCOPE_TYPEREF;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
}
table = &assembly->tables [MONO_TABLE_TYPEREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPEREF_SIZE;
values [MONO_TYPEREF_SCOPE] = scope;
values [MONO_TYPEREF_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_TYPEREF_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
}
token = MONO_TYPEDEFORREF_TYPEREF | (table->next_idx << MONO_TYPEDEFORREF_BITS); /* typeref */
g_hash_table_insert (assembly->typeref, type, GUINT_TO_POINTER(token));
table->next_idx ++;
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), klass->reflection_info);
return token;
}
/*
* Despite the name, we handle also TypeSpec (with the above helper).
*/
static guint32
mono_image_typedef_or_ref (MonoDynamicImage *assembly, MonoType *type)
{
return mono_image_typedef_or_ref_full (assembly, type, TRUE);
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* Insert a memberef row into the metadata: the token that point to the memberref
* is returned. Caching is done in the caller (mono_image_get_methodref_token() or
* mono_image_get_fieldref_token()).
* The sig param is an index to an already built signature.
*/
static guint32
mono_image_get_memberref_token (MonoDynamicImage *assembly, MonoType *type, const char *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, pclass;
guint32 parent;
parent = mono_image_typedef_or_ref (assembly, type);
switch (parent & MONO_TYPEDEFORREF_MASK) {
case MONO_TYPEDEFORREF_TYPEREF:
pclass = MONO_MEMBERREF_PARENT_TYPEREF;
break;
case MONO_TYPEDEFORREF_TYPESPEC:
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
break;
case MONO_TYPEDEFORREF_TYPEDEF:
pclass = MONO_MEMBERREF_PARENT_TYPEDEF;
break;
default:
g_warning ("unknown typeref or def token 0x%08x for %s", parent, name);
return 0;
}
/* extract the index */
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
mono_image_get_methodref_token (MonoDynamicImage *assembly, MonoMethod *method, gboolean create_typespec)
{
guint32 token;
MonoMethodSignature *sig;
create_typespec = create_typespec && method->is_generic && method->klass->image != &assembly->image;
if (create_typespec) {
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1)));
if (token)
return token;
}
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token && !create_typespec)
return token;
g_assert (!method->is_inflated);
if (!token) {
/*
* A methodref signature can't contain an unmanaged calling convention.
*/
sig = mono_metadata_signature_dup (mono_method_signature (method));
if ((sig->call_convention != MONO_CALL_DEFAULT) && (sig->call_convention != MONO_CALL_VARARG))
sig->call_convention = MONO_CALL_DEFAULT;
token = mono_image_get_memberref_token (assembly, &method->klass->byval_arg,
method->name, method_encode_signature (assembly, sig));
g_free (sig);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
}
if (create_typespec) {
MonoDynamicTable *table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF);
token = (mono_metadata_token_index (token) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
if (assembly->save) {
guint32 *values;
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = token;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_sig (assembly, &mono_method_get_generic_container (method)->context);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
/*methodspec and memberef tokens are diferent, */
g_hash_table_insert (assembly->handleref, GUINT_TO_POINTER (GPOINTER_TO_UINT (method) + 1), GUINT_TO_POINTER (token));
return token;
}
return token;
}
static guint32
mono_image_get_methodref_token_for_methodbuilder (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *method)
{
guint32 token;
ReflectionMethodBuilder rmb;
char *name;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
name = mono_string_to_utf8 (method->name);
reflection_methodbuilder_from_method_builder (&rmb, method);
/*
* A methodref signature can't contain an unmanaged calling convention.
* Since some flags are encoded as part of call_conv, we need to check against it.
*/
if ((rmb.call_conv & ~0x60) != MONO_CALL_DEFAULT && (rmb.call_conv & ~0x60) != MONO_CALL_VARARG)
rmb.call_conv = (rmb.call_conv & 0x60) | MONO_CALL_DEFAULT;
token = mono_image_get_memberref_token (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type),
name, method_builder_encode_signature (assembly, &rmb));
g_free (name);
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_varargs_method_token (MonoDynamicImage *assembly, guint32 original,
const gchar *name, guint32 sig)
{
MonoDynamicTable *table;
guint32 token;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = original;
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
encode_generic_method_definition_sig (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
SigBuffer buf;
int i;
guint32 nparams = mono_array_length (mb->generic_params);
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0xa);
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++) {
sigbuffer_add_value (&buf, MONO_TYPE_MVAR);
sigbuffer_add_value (&buf, i);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_methodspec_token_for_generic_method_definition (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0;
token = GPOINTER_TO_UINT (mono_g_hash_table_lookup (assembly->methodspec, mb));
if (token)
return token;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
mtoken = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = encode_generic_method_definition_sig (assembly, mb);
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
mono_g_hash_table_insert (assembly->methodspec, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_methodbuilder_token (MonoDynamicImage *assembly, MonoReflectionMethodBuilder *mb, gboolean create_methodspec)
{
guint32 token;
if (mb->generic_params && create_methodspec)
return mono_image_get_methodspec_token_for_generic_method_definition (assembly, mb);
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, mb));
if (token)
return token;
token = mono_image_get_methodref_token_for_methodbuilder (assembly, mb);
g_hash_table_insert (assembly->handleref, mb, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *mb)
{
guint32 token;
ReflectionMethodBuilder rmb;
char *name;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, mb));
if (token)
return token;
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
name = mono_string_to_utf8 (rmb.name);
token = mono_image_get_memberref_token (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type),
name, method_builder_encode_signature (assembly, &rmb));
g_free (name);
g_hash_table_insert (assembly->handleref, mb, GUINT_TO_POINTER(token));
return token;
}
#endif
static gboolean
is_field_on_inst (MonoClassField *field)
{
return (field->parent->generic_class && field->parent->generic_class->is_dynamic && ((MonoDynamicGenericClass*)field->parent->generic_class)->fields);
}
/*
* If FIELD is a field of a MonoDynamicGenericClass, return its non-inflated type.
*/
static MonoType*
get_field_on_inst_generic_type (MonoClassField *field)
{
MonoDynamicGenericClass *dgclass;
int field_index;
g_assert (is_field_on_inst (field));
dgclass = (MonoDynamicGenericClass*)field->parent->generic_class;
field_index = field - dgclass->fields;
g_assert (field_index >= 0 && field_index < dgclass->count_fields);
return dgclass->field_generic_types [field_index];
}
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoReflectionField *f)
{
MonoType *type;
guint32 token;
MonoClassField *field;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, f));
if (token)
return token;
g_assert (f->field->parent);
field = f->field;
if (field->parent->generic_class && field->parent->generic_class->container_class && field->parent->generic_class->container_class->fields) {
int index = field - field->parent->fields;
type = field->parent->generic_class->container_class->fields [index].type;
} else {
if (is_field_on_inst (f->field))
type = get_field_on_inst_generic_type (f->field);
else
type = f->field->type;
}
token = mono_image_get_memberref_token (assembly, &f->field->parent->byval_arg,
mono_field_get_name (f->field),
fieldref_encode_signature (assembly, field->parent->image, type));
g_hash_table_insert (assembly->handleref, f, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_field_on_inst_token (MonoDynamicImage *assembly, MonoReflectionFieldOnTypeBuilderInst *f)
{
guint32 token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoReflectionFieldBuilder *fb = f->fb;
MonoType *type;
char *name;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, f));
if (token)
return token;
type = mono_reflection_type_get_handle ((MonoReflectionType*)f->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
name = mono_string_to_utf8 (fb->name);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name,
field_encode_signature (assembly, fb));
g_free (name);
g_hash_table_insert (assembly->handleref, f, GUINT_TO_POINTER (token));
return token;
}
static guint32
mono_image_get_ctor_on_inst_token (MonoDynamicImage *assembly, MonoReflectionCtorOnTypeBuilderInst *c, gboolean create_methodspec)
{
guint32 sig, token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoReflectionCtorBuilder *cb = c->cb;
ReflectionMethodBuilder rmb;
MonoType *type;
char *name;
/* A ctor cannot be a generic method, so we can ignore create_methodspec */
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, c));
if (token)
return token;
type = mono_reflection_type_get_handle ((MonoReflectionType*)c->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
reflection_methodbuilder_from_ctor_builder (&rmb, cb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
g_hash_table_insert (assembly->handleref, c, GUINT_TO_POINTER (token));
return token;
}
static MonoMethod*
mono_reflection_method_on_tb_inst_get_handle (MonoReflectionMethodOnTypeBuilderInst *m)
{
MonoClass *klass;
MonoGenericContext tmp_context;
MonoType **type_argv;
MonoGenericInst *ginst;
MonoMethod *method, *inflated;
int count, i;
method = inflate_method (m->inst, (MonoObject*)m->mb);
klass = method->klass;
if (m->method_args == NULL)
return method;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_array_length (m->method_args);
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (m->method_args, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
return inflated;
}
static guint32
mono_image_get_method_on_inst_token (MonoDynamicImage *assembly, MonoReflectionMethodOnTypeBuilderInst *m, gboolean create_methodspec)
{
guint32 sig, token;
MonoClass *klass;
MonoGenericClass *gclass;
MonoReflectionMethodBuilder *mb = m->mb;
ReflectionMethodBuilder rmb;
MonoType *type;
char *name;
if (m->method_args) {
MonoMethod *inflated;
inflated = mono_reflection_method_on_tb_inst_get_handle (m);
if (create_methodspec)
token = mono_image_get_methodspec_token (assembly, inflated);
else
token = mono_image_get_inflated_method_token (assembly, inflated);
return token;
}
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, m));
if (token)
return token;
type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
klass = mono_class_from_mono_type (type);
gclass = type->data.generic_class;
g_assert (gclass->is_dynamic);
reflection_methodbuilder_from_method_builder (&rmb, mb);
name = mono_string_to_utf8 (rmb.name);
sig = method_builder_encode_signature (assembly, &rmb);
token = mono_image_get_memberref_token (assembly, &klass->byval_arg, name, sig);
g_free (name);
g_hash_table_insert (assembly->handleref, m, GUINT_TO_POINTER (token));
return token;
}
static guint32
encode_generic_method_sig (MonoDynamicImage *assembly, MonoGenericContext *context)
{
SigBuffer buf;
int i;
guint32 nparams = context->method_inst->type_argc;
guint32 idx;
if (!assembly->save)
return 0;
sigbuffer_init (&buf, 32);
/*
* FIXME: vararg, explicit_this, differenc call_conv values...
*/
sigbuffer_add_value (&buf, 0xa); /* FIXME FIXME FIXME */
sigbuffer_add_value (&buf, nparams);
for (i = 0; i < nparams; i++)
encode_type (assembly, context->method_inst->type_argv [i], &buf);
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
method_encode_methodspec (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoDynamicTable *table;
guint32 *values;
guint32 token, mtoken = 0, sig;
MonoMethodInflated *imethod;
MonoMethod *declaring;
table = &assembly->tables [MONO_TABLE_METHODSPEC];
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
declaring = imethod->declaring;
sig = method_encode_signature (assembly, mono_method_signature (declaring));
mtoken = mono_image_get_memberref_token (assembly, &method->klass->byval_arg, declaring->name, sig);
if (!mono_method_signature (declaring)->generic_param_count)
return mtoken;
switch (mono_metadata_token_table (mtoken)) {
case MONO_TABLE_MEMBERREF:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODREF;
break;
case MONO_TABLE_METHOD:
mtoken = (mono_metadata_token_index (mtoken) << MONO_METHODDEFORREF_BITS) | MONO_METHODDEFORREF_METHODDEF;
break;
default:
g_assert_not_reached ();
}
sig = encode_generic_method_sig (assembly, mono_method_get_context (method));
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_METHODSPEC_SIZE;
values [MONO_METHODSPEC_METHOD] = mtoken;
values [MONO_METHODSPEC_SIGNATURE] = sig;
}
token = MONO_TOKEN_METHOD_SPEC | table->next_idx;
table->next_idx ++;
return token;
}
static guint32
mono_image_get_methodspec_token (MonoDynamicImage *assembly, MonoMethod *method)
{
MonoMethodInflated *imethod;
guint32 token;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, method));
if (token)
return token;
g_assert (method->is_inflated);
imethod = (MonoMethodInflated *) method;
if (mono_method_signature (imethod->declaring)->generic_param_count) {
token = method_encode_methodspec (assembly, method);
} else {
guint32 sig = method_encode_signature (
assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &method->klass->byval_arg, method->name, sig);
}
g_hash_table_insert (assembly->handleref, method, GUINT_TO_POINTER(token));
return token;
}
static guint32
mono_image_get_inflated_method_token (MonoDynamicImage *assembly, MonoMethod *m)
{
MonoMethodInflated *imethod = (MonoMethodInflated *) m;
guint32 sig, token;
sig = method_encode_signature (assembly, mono_method_signature (imethod->declaring));
token = mono_image_get_memberref_token (
assembly, &m->klass->byval_arg, m->name, sig);
return token;
}
static guint32
create_generic_typespec (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *type;
guint32 *values;
guint32 token;
SigBuffer buf;
int count, i;
/*
* We're creating a TypeSpec for the TypeBuilder of a generic type declaration,
* ie. what we'd normally use as the generic type in a TypeSpec signature.
* Because of this, we must not insert it into the `typeref' hash table.
*/
type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->typespec, type));
if (token)
return token;
sigbuffer_init (&buf, 32);
g_assert (tb->generic_params);
klass = mono_class_from_mono_type (type);
if (tb->generic_container)
mono_reflection_create_generic_class (tb);
sigbuffer_add_value (&buf, MONO_TYPE_GENERICINST);
g_assert (klass->generic_container);
sigbuffer_add_value (&buf, klass->byval_arg.type);
sigbuffer_add_value (&buf, mono_image_typedef_or_ref_full (assembly, &klass->byval_arg, FALSE));
count = mono_array_length (tb->generic_params);
sigbuffer_add_value (&buf, count);
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam;
gparam = mono_array_get (tb->generic_params, MonoReflectionGenericParam *, i);
encode_type (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)gparam), &buf);
}
table = &assembly->tables [MONO_TABLE_TYPESPEC];
if (assembly->save) {
token = sigbuffer_add_to_blob_cached (assembly, &buf);
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_TYPESPEC_SIZE;
values [MONO_TYPESPEC_SIGNATURE] = token;
}
sigbuffer_free (&buf);
token = MONO_TYPEDEFORREF_TYPESPEC | (table->next_idx << MONO_TYPEDEFORREF_BITS);
g_hash_table_insert (assembly->typespec, type, GUINT_TO_POINTER(token));
table->next_idx ++;
return token;
}
/*
* Return a copy of TYPE, adding the custom modifiers in MODREQ and MODOPT.
*/
static MonoType*
add_custom_modifiers (MonoDynamicImage *assembly, MonoType *type, MonoArray *modreq, MonoArray *modopt)
{
int i, count, len, pos;
MonoType *t;
count = 0;
if (modreq)
count += mono_array_length (modreq);
if (modopt)
count += mono_array_length (modopt);
if (count == 0)
return mono_metadata_type_dup (NULL, type);
len = MONO_SIZEOF_TYPE + ((gint32)count) * sizeof (MonoCustomMod);
t = g_malloc (len);
memcpy (t, type, MONO_SIZEOF_TYPE);
t->num_mods = count;
pos = 0;
if (modreq) {
for (i = 0; i < mono_array_length (modreq); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modreq, i);
t->modifiers [pos].required = 1;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
if (modopt) {
for (i = 0; i < mono_array_length (modopt); ++i) {
MonoType *mod = mono_type_array_get_and_resolve (modopt, i);
t->modifiers [pos].required = 0;
t->modifiers [pos].token = mono_image_typedef_or_ref (assembly, mod);
pos ++;
}
}
return t;
}
static guint32
mono_image_get_generic_field_token (MonoDynamicImage *assembly, MonoReflectionFieldBuilder *fb)
{
MonoDynamicTable *table;
MonoClass *klass;
MonoType *custom = NULL;
guint32 *values;
guint32 token, pclass, parent, sig;
gchar *name;
token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, fb));
if (token)
return token;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (fb->typeb));
name = mono_string_to_utf8 (fb->name);
/* fb->type does not include the custom modifiers */
/* FIXME: We should do this in one place when a fieldbuilder is created */
if (fb->modreq || fb->modopt) {
custom = add_custom_modifiers (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type), fb->modreq, fb->modopt);
sig = fieldref_encode_signature (assembly, NULL, custom);
g_free (custom);
} else {
sig = fieldref_encode_signature (assembly, NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
}
parent = create_generic_typespec (assembly, (MonoReflectionTypeBuilder *) fb->typeb);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_TYPEDEFORREF_TYPESPEC);
pclass = MONO_MEMBERREF_PARENT_TYPESPEC;
parent >>= MONO_TYPEDEFORREF_BITS;
table = &assembly->tables [MONO_TABLE_MEMBERREF];
if (assembly->save) {
alloc_table (table, table->rows + 1);
values = table->values + table->next_idx * MONO_MEMBERREF_SIZE;
values [MONO_MEMBERREF_CLASS] = pclass | (parent << MONO_MEMBERREF_PARENT_BITS);
values [MONO_MEMBERREF_NAME] = string_heap_insert (&assembly->sheap, name);
values [MONO_MEMBERREF_SIGNATURE] = sig;
}
token = MONO_TOKEN_MEMBER_REF | table->next_idx;
table->next_idx ++;
g_hash_table_insert (assembly->handleref, fb, GUINT_TO_POINTER(token));
g_free (name);
return token;
}
static guint32
mono_reflection_encode_sighelper (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
SigBuffer buf;
guint32 nargs;
guint32 size;
guint32 i, idx;
if (!assembly->save)
return 0;
/* FIXME: this means SignatureHelper.SignatureHelpType.HELPER_METHOD */
g_assert (helper->type == 2);
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
size = 10 + (nargs * 10);
sigbuffer_init (&buf, 32);
/* Encode calling convention */
/* Change Any to Standard */
if ((helper->call_conv & 0x03) == 0x03)
helper->call_conv = 0x01;
/* explicit_this implies has_this */
if (helper->call_conv & 0x40)
helper->call_conv &= 0x20;
if (helper->call_conv == 0) { /* Unmanaged */
idx = helper->unmanaged_call_conv - 1;
} else {
/* Managed */
idx = helper->call_conv & 0x60; /* has_this + explicit_this */
if (helper->call_conv & 0x02) /* varargs */
idx += 0x05;
}
sigbuffer_add_byte (&buf, idx);
sigbuffer_add_value (&buf, nargs);
encode_reflection_type (assembly, helper->return_type, &buf);
for (i = 0; i < nargs; ++i) {
MonoArray *modreqs = NULL;
MonoArray *modopts = NULL;
MonoReflectionType *pt;
if (helper->modreqs && (i < mono_array_length (helper->modreqs)))
modreqs = mono_array_get (helper->modreqs, MonoArray*, i);
if (helper->modopts && (i < mono_array_length (helper->modopts)))
modopts = mono_array_get (helper->modopts, MonoArray*, i);
encode_custom_modifiers (assembly, modreqs, modopts, &buf);
pt = mono_array_get (helper->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, pt, &buf);
}
idx = sigbuffer_add_to_blob_cached (assembly, &buf);
sigbuffer_free (&buf);
return idx;
}
static guint32
mono_image_get_sighelper_token (MonoDynamicImage *assembly, MonoReflectionSigHelper *helper)
{
guint32 idx;
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_STANDALONESIG];
idx = table->next_idx ++;
table->rows ++;
alloc_table (table, table->rows);
values = table->values + idx * MONO_STAND_ALONE_SIGNATURE_SIZE;
values [MONO_STAND_ALONE_SIGNATURE] =
mono_reflection_encode_sighelper (assembly, helper);
return idx;
}
static int
reflection_cc_to_file (int call_conv) {
switch (call_conv & 0x3) {
case 0:
case 1: return MONO_CALL_DEFAULT;
case 2: return MONO_CALL_VARARG;
default:
g_assert_not_reached ();
}
return 0;
}
#endif /* !DISABLE_REFLECTION_EMIT */
typedef struct {
MonoType *parent;
MonoMethodSignature *sig;
char *name;
guint32 token;
} ArrayMethod;
#ifndef DISABLE_REFLECTION_EMIT
static guint32
mono_image_get_array_token (MonoDynamicImage *assembly, MonoReflectionArrayMethod *m)
{
guint32 nparams, i;
GList *tmp;
char *name;
MonoMethodSignature *sig;
ArrayMethod *am;
MonoType *mtype;
name = mono_string_to_utf8 (m->name);
nparams = mono_array_length (m->parameters);
sig = g_malloc0 (MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * nparams);
sig->hasthis = 1;
sig->sentinelpos = -1;
sig->call_convention = reflection_cc_to_file (m->call_conv);
sig->param_count = nparams;
sig->ret = m->ret ? mono_reflection_type_get_handle (m->ret): &mono_defaults.void_class->byval_arg;
mtype = mono_reflection_type_get_handle (m->parent);
for (i = 0; i < nparams; ++i)
sig->params [i] = mono_type_array_get_and_resolve (m->parameters, i);
for (tmp = assembly->array_methods; tmp; tmp = tmp->next) {
am = tmp->data;
if (strcmp (name, am->name) == 0 &&
mono_metadata_type_equal (am->parent, mtype) &&
mono_metadata_signature_equal (am->sig, sig)) {
g_free (name);
g_free (sig);
m->table_idx = am->token & 0xffffff;
return am->token;
}
}
am = g_new0 (ArrayMethod, 1);
am->name = name;
am->sig = sig;
am->parent = mtype;
am->token = mono_image_get_memberref_token (assembly, am->parent, name,
method_encode_signature (assembly, sig));
assembly->array_methods = g_list_prepend (assembly->array_methods, am);
m->table_idx = am->token & 0xffffff;
return am->token;
}
/*
* Insert into the metadata tables all the info about the TypeBuilder tb.
* Data in the tables is inserted in a predefined order, since some tables need to be sorted.
*/
static void
mono_image_get_type_info (MonoDomain *domain, MonoReflectionTypeBuilder *tb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint *values;
int i, is_object = 0, is_system = 0;
char *n;
table = &assembly->tables [MONO_TABLE_TYPEDEF];
values = table->values + tb->table_idx * MONO_TYPEDEF_SIZE;
values [MONO_TYPEDEF_FLAGS] = tb->attrs;
n = mono_string_to_utf8 (tb->name);
if (strcmp (n, "Object") == 0)
is_object++;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, n);
g_free (n);
n = mono_string_to_utf8 (tb->nspace);
if (strcmp (n, "System") == 0)
is_system++;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, n);
g_free (n);
if (tb->parent && !(is_system && is_object) &&
!(tb->attrs & TYPE_ATTRIBUTE_INTERFACE)) { /* interfaces don't have a parent */
values [MONO_TYPEDEF_EXTENDS] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
} else {
values [MONO_TYPEDEF_EXTENDS] = 0;
}
values [MONO_TYPEDEF_FIELD_LIST] = assembly->tables [MONO_TABLE_FIELD].next_idx;
values [MONO_TYPEDEF_METHOD_LIST] = assembly->tables [MONO_TABLE_METHOD].next_idx;
/*
* if we have explicitlayout or sequentiallayouts, output data in the
* ClassLayout table.
*/
if (((tb->attrs & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT) &&
((tb->class_size > 0) || (tb->packing_size > 0))) {
table = &assembly->tables [MONO_TABLE_CLASSLAYOUT];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_CLASS_LAYOUT_SIZE;
values [MONO_CLASS_LAYOUT_PARENT] = tb->table_idx;
values [MONO_CLASS_LAYOUT_CLASS_SIZE] = tb->class_size;
values [MONO_CLASS_LAYOUT_PACKING_SIZE] = tb->packing_size;
}
/* handle interfaces */
if (tb->interfaces) {
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
i = table->rows;
table->rows += mono_array_length (tb->interfaces);
alloc_table (table, table->rows);
values = table->values + (i + 1) * MONO_INTERFACEIMPL_SIZE;
for (i = 0; i < mono_array_length (tb->interfaces); ++i) {
MonoReflectionType* iface = (MonoReflectionType*) mono_array_get (tb->interfaces, gpointer, i);
values [MONO_INTERFACEIMPL_CLASS] = tb->table_idx;
values [MONO_INTERFACEIMPL_INTERFACE] = mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (iface));
values += MONO_INTERFACEIMPL_SIZE;
}
}
/* handle fields */
if (tb->fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += tb->num_fields;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_fields; ++i)
mono_image_get_field_info (
mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i), assembly);
}
/* handle constructors */
if (tb->ctors) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (tb->ctors);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->ctors); ++i)
mono_image_get_ctor_info (domain,
mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i), assembly);
}
/* handle methods */
if (tb->methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += tb->num_methods;
alloc_table (table, table->rows);
for (i = 0; i < tb->num_methods; ++i)
mono_image_get_method_info (
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i), assembly);
}
/* Do the same with properties etc.. */
if (tb->events && mono_array_length (tb->events)) {
table = &assembly->tables [MONO_TABLE_EVENT];
table->rows += mono_array_length (tb->events);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_EVENTMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_EVENT_MAP_SIZE;
values [MONO_EVENT_MAP_PARENT] = tb->table_idx;
values [MONO_EVENT_MAP_EVENTLIST] = assembly->tables [MONO_TABLE_EVENT].next_idx;
for (i = 0; i < mono_array_length (tb->events); ++i)
mono_image_get_event_info (
mono_array_get (tb->events, MonoReflectionEventBuilder*, i), assembly);
}
if (tb->properties && mono_array_length (tb->properties)) {
table = &assembly->tables [MONO_TABLE_PROPERTY];
table->rows += mono_array_length (tb->properties);
alloc_table (table, table->rows);
table = &assembly->tables [MONO_TABLE_PROPERTYMAP];
table->rows ++;
alloc_table (table, table->rows);
values = table->values + table->rows * MONO_PROPERTY_MAP_SIZE;
values [MONO_PROPERTY_MAP_PARENT] = tb->table_idx;
values [MONO_PROPERTY_MAP_PROPERTY_LIST] = assembly->tables [MONO_TABLE_PROPERTY].next_idx;
for (i = 0; i < mono_array_length (tb->properties); ++i)
mono_image_get_property_info (
mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i), assembly);
}
/* handle generic parameters */
if (tb->generic_params) {
table = &assembly->tables [MONO_TABLE_GENERICPARAM];
table->rows += mono_array_length (tb->generic_params);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (tb->generic_params); ++i) {
guint32 owner = MONO_TYPEORMETHOD_TYPE | (tb->table_idx << MONO_TYPEORMETHOD_BITS);
mono_image_get_generic_param_info (
mono_array_get (tb->generic_params, MonoReflectionGenericParam*, i), owner, assembly);
}
}
mono_image_add_decl_security (assembly,
mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx), tb->permissions);
if (tb->subtypes) {
MonoDynamicTable *ntable;
ntable = &assembly->tables [MONO_TABLE_NESTEDCLASS];
ntable->rows += mono_array_length (tb->subtypes);
alloc_table (ntable, ntable->rows);
values = ntable->values + ntable->next_idx * MONO_NESTED_CLASS_SIZE;
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
values [MONO_NESTED_CLASS_NESTED] = subtype->table_idx;
values [MONO_NESTED_CLASS_ENCLOSING] = tb->table_idx;
/*g_print ("nesting %s (%d) in %s (%d) (rows %d/%d)\n",
mono_string_to_utf8 (subtype->name), subtype->table_idx,
mono_string_to_utf8 (tb->name), tb->table_idx,
ntable->next_idx, ntable->rows);*/
values += MONO_NESTED_CLASS_SIZE;
ntable->next_idx++;
}
}
}
#endif
static void
collect_types (GPtrArray *types, MonoReflectionTypeBuilder *type)
{
int i;
g_ptr_array_add (types, type); /* FIXME: GC object added to unmanaged memory */
if (!type->subtypes)
return;
for (i = 0; i < mono_array_length (type->subtypes); ++i) {
MonoReflectionTypeBuilder *subtype = mono_array_get (type->subtypes, MonoReflectionTypeBuilder*, i);
collect_types (types, subtype);
}
}
static gint
compare_types_by_table_idx (MonoReflectionTypeBuilder **type1, MonoReflectionTypeBuilder **type2)
{
if ((*type1)->table_idx < (*type2)->table_idx)
return -1;
else
if ((*type1)->table_idx > (*type2)->table_idx)
return 1;
else
return 0;
}
static void
params_add_cattrs (MonoDynamicImage *assembly, MonoArray *pinfo) {
int i;
if (!pinfo)
return;
for (i = 0; i < mono_array_length (pinfo); ++i) {
MonoReflectionParamBuilder *pb;
pb = mono_array_get (pinfo, MonoReflectionParamBuilder *, i);
if (!pb)
continue;
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PARAMDEF, pb->cattrs);
}
}
static void
type_add_cattrs (MonoDynamicImage *assembly, MonoReflectionTypeBuilder *tb) {
int i;
mono_image_add_cattrs (assembly, tb->table_idx, MONO_CUSTOM_ATTR_TYPEDEF, tb->cattrs);
if (tb->fields) {
for (i = 0; i < tb->num_fields; ++i) {
MonoReflectionFieldBuilder* fb;
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (tb->events) {
for (i = 0; i < mono_array_length (tb->events); ++i) {
MonoReflectionEventBuilder* eb;
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
mono_image_add_cattrs (assembly, eb->table_idx, MONO_CUSTOM_ATTR_EVENT, eb->cattrs);
}
}
if (tb->properties) {
for (i = 0; i < mono_array_length (tb->properties); ++i) {
MonoReflectionPropertyBuilder* pb;
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
mono_image_add_cattrs (assembly, pb->table_idx, MONO_CUSTOM_ATTR_PROPERTY, pb->cattrs);
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder* cb;
cb = mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i);
mono_image_add_cattrs (assembly, cb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, cb->cattrs);
params_add_cattrs (assembly, cb->pinfo);
}
}
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder* mb;
mb = mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
type_add_cattrs (assembly, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i));
}
}
static void
module_add_cattrs (MonoDynamicImage *assembly, MonoReflectionModuleBuilder *moduleb)
{
int i;
mono_image_add_cattrs (assembly, moduleb->table_idx, MONO_CUSTOM_ATTR_MODULE, moduleb->cattrs);
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder* mb = mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_cattrs (assembly, mb->table_idx, MONO_CUSTOM_ATTR_METHODDEF, mb->cattrs);
params_add_cattrs (assembly, mb->pinfo);
}
}
if (moduleb->global_fields) {
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i);
mono_image_add_cattrs (assembly, fb->table_idx, MONO_CUSTOM_ATTR_FIELDDEF, fb->cattrs);
}
}
if (moduleb->types) {
for (i = 0; i < moduleb->num_types; ++i)
type_add_cattrs (assembly, mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i));
}
}
static void
mono_image_fill_file_table (MonoDomain *domain, MonoReflectionModule *module, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *dir, *path;
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, module->image->module_name);
if (module->image->dynamic) {
/* This depends on the fact that the main module is emitted last */
dir = mono_string_to_utf8 (((MonoReflectionModuleBuilder*)module)->assemblyb->dir);
path = g_strdup_printf ("%s%c%s", dir, G_DIR_SEPARATOR, module->image->module_name);
} else {
dir = NULL;
path = g_strdup (module->image->name);
}
mono_sha1_get_digest_from_file (path, hash);
g_free (dir);
g_free (path);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
table->next_idx ++;
}
static void
mono_image_fill_module_table (MonoDomain *domain, MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
table = &assembly->tables [MONO_TABLE_MODULE];
mb->table_idx = table->next_idx ++;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_NAME] = string_heap_insert_mstring (&assembly->sheap, mb->module.name);
i = mono_image_add_stream_data (&assembly->guid, mono_array_addr (mb->guid, char, 0), 16);
i /= 16;
++i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_GENERATION] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_MVID] = i;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENC] = 0;
table->values [mb->table_idx * MONO_MODULE_SIZE + MONO_MODULE_ENCBASE] = 0;
}
static guint32
mono_image_fill_export_table_from_class (MonoDomain *domain, MonoClass *klass,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 visib, res;
visib = klass->flags & TYPE_ATTRIBUTE_VISIBILITY_MASK;
if (! ((visib & TYPE_ATTRIBUTE_PUBLIC) || (visib & TYPE_ATTRIBUTE_NESTED_PUBLIC)))
return 0;
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = klass->flags;
values [MONO_EXP_TYPE_TYPEDEF] = klass->type_token;
if (klass->nested_in)
values [MONO_EXP_TYPE_IMPLEMENTATION] = (parent_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
else
values [MONO_EXP_TYPE_IMPLEMENTATION] = (module_index << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_FILE;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
res = table->next_idx;
table->next_idx ++;
/* Emit nested types */
if (klass->ext && klass->ext->nested_classes) {
GList *tmp;
for (tmp = klass->ext->nested_classes; tmp; tmp = tmp->next)
mono_image_fill_export_table_from_class (domain, tmp->data, module_index, table->next_idx - 1, assembly);
}
return res;
}
static void
mono_image_fill_export_table (MonoDomain *domain, MonoReflectionTypeBuilder *tb,
guint32 module_index, guint32 parent_index, MonoDynamicImage *assembly)
{
MonoClass *klass;
guint32 idx, i;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
klass->type_token = mono_metadata_make_token (MONO_TABLE_TYPEDEF, tb->table_idx);
idx = mono_image_fill_export_table_from_class (domain, klass, module_index,
parent_index, assembly);
/*
* Emit nested types
* We need to do this ourselves since klass->nested_classes is not set up.
*/
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i)
mono_image_fill_export_table (domain, mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i), module_index, idx, assembly);
}
}
static void
mono_image_fill_export_table_from_module (MonoDomain *domain, MonoReflectionModule *module,
guint32 module_index, MonoDynamicImage *assembly)
{
MonoImage *image = module->image;
MonoTableInfo *t;
guint32 i;
t = &image->tables [MONO_TABLE_TYPEDEF];
for (i = 0; i < t->rows; ++i) {
MonoClass *klass = mono_class_get (image, mono_metadata_make_token (MONO_TABLE_TYPEDEF, i + 1));
if (klass->flags & TYPE_ATTRIBUTE_PUBLIC)
mono_image_fill_export_table_from_class (domain, klass, module_index, 0, assembly);
}
}
static guint32
add_exported_type (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly, MonoClass *klass)
{
MonoDynamicTable *table;
guint32 *values;
guint32 scope, idx, res, impl;
gboolean forwarder = TRUE;
if (klass->nested_in) {
impl = add_exported_type (assemblyb, assembly, klass->nested_in);
forwarder = FALSE;
} else {
scope = resolution_scope_from_image (assembly, klass->image);
g_assert ((scope & MONO_RESOLTION_SCOPE_MASK) == MONO_RESOLTION_SCOPE_ASSEMBLYREF);
idx = scope >> MONO_RESOLTION_SCOPE_BITS;
impl = (idx << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_ASSEMBLYREF;
}
table = &assembly->tables [MONO_TABLE_EXPORTEDTYPE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_EXP_TYPE_SIZE;
values [MONO_EXP_TYPE_FLAGS] = forwarder ? TYPE_ATTRIBUTE_FORWARDER : 0;
values [MONO_EXP_TYPE_TYPEDEF] = 0;
values [MONO_EXP_TYPE_IMPLEMENTATION] = impl;
values [MONO_EXP_TYPE_NAME] = string_heap_insert (&assembly->sheap, klass->name);
values [MONO_EXP_TYPE_NAMESPACE] = string_heap_insert (&assembly->sheap, klass->name_space);
res = (table->next_idx << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE;
table->next_idx++;
return res;
}
static void
mono_image_fill_export_table_from_type_forwarders (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly)
{
MonoClass *klass;
int i;
if (!assemblyb->type_forwarders)
return;
for (i = 0; i < mono_array_length (assemblyb->type_forwarders); ++i) {
MonoReflectionType *t = mono_array_get (assemblyb->type_forwarders, MonoReflectionType *, i);
MonoType *type;
if (!t)
continue;
type = mono_reflection_type_get_handle (t);
g_assert (type);
klass = mono_class_from_mono_type (type);
add_exported_type (assemblyb, assembly, klass);
}
}
#define align_pointer(base,p)\
do {\
guint32 __diff = (unsigned char*)(p)-(unsigned char*)(base);\
if (__diff & 3)\
(p) += 4 - (__diff & 3);\
} while (0)
static int
compare_constants (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CONSTANT_PARENT] - b_values [MONO_CONSTANT_PARENT];
}
static int
compare_semantics (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int assoc = a_values [MONO_METHOD_SEMA_ASSOCIATION] - b_values [MONO_METHOD_SEMA_ASSOCIATION];
if (assoc)
return assoc;
return a_values [MONO_METHOD_SEMA_SEMANTICS] - b_values [MONO_METHOD_SEMA_SEMANTICS];
}
static int
compare_custom_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_CUSTOM_ATTR_PARENT] - b_values [MONO_CUSTOM_ATTR_PARENT];
}
static int
compare_field_marshal (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_FIELD_MARSHAL_PARENT] - b_values [MONO_FIELD_MARSHAL_PARENT];
}
static int
compare_nested (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_NESTED_CLASS_NESTED] - b_values [MONO_NESTED_CLASS_NESTED];
}
static int
compare_genericparam (const void *a, const void *b)
{
const GenericParamTableEntry **a_entry = (const GenericParamTableEntry **) a;
const GenericParamTableEntry **b_entry = (const GenericParamTableEntry **) b;
if ((*b_entry)->owner == (*a_entry)->owner)
return
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*a_entry)->gparam)) -
mono_type_get_generic_param_num (mono_reflection_type_get_handle ((MonoReflectionType*)(*b_entry)->gparam));
else
return (*a_entry)->owner - (*b_entry)->owner;
}
static int
compare_declsecurity_attrs (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
return a_values [MONO_DECL_SECURITY_PARENT] - b_values [MONO_DECL_SECURITY_PARENT];
}
static int
compare_interface_impl (const void *a, const void *b)
{
const guint32 *a_values = a;
const guint32 *b_values = b;
int klass = a_values [MONO_INTERFACEIMPL_CLASS] - b_values [MONO_INTERFACEIMPL_CLASS];
if (klass)
return klass;
return a_values [MONO_INTERFACEIMPL_INTERFACE] - b_values [MONO_INTERFACEIMPL_INTERFACE];
}
static void
pad_heap (MonoDynamicStream *sh)
{
if (sh->index & 3) {
int sz = 4 - (sh->index & 3);
memset (sh->data + sh->index, 0, sz);
sh->index += sz;
}
}
struct StreamDesc {
const char *name;
MonoDynamicStream *stream;
};
/*
* build_compressed_metadata() fills in the blob of data that represents the
* raw metadata as it will be saved in the PE file. The five streams are output
* and the metadata tables are comnpressed from the guint32 array representation,
* to the compressed on-disk format.
*/
static void
build_compressed_metadata (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
int i;
guint64 valid_mask = 0;
guint64 sorted_mask;
guint32 heapt_size = 0;
guint32 meta_size = 256; /* allow for header and other stuff */
guint32 table_offset;
guint32 ntables = 0;
guint64 *int64val;
guint32 *int32val;
guint16 *int16val;
MonoImage *meta;
unsigned char *p;
struct StreamDesc stream_desc [5];
qsort (assembly->gen_params->pdata, assembly->gen_params->len, sizeof (gpointer), compare_genericparam);
for (i = 0; i < assembly->gen_params->len; i++){
GenericParamTableEntry *entry = g_ptr_array_index (assembly->gen_params, i);
write_generic_param_entry (assembly, entry);
}
stream_desc [0].name = "#~";
stream_desc [0].stream = &assembly->tstream;
stream_desc [1].name = "#Strings";
stream_desc [1].stream = &assembly->sheap;
stream_desc [2].name = "#US";
stream_desc [2].stream = &assembly->us;
stream_desc [3].name = "#Blob";
stream_desc [3].stream = &assembly->blob;
stream_desc [4].name = "#GUID";
stream_desc [4].stream = &assembly->guid;
/* tables that are sorted */
sorted_mask = ((guint64)1 << MONO_TABLE_CONSTANT) | ((guint64)1 << MONO_TABLE_FIELDMARSHAL)
| ((guint64)1 << MONO_TABLE_METHODSEMANTICS) | ((guint64)1 << MONO_TABLE_CLASSLAYOUT)
| ((guint64)1 << MONO_TABLE_FIELDLAYOUT) | ((guint64)1 << MONO_TABLE_FIELDRVA)
| ((guint64)1 << MONO_TABLE_IMPLMAP) | ((guint64)1 << MONO_TABLE_NESTEDCLASS)
| ((guint64)1 << MONO_TABLE_METHODIMPL) | ((guint64)1 << MONO_TABLE_CUSTOMATTRIBUTE)
| ((guint64)1 << MONO_TABLE_DECLSECURITY) | ((guint64)1 << MONO_TABLE_GENERICPARAM)
| ((guint64)1 << MONO_TABLE_INTERFACEIMPL);
/* Compute table sizes */
/* the MonoImage has already been created in mono_image_basic_init() */
meta = &assembly->image;
/* sizes should be multiple of 4 */
pad_heap (&assembly->blob);
pad_heap (&assembly->guid);
pad_heap (&assembly->sheap);
pad_heap (&assembly->us);
/* Setup the info used by compute_sizes () */
meta->idx_blob_wide = assembly->blob.index >= 65536 ? 1 : 0;
meta->idx_guid_wide = assembly->guid.index >= 65536 ? 1 : 0;
meta->idx_string_wide = assembly->sheap.index >= 65536 ? 1 : 0;
meta_size += assembly->blob.index;
meta_size += assembly->guid.index;
meta_size += assembly->sheap.index;
meta_size += assembly->us.index;
for (i=0; i < MONO_TABLE_NUM; ++i)
meta->tables [i].rows = assembly->tables [i].rows;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
valid_mask |= (guint64)1 << i;
ntables ++;
meta->tables [i].row_size = mono_metadata_compute_size (
meta, i, &meta->tables [i].size_bitfield);
heapt_size += meta->tables [i].row_size * meta->tables [i].rows;
}
heapt_size += 24; /* #~ header size */
heapt_size += ntables * 4;
/* make multiple of 4 */
heapt_size += 3;
heapt_size &= ~3;
meta_size += heapt_size;
meta->raw_metadata = g_malloc0 (meta_size);
p = (unsigned char*)meta->raw_metadata;
/* the metadata signature */
*p++ = 'B'; *p++ = 'S'; *p++ = 'J'; *p++ = 'B';
/* version numbers and 4 bytes reserved */
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (meta->md_version_major);
*int16val = GUINT16_TO_LE (meta->md_version_minor);
p += 8;
/* version string */
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE ((strlen (meta->version) + 3) & (~3)); /* needs to be multiple of 4 */
p += 4;
memcpy (p, meta->version, strlen (meta->version));
p += GUINT32_FROM_LE (*int32val);
align_pointer (meta->raw_metadata, p);
int16val = (guint16*)p;
*int16val++ = GUINT16_TO_LE (0); /* flags must be 0 */
*int16val = GUINT16_TO_LE (5); /* number of streams */
p += 4;
/*
* write the stream info.
*/
table_offset = (p - (unsigned char*)meta->raw_metadata) + 5 * 8 + 40; /* room needed for stream headers */
table_offset += 3; table_offset &= ~3;
assembly->tstream.index = heapt_size;
for (i = 0; i < 5; ++i) {
int32val = (guint32*)p;
stream_desc [i].stream->offset = table_offset;
*int32val++ = GUINT32_TO_LE (table_offset);
*int32val = GUINT32_TO_LE (stream_desc [i].stream->index);
table_offset += GUINT32_FROM_LE (*int32val);
table_offset += 3; table_offset &= ~3;
p += 8;
strcpy ((char*)p, stream_desc [i].name);
p += strlen (stream_desc [i].name) + 1;
align_pointer (meta->raw_metadata, p);
}
/*
* now copy the data, the table stream header and contents goes first.
*/
g_assert ((p - (unsigned char*)meta->raw_metadata) < assembly->tstream.offset);
p = (guchar*)meta->raw_metadata + assembly->tstream.offset;
int32val = (guint32*)p;
*int32val = GUINT32_TO_LE (0); /* reserved */
p += 4;
if (mono_framework_version () > 1) {
*p++ = 2; /* version */
*p++ = 0;
} else {
*p++ = 1; /* version */
*p++ = 0;
}
if (meta->idx_string_wide)
*p |= 0x01;
if (meta->idx_guid_wide)
*p |= 0x02;
if (meta->idx_blob_wide)
*p |= 0x04;
++p;
*p++ = 1; /* reserved */
int64val = (guint64*)p;
*int64val++ = GUINT64_TO_LE (valid_mask);
*int64val++ = GUINT64_TO_LE (valid_mask & sorted_mask); /* bitvector of sorted tables */
p += 16;
int32val = (guint32*)p;
for (i = 0; i < MONO_TABLE_NUM; i++){
if (meta->tables [i].rows == 0)
continue;
*int32val++ = GUINT32_TO_LE (meta->tables [i].rows);
}
p = (unsigned char*)int32val;
/* sort the tables that still need sorting */
table = &assembly->tables [MONO_TABLE_CONSTANT];
if (table->rows)
qsort (table->values + MONO_CONSTANT_SIZE, table->rows, sizeof (guint32) * MONO_CONSTANT_SIZE, compare_constants);
table = &assembly->tables [MONO_TABLE_METHODSEMANTICS];
if (table->rows)
qsort (table->values + MONO_METHOD_SEMA_SIZE, table->rows, sizeof (guint32) * MONO_METHOD_SEMA_SIZE, compare_semantics);
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
if (table->rows)
qsort (table->values + MONO_CUSTOM_ATTR_SIZE, table->rows, sizeof (guint32) * MONO_CUSTOM_ATTR_SIZE, compare_custom_attrs);
table = &assembly->tables [MONO_TABLE_FIELDMARSHAL];
if (table->rows)
qsort (table->values + MONO_FIELD_MARSHAL_SIZE, table->rows, sizeof (guint32) * MONO_FIELD_MARSHAL_SIZE, compare_field_marshal);
table = &assembly->tables [MONO_TABLE_NESTEDCLASS];
if (table->rows)
qsort (table->values + MONO_NESTED_CLASS_SIZE, table->rows, sizeof (guint32) * MONO_NESTED_CLASS_SIZE, compare_nested);
/* Section 21.11 DeclSecurity in Partition II doesn't specify this to be sorted by MS implementation requires it */
table = &assembly->tables [MONO_TABLE_DECLSECURITY];
if (table->rows)
qsort (table->values + MONO_DECL_SECURITY_SIZE, table->rows, sizeof (guint32) * MONO_DECL_SECURITY_SIZE, compare_declsecurity_attrs);
table = &assembly->tables [MONO_TABLE_INTERFACEIMPL];
if (table->rows)
qsort (table->values + MONO_INTERFACEIMPL_SIZE, table->rows, sizeof (guint32) * MONO_INTERFACEIMPL_SIZE, compare_interface_impl);
/* compress the tables */
for (i = 0; i < MONO_TABLE_NUM; i++){
int row, col;
guint32 *values;
guint32 bitfield = meta->tables [i].size_bitfield;
if (!meta->tables [i].rows)
continue;
if (assembly->tables [i].columns != mono_metadata_table_count (bitfield))
g_error ("col count mismatch in %d: %d %d", i, assembly->tables [i].columns, mono_metadata_table_count (bitfield));
meta->tables [i].base = (char*)p;
for (row = 1; row <= meta->tables [i].rows; ++row) {
values = assembly->tables [i].values + row * assembly->tables [i].columns;
for (col = 0; col < assembly->tables [i].columns; ++col) {
switch (mono_metadata_table_size (bitfield, col)) {
case 1:
*p++ = values [col];
break;
case 2:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
break;
case 4:
*p++ = values [col] & 0xff;
*p++ = (values [col] >> 8) & 0xff;
*p++ = (values [col] >> 16) & 0xff;
*p++ = (values [col] >> 24) & 0xff;
break;
default:
g_assert_not_reached ();
}
}
}
g_assert ((p - (const unsigned char*)meta->tables [i].base) == (meta->tables [i].rows * meta->tables [i].row_size));
}
g_assert (assembly->guid.offset + assembly->guid.index < meta_size);
memcpy (meta->raw_metadata + assembly->sheap.offset, assembly->sheap.data, assembly->sheap.index);
memcpy (meta->raw_metadata + assembly->us.offset, assembly->us.data, assembly->us.index);
memcpy (meta->raw_metadata + assembly->blob.offset, assembly->blob.data, assembly->blob.index);
memcpy (meta->raw_metadata + assembly->guid.offset, assembly->guid.data, assembly->guid.index);
assembly->meta_size = assembly->guid.offset + assembly->guid.index;
}
/*
* Some tables in metadata need to be sorted according to some criteria, but
* when methods and fields are first created with reflection, they may be assigned a token
* that doesn't correspond to the final token they will get assigned after the sorting.
* ILGenerator.cs keeps a fixup table that maps the position of tokens in the IL code stream
* with the reflection objects that represent them. Once all the tables are set up, the
* reflection objects will contains the correct table index. fixup_method() will fixup the
* tokens for the method with ILGenerator @ilgen.
*/
static void
fixup_method (MonoReflectionILGen *ilgen, gpointer value, MonoDynamicImage *assembly)
{
guint32 code_idx = GPOINTER_TO_UINT (value);
MonoReflectionILTokenInfo *iltoken;
MonoReflectionFieldBuilder *field;
MonoReflectionCtorBuilder *ctor;
MonoReflectionMethodBuilder *method;
MonoReflectionTypeBuilder *tb;
MonoReflectionArrayMethod *am;
guint32 i, idx = 0;
unsigned char *target;
for (i = 0; i < ilgen->num_token_fixups; ++i) {
iltoken = (MonoReflectionILTokenInfo *)mono_array_addr_with_size (ilgen->token_fixups, sizeof (MonoReflectionILTokenInfo), i);
target = (guchar*)assembly->code.data + code_idx + iltoken->code_pos;
switch (target [3]) {
case MONO_TABLE_FIELD:
if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
field = (MonoReflectionFieldBuilder *)iltoken->member;
idx = field->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->field_to_table_idx, f));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHOD:
if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
method = (MonoReflectionMethodBuilder *)iltoken->member;
idx = method->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
ctor = (MonoReflectionCtorBuilder *)iltoken->member;
idx = ctor->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_TYPEDEF:
if (strcmp (iltoken->member->vtable->klass->name, "TypeBuilder"))
g_assert_not_reached ();
tb = (MonoReflectionTypeBuilder *)iltoken->member;
idx = tb->table_idx;
break;
case MONO_TABLE_MEMBERREF:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoArrayMethod")) {
am = (MonoReflectionArrayMethod*)iltoken->member;
idx = am->table_idx;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoCMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod") ||
!strcmp (iltoken->member->vtable->klass->name, "MonoGenericCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (m->klass->generic_class || m->klass->generic_container);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MonoField")) {
MonoClassField *f = ((MonoReflectionField*)iltoken->member)->field;
g_assert (is_field_on_inst (f));
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder") ||
!strcmp (iltoken->member->vtable->klass->name, "ConstructorBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "FieldOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "ConstructorOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
case MONO_TABLE_METHODSPEC:
if (!strcmp (iltoken->member->vtable->klass->name, "MonoGenericMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)iltoken->member)->method;
g_assert (mono_method_signature (m)->generic_param_count);
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodBuilder")) {
continue;
} else if (!strcmp (iltoken->member->vtable->klass->name, "MethodOnTypeBuilderInst")) {
continue;
} else {
g_assert_not_reached ();
}
break;
default:
g_error ("got unexpected table 0x%02x in fixup", target [3]);
}
target [0] = idx & 0xff;
target [1] = (idx >> 8) & 0xff;
target [2] = (idx >> 16) & 0xff;
}
}
/*
* fixup_cattrs:
*
* The CUSTOM_ATTRIBUTE table might contain METHODDEF tokens whose final
* value is not known when the table is emitted.
*/
static void
fixup_cattrs (MonoDynamicImage *assembly)
{
MonoDynamicTable *table;
guint32 *values;
guint32 type, i, idx, token;
MonoObject *ctor;
table = &assembly->tables [MONO_TABLE_CUSTOMATTRIBUTE];
for (i = 0; i < table->rows; ++i) {
values = table->values + ((i + 1) * MONO_CUSTOM_ATTR_SIZE);
type = values [MONO_CUSTOM_ATTR_TYPE];
if ((type & MONO_CUSTOM_ATTR_TYPE_MASK) == MONO_CUSTOM_ATTR_TYPE_METHODDEF) {
idx = type >> MONO_CUSTOM_ATTR_TYPE_BITS;
token = mono_metadata_make_token (MONO_TABLE_METHOD, idx);
ctor = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
g_assert (ctor);
if (!strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
MonoMethod *m = ((MonoReflectionMethod*)ctor)->method;
idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, m));
values [MONO_CUSTOM_ATTR_TYPE] = (idx << MONO_CUSTOM_ATTR_TYPE_BITS) | MONO_CUSTOM_ATTR_TYPE_METHODDEF;
}
}
}
}
static void
assembly_add_resource_manifest (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc, guint32 implementation)
{
MonoDynamicTable *table;
guint32 *values;
table = &assembly->tables [MONO_TABLE_MANIFESTRESOURCE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_MANIFEST_SIZE;
values [MONO_MANIFEST_OFFSET] = rsrc->offset;
values [MONO_MANIFEST_FLAGS] = rsrc->attrs;
values [MONO_MANIFEST_NAME] = string_heap_insert_mstring (&assembly->sheap, rsrc->name);
values [MONO_MANIFEST_IMPLEMENTATION] = implementation;
table->next_idx++;
}
static void
assembly_add_resource (MonoReflectionModuleBuilder *mb, MonoDynamicImage *assembly, MonoReflectionResource *rsrc)
{
MonoDynamicTable *table;
guint32 *values;
char blob_size [6];
guchar hash [20];
char *b = blob_size;
char *name, *sname;
guint32 idx, offset;
if (rsrc->filename) {
name = mono_string_to_utf8 (rsrc->filename);
sname = g_path_get_basename (name);
table = &assembly->tables [MONO_TABLE_FILE];
table->rows++;
alloc_table (table, table->rows);
values = table->values + table->next_idx * MONO_FILE_SIZE;
values [MONO_FILE_FLAGS] = FILE_CONTAINS_NO_METADATA;
values [MONO_FILE_NAME] = string_heap_insert (&assembly->sheap, sname);
g_free (sname);
mono_sha1_get_digest_from_file (name, hash);
mono_metadata_encode_value (20, b, &b);
values [MONO_FILE_HASH_VALUE] = mono_image_add_stream_data (&assembly->blob, blob_size, b-blob_size);
mono_image_add_stream_data (&assembly->blob, (char*)hash, 20);
g_free (name);
idx = table->next_idx++;
rsrc->offset = 0;
idx = MONO_IMPLEMENTATION_FILE | (idx << MONO_IMPLEMENTATION_BITS);
} else {
char sizebuf [4];
char *data;
guint len;
if (rsrc->data) {
data = mono_array_addr (rsrc->data, char, 0);
len = mono_array_length (rsrc->data);
} else {
data = NULL;
len = 0;
}
offset = len;
sizebuf [0] = offset; sizebuf [1] = offset >> 8;
sizebuf [2] = offset >> 16; sizebuf [3] = offset >> 24;
rsrc->offset = mono_image_add_stream_data (&assembly->resources, sizebuf, 4);
mono_image_add_stream_data (&assembly->resources, data, len);
if (!mb->is_main)
/*
* The entry should be emitted into the MANIFESTRESOURCE table of
* the main module, but that needs to reference the FILE table
* which isn't emitted yet.
*/
return;
else
idx = 0;
}
assembly_add_resource_manifest (mb, assembly, rsrc, idx);
}
static void
set_version_from_string (MonoString *version, guint32 *values)
{
gchar *ver, *p, *str;
guint32 i;
values [MONO_ASSEMBLY_MAJOR_VERSION] = 0;
values [MONO_ASSEMBLY_MINOR_VERSION] = 0;
values [MONO_ASSEMBLY_REV_NUMBER] = 0;
values [MONO_ASSEMBLY_BUILD_NUMBER] = 0;
if (!version)
return;
ver = str = mono_string_to_utf8 (version);
for (i = 0; i < 4; ++i) {
values [MONO_ASSEMBLY_MAJOR_VERSION + i] = strtol (ver, &p, 10);
switch (*p) {
case '.':
p++;
break;
case '*':
/* handle Revision and Build */
p++;
break;
}
ver = p;
}
g_free (str);
}
static guint32
load_public_key (MonoArray *pkey, MonoDynamicImage *assembly) {
gsize len;
guint32 token = 0;
char blob_size [6];
char *b = blob_size;
if (!pkey)
return token;
len = mono_array_length (pkey);
mono_metadata_encode_value (len, b, &b);
token = mono_image_add_stream_data (&assembly->blob, blob_size, b - blob_size);
mono_image_add_stream_data (&assembly->blob, mono_array_addr (pkey, char, 0), len);
assembly->public_key = g_malloc (len);
memcpy (assembly->public_key, mono_array_addr (pkey, char, 0), len);
assembly->public_key_len = len;
/* Special case: check for ECMA key (16 bytes) */
if ((len == MONO_ECMA_KEY_LENGTH) && mono_is_ecma_key (mono_array_addr (pkey, char, 0), len)) {
/* In this case we must reserve 128 bytes (1024 bits) for the signature */
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH;
} else if (len >= MONO_PUBLIC_KEY_HEADER_LENGTH + MONO_MINIMUM_PUBLIC_KEY_LENGTH) {
/* minimum key size (in 2.0) is 384 bits */
assembly->strong_name_size = len - MONO_PUBLIC_KEY_HEADER_LENGTH;
} else {
/* FIXME - verifier */
g_warning ("Invalid public key length: %d bits (total: %d)", (int)MONO_PUBLIC_KEY_BIT_SIZE (len), (int)len);
assembly->strong_name_size = MONO_DEFAULT_PUBLIC_KEY_LENGTH; /* to be safe */
}
assembly->strong_name = g_malloc0 (assembly->strong_name_size);
return token;
}
static void
mono_image_emit_manifest (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
guint32 *values;
int i;
guint32 module_index;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
/* Emit ASSEMBLY table */
table = &assembly->tables [MONO_TABLE_ASSEMBLY];
alloc_table (table, 1);
values = table->values + MONO_ASSEMBLY_SIZE;
values [MONO_ASSEMBLY_HASH_ALG] = assemblyb->algid? assemblyb->algid: ASSEMBLY_HASH_SHA1;
values [MONO_ASSEMBLY_NAME] = string_heap_insert_mstring (&assembly->sheap, assemblyb->name);
if (assemblyb->culture) {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert_mstring (&assembly->sheap, assemblyb->culture);
} else {
values [MONO_ASSEMBLY_CULTURE] = string_heap_insert (&assembly->sheap, "");
}
values [MONO_ASSEMBLY_PUBLIC_KEY] = load_public_key (assemblyb->public_key, assembly);
values [MONO_ASSEMBLY_FLAGS] = assemblyb->flags;
set_version_from_string (assemblyb->version, values);
/* Emit FILE + EXPORTED_TYPE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
if (file_module != moduleb) {
mono_image_fill_file_table (domain, (MonoReflectionModule*)file_module, assembly);
module_index ++;
if (file_module->types) {
for (j = 0; j < file_module->num_types; ++j) {
MonoReflectionTypeBuilder *tb = mono_array_get (file_module->types, MonoReflectionTypeBuilder*, j);
mono_image_fill_export_table (domain, tb, module_index, 0, assembly);
}
}
}
}
if (assemblyb->loaded_modules) {
for (i = 0; i < mono_array_length (assemblyb->loaded_modules); ++i) {
MonoReflectionModule *file_module =
mono_array_get (assemblyb->loaded_modules, MonoReflectionModule*, i);
mono_image_fill_file_table (domain, file_module, assembly);
module_index ++;
mono_image_fill_export_table_from_module (domain, file_module, module_index, assembly);
}
}
if (assemblyb->type_forwarders)
mono_image_fill_export_table_from_type_forwarders (assemblyb, assembly);
/* Emit MANIFESTRESOURCE table */
module_index = 0;
for (i = 0; i < mono_array_length (assemblyb->modules); ++i) {
int j;
MonoReflectionModuleBuilder *file_module =
mono_array_get (assemblyb->modules, MonoReflectionModuleBuilder*, i);
/* The table for the main module is emitted later */
if (file_module != moduleb) {
module_index ++;
if (file_module->resources) {
int len = mono_array_length (file_module->resources);
for (j = 0; j < len; ++j) {
MonoReflectionResource* res = (MonoReflectionResource*)mono_array_addr (file_module->resources, MonoReflectionResource, j);
assembly_add_resource_manifest (file_module, assembly, res, MONO_IMPLEMENTATION_FILE | (module_index << MONO_IMPLEMENTATION_BITS));
}
}
}
}
}
#ifndef DISABLE_REFLECTION_EMIT_SAVE
/*
* mono_image_build_metadata() will fill the info in all the needed metadata tables
* for the modulebuilder @moduleb.
* At the end of the process, method and field tokens are fixed up and the
* on-disk compressed metadata representation is created.
*/
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicTable *table;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDomain *domain;
GPtrArray *types;
guint32 *values;
int i, j;
assemblyb = moduleb->assemblyb;
assembly = moduleb->dynamic_image;
domain = mono_object_domain (assemblyb);
if (assembly->text_rva)
return;
assembly->text_rva = START_TEXT_RVA;
if (moduleb->is_main) {
mono_image_emit_manifest (moduleb);
}
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows = 1; /* .<Module> */
table->next_idx++;
alloc_table (table, table->rows);
/*
* Set the first entry.
*/
values = table->values + table->columns;
values [MONO_TYPEDEF_FLAGS] = 0;
values [MONO_TYPEDEF_NAME] = string_heap_insert (&assembly->sheap, "<Module>") ;
values [MONO_TYPEDEF_NAMESPACE] = string_heap_insert (&assembly->sheap, "") ;
values [MONO_TYPEDEF_EXTENDS] = 0;
values [MONO_TYPEDEF_FIELD_LIST] = 1;
values [MONO_TYPEDEF_METHOD_LIST] = 1;
/*
* handle global methods
* FIXME: test what to do when global methods are defined in multiple modules.
*/
if (moduleb->global_methods) {
table = &assembly->tables [MONO_TABLE_METHOD];
table->rows += mono_array_length (moduleb->global_methods);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i)
mono_image_get_method_info (
mono_array_get (moduleb->global_methods, MonoReflectionMethodBuilder*, i), assembly);
}
if (moduleb->global_fields) {
table = &assembly->tables [MONO_TABLE_FIELD];
table->rows += mono_array_length (moduleb->global_fields);
alloc_table (table, table->rows);
for (i = 0; i < mono_array_length (moduleb->global_fields); ++i)
mono_image_get_field_info (
mono_array_get (moduleb->global_fields, MonoReflectionFieldBuilder*, i), assembly);
}
table = &assembly->tables [MONO_TABLE_MODULE];
alloc_table (table, 1);
mono_image_fill_module_table (domain, moduleb, assembly);
/* Collect all types into a list sorted by their table_idx */
types = g_ptr_array_new ();
if (moduleb->types)
for (i = 0; i < moduleb->num_types; ++i) {
MonoReflectionTypeBuilder *type = mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i);
collect_types (types, type);
}
g_ptr_array_sort (types, (GCompareFunc)compare_types_by_table_idx);
table = &assembly->tables [MONO_TABLE_TYPEDEF];
table->rows += types->len;
alloc_table (table, table->rows);
/*
* Emit type names + namespaces at one place inside the string heap,
* so load_class_names () needs to touch fewer pages.
*/
for (i = 0; i < types->len; ++i) {
MonoReflectionTypeBuilder *tb = g_ptr_array_index (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->nspace);
}
for (i = 0; i < types->len; ++i) {
MonoReflectionTypeBuilder *tb = g_ptr_array_index (types, i);
string_heap_insert_mstring (&assembly->sheap, tb->name);
}
for (i = 0; i < types->len; ++i) {
MonoReflectionTypeBuilder *type = g_ptr_array_index (types, i);
mono_image_get_type_info (domain, type, assembly);
}
/*
* table->rows is already set above and in mono_image_fill_module_table.
*/
/* add all the custom attributes at the end, once all the indexes are stable */
mono_image_add_cattrs (assembly, 1, MONO_CUSTOM_ATTR_ASSEMBLY, assemblyb->cattrs);
/* CAS assembly permissions */
if (assemblyb->permissions_minimum)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_minimum);
if (assemblyb->permissions_optional)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_optional);
if (assemblyb->permissions_refused)
mono_image_add_decl_security (assembly, mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1), assemblyb->permissions_refused);
module_add_cattrs (assembly, moduleb);
/* fixup tokens */
mono_g_hash_table_foreach (assembly->token_fixups, (GHFunc)fixup_method, assembly);
/* Create the MethodImpl table. We do this after emitting all methods so we already know
* the final tokens and don't need another fixup pass. */
if (moduleb->global_methods) {
for (i = 0; i < mono_array_length (moduleb->global_methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (
moduleb->global_methods, MonoReflectionMethodBuilder*, i);
mono_image_add_methodimpl (assembly, mb);
}
}
for (i = 0; i < types->len; ++i) {
MonoReflectionTypeBuilder *type = g_ptr_array_index (types, i);
if (type->methods) {
for (j = 0; j < type->num_methods; ++j) {
MonoReflectionMethodBuilder *mb = mono_array_get (
type->methods, MonoReflectionMethodBuilder*, j);
mono_image_add_methodimpl (assembly, mb);
}
}
}
g_ptr_array_free (types, TRUE);
fixup_cattrs (assembly);
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_build_metadata (MonoReflectionModuleBuilder *moduleb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit_save, so saving of dynamic assemblies is not supported.");
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
typedef struct {
guint32 import_lookup_table;
guint32 timestamp;
guint32 forwarder;
guint32 name_rva;
guint32 import_address_table_rva;
} MonoIDT;
typedef struct {
guint32 name_rva;
guint32 flags;
} MonoILT;
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_insert_string:
* @module: module builder object
* @str: a string
*
* Insert @str into the user string stream of @module.
*/
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
MonoDynamicImage *assembly;
guint32 idx;
char buf [16];
char *b = buf;
MONO_ARCH_SAVE_REGS;
if (!module->dynamic_image)
mono_image_module_basic_init (module);
assembly = module->dynamic_image;
if (assembly->save) {
mono_metadata_encode_value (1 | (str->length * 2), b, &b);
idx = mono_image_add_stream_data (&assembly->us, buf, b-buf);
#if G_BYTE_ORDER != G_LITTLE_ENDIAN
{
char *swapped = g_malloc (2 * mono_string_length (str));
const char *p = (const char*)mono_string_chars (str);
swap_with_size (swapped, p, 2, mono_string_length (str));
mono_image_add_stream_data (&assembly->us, swapped, str->length * 2);
g_free (swapped);
}
#else
mono_image_add_stream_data (&assembly->us, (const char*)mono_string_chars (str), str->length * 2);
#endif
mono_image_add_stream_data (&assembly->us, "", 1);
} else {
idx = assembly->us.index ++;
}
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (MONO_TOKEN_STRING | idx), str);
return MONO_TOKEN_STRING | idx;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MonoMethod") == 0) {
MonoMethod *method = ((MonoReflectionMethod *)obj)->method;
MonoMethodSignature *sig, *old;
guint32 sig_token, parent;
int nargs, i;
g_assert (opt_param_types && (mono_method_signature (method)->sentinelpos >= 0));
nargs = mono_array_length (opt_param_types);
old = mono_method_signature (method);
sig = mono_metadata_signature_alloc ( &assembly->image, old->param_count + nargs);
sig->hasthis = old->hasthis;
sig->explicit_this = old->explicit_this;
sig->call_convention = old->call_convention;
sig->generic_param_count = old->generic_param_count;
sig->param_count = old->param_count + nargs;
sig->sentinelpos = old->param_count;
sig->ret = old->ret;
for (i = 0; i < old->param_count; i++)
sig->params [i] = old->params [i];
for (i = 0; i < nargs; i++) {
MonoReflectionType *rt = mono_array_get (opt_param_types, MonoReflectionType *, i);
sig->params [old->param_count + i] = mono_reflection_type_get_handle (rt);
}
parent = mono_image_typedef_or_ref (assembly, &method->klass->byval_arg);
g_assert ((parent & MONO_TYPEDEFORREF_MASK) == MONO_MEMBERREF_PARENT_TYPEREF);
parent >>= MONO_TYPEDEFORREF_BITS;
parent <<= MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_TYPEREF;
sig_token = method_encode_signature (assembly, sig);
token = mono_image_get_varargs_method_token (assembly, parent, method->name, sig_token);
} else if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
ReflectionMethodBuilder rmb;
guint32 parent, sig;
char *name;
reflection_methodbuilder_from_method_builder (&rmb, mb);
rmb.opt_types = opt_param_types;
sig = method_builder_encode_signature (assembly, &rmb);
parent = mono_image_create_token (assembly, obj, TRUE, TRUE);
g_assert (mono_metadata_token_table (parent) == MONO_TABLE_METHOD);
parent = mono_metadata_token_index (parent) << MONO_MEMBERREF_PARENT_BITS;
parent |= MONO_MEMBERREF_PARENT_METHODDEF;
name = mono_string_to_utf8 (rmb.name);
token = mono_image_get_varargs_method_token (
assembly, parent, name, sig);
g_free (name);
} else {
g_error ("requested method token for %s\n", klass->name);
}
return token;
}
/*
* mono_image_create_token:
* @assembly: a dynamic assembly
* @obj:
* @register_token: Whenever to register the token in the assembly->tokens hash.
*
* Get a token to insert in the IL code stream for the given MemberInfo.
* The metadata emission routines need to pass FALSE as REGISTER_TOKEN, since by that time,
* the table_idx-es were recomputed, so registering the token would overwrite an existing
* entry.
*/
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_methodspec, gboolean register_token)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
/* Check for user defined reflection objects */
/* TypeDelegator is the only corlib type which doesn't look like a MonoReflectionType */
if (klass->image != mono_defaults.corlib || (strcmp (klass->name, "TypeDelegator") == 0))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported")); \
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params && !mb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_methodbuilder_token (assembly, mb, create_methodspec);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
if (tb->module->dynamic_image == assembly && !tb->generic_params)
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
else
token = mono_image_get_ctorbuilder_token (assembly, mb);
/*g_print ("got token 0x%08x for %s\n", token, mono_string_to_utf8 (mb->name));*/
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)fb->typeb;
if (tb->generic_params) {
token = mono_image_get_generic_field_token (assembly, fb);
} else {
token = fb->table_idx | MONO_TOKEN_FIELD_DEF;
}
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
MonoClass *mc = mono_class_from_mono_type (type);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref_full (assembly, type, mc->generic_container == NULL));
} else if (strcmp (klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
if (create_methodspec)
token = mono_image_get_methodspec_token (assembly, m->method);
else
token = mono_image_get_inflated_method_token (assembly, m->method);
} else if ((m->method->klass->image == &assembly->image) &&
!m->method->klass->generic_class) {
static guint32 method_table_idx = 0xffffff;
if (m->method->klass->wastypebuilder) {
/* we use the same token as the one that was assigned
* to the Methodbuilder.
* FIXME: do the equivalent for Fields.
*/
token = m->method->token;
} else {
/*
* Each token should have a unique index, but the indexes are
* assigned by managed code, so we don't know about them. An
* easy solution is to count backwards...
*/
method_table_idx --;
token = MONO_TOKEN_METHOD_DEF | method_table_idx;
}
} else {
token = mono_image_get_methodref_token (assembly, m->method, create_methodspec);
}
/*g_print ("got token 0x%08x for %s\n", token, m->method->name);*/
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField *)obj;
if ((f->field->parent->image == &assembly->image) && !is_field_on_inst (f->field)) {
static guint32 field_table_idx = 0xffffff;
field_table_idx --;
token = MONO_TOKEN_FIELD_DEF | field_table_idx;
} else {
token = mono_image_get_fieldref_token (assembly, f);
}
/*g_print ("got token 0x%08x for %s\n", token, f->field->name);*/
} else if (strcmp (klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod *)obj;
token = mono_image_get_array_token (assembly, m);
} else if (strcmp (klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *s = (MonoReflectionSigHelper*)obj;
token = MONO_TOKEN_SIGNATURE | mono_image_get_sighelper_token (assembly, s);
} else if (strcmp (klass->name, "EnumBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, type));
} else if (strcmp (klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
token = mono_image_get_field_on_inst_token (assembly, f);
} else if (strcmp (klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
token = mono_image_get_ctor_on_inst_token (assembly, c, create_methodspec);
} else if (strcmp (klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
token = mono_image_get_method_on_inst_token (assembly, m, create_methodspec);
} else if (is_sre_array (klass) || is_sre_byref (klass) || is_sre_pointer (klass)) {
MonoReflectionType *type = (MonoReflectionType *)obj;
token = mono_metadata_token_from_dor (
mono_image_typedef_or_ref (assembly, mono_reflection_type_get_handle (type)));
} else {
g_error ("requested token for %s\n", klass->name);
}
if (register_token)
mono_image_register_token (assembly, token, obj);
return token;
}
/*
* mono_image_register_token:
*
* Register the TOKEN->OBJ mapping in the mapping table in ASSEMBLY. This is required for
* the Module.ResolveXXXToken () methods to work.
*/
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
MonoObject *prev = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
if (prev) {
/* There could be multiple MethodInfo objects with the same token */
//g_assert (prev == obj);
} else {
mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), obj);
}
}
static MonoDynamicImage*
create_dynamic_mono_image (MonoDynamicAssembly *assembly, char *assembly_name, char *module_name)
{
static const guchar entrycode [16] = {0xff, 0x25, 0};
MonoDynamicImage *image;
int i;
const char *version;
if (!strcmp (mono_get_runtime_info ()->framework_version, "2.1"))
version = "v2.0.50727"; /* HACK: SL 2 enforces the .net 2 metadata version */
else
version = mono_get_runtime_info ()->runtime_version;
#if HAVE_BOEHM_GC
image = GC_MALLOC (sizeof (MonoDynamicImage));
#else
image = g_new0 (MonoDynamicImage, 1);
#endif
mono_profiler_module_event (&image->image, MONO_PROFILE_START_LOAD);
/*g_print ("created image %p\n", image);*/
/* keep in sync with image.c */
image->image.name = assembly_name;
image->image.assembly_name = image->image.name; /* they may be different */
image->image.module_name = module_name;
image->image.version = g_strdup (version);
image->image.md_version_major = 1;
image->image.md_version_minor = 1;
image->image.dynamic = TRUE;
image->image.references = g_new0 (MonoAssembly*, 1);
image->image.references [0] = NULL;
mono_image_init (&image->image);
image->token_fixups = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->method_to_table_idx = g_hash_table_new (NULL, NULL);
image->field_to_table_idx = g_hash_table_new (NULL, NULL);
image->method_aux_hash = g_hash_table_new (NULL, NULL);
image->handleref = g_hash_table_new (NULL, NULL);
image->tokens = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->generic_def_objects = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
image->methodspec = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC);
image->typespec = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->typeref = g_hash_table_new ((GHashFunc)mono_metadata_type_hash, (GCompareFunc)mono_metadata_type_equal);
image->blob_cache = g_hash_table_new ((GHashFunc)mono_blob_entry_hash, (GCompareFunc)mono_blob_entry_equal);
image->gen_params = g_ptr_array_new ();
/*g_print ("string heap create for image %p (%s)\n", image, module_name);*/
string_heap_init (&image->sheap);
mono_image_add_stream_data (&image->us, "", 1);
add_to_blob_cached (image, (char*) "", 1, NULL, 0);
/* import tables... */
mono_image_add_stream_data (&image->code, (char*)entrycode, sizeof (entrycode));
image->iat_offset = mono_image_add_stream_zero (&image->code, 8); /* two IAT entries */
image->idt_offset = mono_image_add_stream_zero (&image->code, 2 * sizeof (MonoIDT)); /* two IDT entries */
image->imp_names_offset = mono_image_add_stream_zero (&image->code, 2); /* flags for name entry */
mono_image_add_stream_data (&image->code, "_CorExeMain", 12);
mono_image_add_stream_data (&image->code, "mscoree.dll", 12);
image->ilt_offset = mono_image_add_stream_zero (&image->code, 8); /* two ILT entries */
stream_data_align (&image->code);
image->cli_header_offset = mono_image_add_stream_zero (&image->code, sizeof (MonoCLIHeader));
for (i=0; i < MONO_TABLE_NUM; ++i) {
image->tables [i].next_idx = 1;
image->tables [i].columns = table_sizes [i];
}
image->image.assembly = (MonoAssembly*)assembly;
image->run = assembly->run;
image->save = assembly->save;
image->pe_kind = 0x1; /* ILOnly */
image->machine = 0x14c; /* I386 */
mono_profiler_module_loaded (&image->image, MONO_PROFILE_OK);
return image;
}
#endif
static void
free_blob_cache_entry (gpointer key, gpointer val, gpointer user_data)
{
g_free (key);
}
void
mono_dynamic_image_free (MonoDynamicImage *image)
{
MonoDynamicImage *di = image;
GList *list;
int i;
if (di->methodspec)
mono_g_hash_table_destroy (di->methodspec);
if (di->typespec)
g_hash_table_destroy (di->typespec);
if (di->typeref)
g_hash_table_destroy (di->typeref);
if (di->handleref)
g_hash_table_destroy (di->handleref);
if (di->tokens)
mono_g_hash_table_destroy (di->tokens);
if (di->generic_def_objects)
mono_g_hash_table_destroy (di->generic_def_objects);
if (di->blob_cache) {
g_hash_table_foreach (di->blob_cache, free_blob_cache_entry, NULL);
g_hash_table_destroy (di->blob_cache);
}
if (di->standalonesig_cache)
g_hash_table_destroy (di->standalonesig_cache);
for (list = di->array_methods; list; list = list->next) {
ArrayMethod *am = (ArrayMethod *)list->data;
g_free (am->sig);
g_free (am->name);
g_free (am);
}
g_list_free (di->array_methods);
if (di->gen_params) {
for (i = 0; i < di->gen_params->len; i++) {
GenericParamTableEntry *entry = g_ptr_array_index (di->gen_params, i);
if (entry->gparam->type.type) {
MonoGenericParam *param = entry->gparam->type.type->data.generic_param;
g_free ((char*)mono_generic_param_info (param)->name);
g_free (param);
}
g_free (entry);
}
g_ptr_array_free (di->gen_params, TRUE);
}
if (di->token_fixups)
mono_g_hash_table_destroy (di->token_fixups);
if (di->method_to_table_idx)
g_hash_table_destroy (di->method_to_table_idx);
if (di->field_to_table_idx)
g_hash_table_destroy (di->field_to_table_idx);
if (di->method_aux_hash)
g_hash_table_destroy (di->method_aux_hash);
g_free (di->strong_name);
g_free (di->win32_res);
if (di->public_key)
g_free (di->public_key);
/*g_print ("string heap destroy for image %p\n", di);*/
mono_dynamic_stream_reset (&di->sheap);
mono_dynamic_stream_reset (&di->code);
mono_dynamic_stream_reset (&di->resources);
mono_dynamic_stream_reset (&di->us);
mono_dynamic_stream_reset (&di->blob);
mono_dynamic_stream_reset (&di->tstream);
mono_dynamic_stream_reset (&di->guid);
for (i = 0; i < MONO_TABLE_NUM; ++i) {
g_free (di->tables [i].values);
}
}
#ifndef DISABLE_REFLECTION_EMIT
/*
* mono_image_basic_init:
* @assembly: an assembly builder object
*
* Create the MonoImage that represents the assembly builder and setup some
* of the helper hash table and the basic metadata streams.
*/
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
MonoDynamicAssembly *assembly;
MonoDynamicImage *image;
MonoDomain *domain = mono_object_domain (assemblyb);
MONO_ARCH_SAVE_REGS;
if (assemblyb->dynamic_assembly)
return;
#if HAVE_BOEHM_GC
assembly = assemblyb->dynamic_assembly = GC_MALLOC (sizeof (MonoDynamicAssembly));
#else
assembly = assemblyb->dynamic_assembly = g_new0 (MonoDynamicAssembly, 1);
#endif
mono_profiler_assembly_event (&assembly->assembly, MONO_PROFILE_START_LOAD);
assembly->assembly.ref_count = 1;
assembly->assembly.dynamic = TRUE;
assembly->assembly.corlib_internal = assemblyb->corlib_internal;
assemblyb->assembly.assembly = (MonoAssembly*)assembly;
assembly->assembly.basedir = mono_string_to_utf8 (assemblyb->dir);
if (assemblyb->culture)
assembly->assembly.aname.culture = mono_string_to_utf8 (assemblyb->culture);
else
assembly->assembly.aname.culture = g_strdup ("");
if (assemblyb->version) {
char *vstr = mono_string_to_utf8 (assemblyb->version);
char **version = g_strsplit (vstr, ".", 4);
char **parts = version;
assembly->assembly.aname.major = atoi (*parts++);
assembly->assembly.aname.minor = atoi (*parts++);
assembly->assembly.aname.build = *parts != NULL ? atoi (*parts++) : 0;
assembly->assembly.aname.revision = *parts != NULL ? atoi (*parts) : 0;
g_strfreev (version);
g_free (vstr);
} else {
assembly->assembly.aname.major = 0;
assembly->assembly.aname.minor = 0;
assembly->assembly.aname.build = 0;
assembly->assembly.aname.revision = 0;
}
assembly->run = assemblyb->access != 2;
assembly->save = assemblyb->access != 1;
assembly->domain = domain;
image = create_dynamic_mono_image (assembly, mono_string_to_utf8 (assemblyb->name), g_strdup ("RefEmit_YouForgotToDefineAModule"));
image->initial_image = TRUE;
assembly->assembly.aname.name = image->image.name;
assembly->assembly.image = &image->image;
if (assemblyb->pktoken && assemblyb->pktoken->max_length) {
/* -1 to correct for the trailing NULL byte */
if (assemblyb->pktoken->max_length != MONO_PUBLIC_KEY_TOKEN_LENGTH - 1) {
g_error ("Public key token length invalid for assembly %s: %i", assembly->assembly.aname.name, assemblyb->pktoken->max_length);
}
memcpy (&assembly->assembly.aname.public_key_token, mono_array_addr (assemblyb->pktoken, guint8, 0), assemblyb->pktoken->max_length);
}
mono_domain_assemblies_lock (domain);
domain->domain_assemblies = g_slist_prepend (domain->domain_assemblies, assembly);
mono_domain_assemblies_unlock (domain);
register_assembly (mono_object_domain (assemblyb), &assemblyb->assembly, &assembly->assembly);
mono_profiler_assembly_loaded (&assembly->assembly, MONO_PROFILE_OK);
mono_assembly_invoke_load_hook ((MonoAssembly*)assembly);
}
#endif /* !DISABLE_REFLECTION_EMIT */
#ifndef DISABLE_REFLECTION_EMIT_SAVE
static int
calc_section_size (MonoDynamicImage *assembly)
{
int nsections = 0;
/* alignment constraints */
mono_image_add_stream_zero (&assembly->code, 4 - (assembly->code.index % 4));
g_assert ((assembly->code.index % 4) == 0);
assembly->meta_size += 3;
assembly->meta_size &= ~3;
mono_image_add_stream_zero (&assembly->resources, 4 - (assembly->resources.index % 4));
g_assert ((assembly->resources.index % 4) == 0);
assembly->sections [MONO_SECTION_TEXT].size = assembly->meta_size + assembly->code.index + assembly->resources.index + assembly->strong_name_size;
assembly->sections [MONO_SECTION_TEXT].attrs = SECT_FLAGS_HAS_CODE | SECT_FLAGS_MEM_EXECUTE | SECT_FLAGS_MEM_READ;
nsections++;
if (assembly->win32_res) {
guint32 res_size = (assembly->win32_res_size + 3) & ~3;
assembly->sections [MONO_SECTION_RSRC].size = res_size;
assembly->sections [MONO_SECTION_RSRC].attrs = SECT_FLAGS_HAS_INITIALIZED_DATA | SECT_FLAGS_MEM_READ;
nsections++;
}
assembly->sections [MONO_SECTION_RELOC].size = 12;
assembly->sections [MONO_SECTION_RELOC].attrs = SECT_FLAGS_MEM_READ | SECT_FLAGS_MEM_DISCARDABLE | SECT_FLAGS_HAS_INITIALIZED_DATA;
nsections++;
return nsections;
}
typedef struct {
guint32 id;
guint32 offset;
GSList *children;
MonoReflectionWin32Resource *win32_res; /* Only for leaf nodes */
} ResTreeNode;
static int
resource_tree_compare_by_id (gconstpointer a, gconstpointer b)
{
ResTreeNode *t1 = (ResTreeNode*)a;
ResTreeNode *t2 = (ResTreeNode*)b;
return t1->id - t2->id;
}
/*
* resource_tree_create:
*
* Organize the resources into a resource tree.
*/
static ResTreeNode *
resource_tree_create (MonoArray *win32_resources)
{
ResTreeNode *tree, *res_node, *type_node, *lang_node;
GSList *l;
int i;
tree = g_new0 (ResTreeNode, 1);
for (i = 0; i < mono_array_length (win32_resources); ++i) {
MonoReflectionWin32Resource *win32_res =
(MonoReflectionWin32Resource*)mono_array_addr (win32_resources, MonoReflectionWin32Resource, i);
/* Create node */
/* FIXME: BUG: this stores managed references in unmanaged memory */
lang_node = g_new0 (ResTreeNode, 1);
lang_node->id = win32_res->lang_id;
lang_node->win32_res = win32_res;
/* Create type node if neccesary */
type_node = NULL;
for (l = tree->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_type) {
type_node = (ResTreeNode*)l->data;
break;
}
if (!type_node) {
type_node = g_new0 (ResTreeNode, 1);
type_node->id = win32_res->res_type;
/*
* The resource types have to be sorted otherwise
* Windows Explorer can't display the version information.
*/
tree->children = g_slist_insert_sorted (tree->children,
type_node, resource_tree_compare_by_id);
}
/* Create res node if neccesary */
res_node = NULL;
for (l = type_node->children; l; l = l->next)
if (((ResTreeNode*)(l->data))->id == win32_res->res_id) {
res_node = (ResTreeNode*)l->data;
break;
}
if (!res_node) {
res_node = g_new0 (ResTreeNode, 1);
res_node->id = win32_res->res_id;
type_node->children = g_slist_append (type_node->children, res_node);
}
res_node->children = g_slist_append (res_node->children, lang_node);
}
return tree;
}
/*
* resource_tree_encode:
*
* Encode the resource tree into the format used in the PE file.
*/
static void
resource_tree_encode (ResTreeNode *node, char *begin, char *p, char **endbuf)
{
char *entries;
MonoPEResourceDir dir;
MonoPEResourceDirEntry dir_entry;
MonoPEResourceDataEntry data_entry;
GSList *l;
guint32 res_id_entries;
/*
* For the format of the resource directory, see the article
* "An In-Depth Look into the Win32 Portable Executable File Format" by
* Matt Pietrek
*/
memset (&dir, 0, sizeof (dir));
memset (&dir_entry, 0, sizeof (dir_entry));
memset (&data_entry, 0, sizeof (data_entry));
g_assert (sizeof (dir) == 16);
g_assert (sizeof (dir_entry) == 8);
g_assert (sizeof (data_entry) == 16);
node->offset = p - begin;
/* IMAGE_RESOURCE_DIRECTORY */
res_id_entries = g_slist_length (node->children);
dir.res_id_entries = GUINT16_TO_LE (res_id_entries);
memcpy (p, &dir, sizeof (dir));
p += sizeof (dir);
/* Reserve space for entries */
entries = p;
p += sizeof (dir_entry) * res_id_entries;
/* Write children */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
if (child->win32_res) {
guint32 size;
child->offset = p - begin;
/* IMAGE_RESOURCE_DATA_ENTRY */
data_entry.rde_data_offset = GUINT32_TO_LE (p - begin + sizeof (data_entry));
size = mono_array_length (child->win32_res->res_data);
data_entry.rde_size = GUINT32_TO_LE (size);
memcpy (p, &data_entry, sizeof (data_entry));
p += sizeof (data_entry);
memcpy (p, mono_array_addr (child->win32_res->res_data, char, 0), size);
p += size;
} else {
resource_tree_encode (child, begin, p, &p);
}
}
/* IMAGE_RESOURCE_ENTRY */
for (l = node->children; l; l = l->next) {
ResTreeNode *child = (ResTreeNode*)l->data;
MONO_PE_RES_DIR_ENTRY_SET_NAME (dir_entry, FALSE, child->id);
MONO_PE_RES_DIR_ENTRY_SET_DIR (dir_entry, !child->win32_res, child->offset);
memcpy (entries, &dir_entry, sizeof (dir_entry));
entries += sizeof (dir_entry);
}
*endbuf = p;
}
static void
resource_tree_free (ResTreeNode * node)
{
GSList * list;
for (list = node->children; list; list = list->next)
resource_tree_free ((ResTreeNode*)list->data);
g_slist_free(node->children);
g_free (node);
}
static void
assembly_add_win32_resources (MonoDynamicImage *assembly, MonoReflectionAssemblyBuilder *assemblyb)
{
char *buf;
char *p;
guint32 size, i;
MonoReflectionWin32Resource *win32_res;
ResTreeNode *tree;
if (!assemblyb->win32_resources)
return;
/*
* Resources are stored in a three level tree inside the PE file.
* - level one contains a node for each type of resource
* - level two contains a node for each resource
* - level three contains a node for each instance of a resource for a
* specific language.
*/
tree = resource_tree_create (assemblyb->win32_resources);
/* Estimate the size of the encoded tree */
size = 0;
for (i = 0; i < mono_array_length (assemblyb->win32_resources); ++i) {
win32_res = (MonoReflectionWin32Resource*)mono_array_addr (assemblyb->win32_resources, MonoReflectionWin32Resource, i);
size += mono_array_length (win32_res->res_data);
}
/* Directory structure */
size += mono_array_length (assemblyb->win32_resources) * 256;
p = buf = g_malloc (size);
resource_tree_encode (tree, p, p, &p);
g_assert (p - buf <= size);
assembly->win32_res = g_malloc (p - buf);
assembly->win32_res_size = p - buf;
memcpy (assembly->win32_res, buf, p - buf);
g_free (buf);
resource_tree_free (tree);
}
static void
fixup_resource_directory (char *res_section, char *p, guint32 rva)
{
MonoPEResourceDir *dir = (MonoPEResourceDir*)p;
int i;
p += sizeof (MonoPEResourceDir);
for (i = 0; i < GUINT16_FROM_LE (dir->res_named_entries) + GUINT16_FROM_LE (dir->res_id_entries); ++i) {
MonoPEResourceDirEntry *dir_entry = (MonoPEResourceDirEntry*)p;
char *child = res_section + MONO_PE_RES_DIR_ENTRY_DIR_OFFSET (*dir_entry);
if (MONO_PE_RES_DIR_ENTRY_IS_DIR (*dir_entry)) {
fixup_resource_directory (res_section, child, rva);
} else {
MonoPEResourceDataEntry *data_entry = (MonoPEResourceDataEntry*)child;
data_entry->rde_data_offset = GUINT32_TO_LE (GUINT32_FROM_LE (data_entry->rde_data_offset) + rva);
}
p += sizeof (MonoPEResourceDirEntry);
}
}
static void
checked_write_file (HANDLE f, gconstpointer buffer, guint32 numbytes)
{
guint32 dummy;
if (!WriteFile (f, buffer, numbytes, &dummy, NULL))
g_error ("WriteFile returned %d\n", GetLastError ());
}
/*
* mono_image_create_pefile:
* @mb: a module builder object
*
* This function creates the PE-COFF header, the image sections, the CLI header * etc. all the data is written in
* assembly->pefile where it can be easily retrieved later in chunks.
*/
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
MonoMSDOSHeader *msdos;
MonoDotNetHeader *header;
MonoSectionTable *section;
MonoCLIHeader *cli_header;
guint32 size, image_size, virtual_base, text_offset;
guint32 header_start, section_start, file_offset, virtual_offset;
MonoDynamicImage *assembly;
MonoReflectionAssemblyBuilder *assemblyb;
MonoDynamicStream pefile_stream = {0};
MonoDynamicStream *pefile = &pefile_stream;
int i, nsections;
guint32 *rva, value;
guchar *p;
static const unsigned char msheader[] = {
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
assemblyb = mb->assemblyb;
mono_image_basic_init (assemblyb);
assembly = mb->dynamic_image;
assembly->pe_kind = assemblyb->pe_kind;
assembly->machine = assemblyb->machine;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->pe_kind = assemblyb->pe_kind;
((MonoDynamicImage*)assemblyb->dynamic_assembly->assembly.image)->machine = assemblyb->machine;
mono_image_build_metadata (mb);
if (mb->is_main && assemblyb->resources) {
int len = mono_array_length (assemblyb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (assemblyb->resources, MonoReflectionResource, i));
}
if (mb->resources) {
int len = mono_array_length (mb->resources);
for (i = 0; i < len; ++i)
assembly_add_resource (mb, assembly, (MonoReflectionResource*)mono_array_addr (mb->resources, MonoReflectionResource, i));
}
build_compressed_metadata (assembly);
if (mb->is_main)
assembly_add_win32_resources (assembly, assemblyb);
nsections = calc_section_size (assembly);
/* The DOS header and stub */
g_assert (sizeof (MonoMSDOSHeader) == sizeof (msheader));
mono_image_add_stream_data (pefile, (char*)msheader, sizeof (msheader));
/* the dotnet header */
header_start = mono_image_add_stream_zero (pefile, sizeof (MonoDotNetHeader));
/* the section tables */
section_start = mono_image_add_stream_zero (pefile, sizeof (MonoSectionTable) * nsections);
file_offset = section_start + sizeof (MonoSectionTable) * nsections;
virtual_offset = VIRT_ALIGN;
image_size = 0;
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
/* align offsets */
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
virtual_offset += VIRT_ALIGN - 1;
virtual_offset &= ~(VIRT_ALIGN - 1);
assembly->sections [i].offset = file_offset;
assembly->sections [i].rva = virtual_offset;
file_offset += assembly->sections [i].size;
virtual_offset += assembly->sections [i].size;
image_size += (assembly->sections [i].size + VIRT_ALIGN - 1) & ~(VIRT_ALIGN - 1);
}
file_offset += FILE_ALIGN - 1;
file_offset &= ~(FILE_ALIGN - 1);
image_size += section_start + sizeof (MonoSectionTable) * nsections;
/* back-patch info */
msdos = (MonoMSDOSHeader*)pefile->data;
msdos->pe_offset = GUINT32_FROM_LE (sizeof (MonoMSDOSHeader));
header = (MonoDotNetHeader*)(pefile->data + header_start);
header->pesig [0] = 'P';
header->pesig [1] = 'E';
header->coff.coff_machine = GUINT16_FROM_LE (assemblyb->machine);
header->coff.coff_sections = GUINT16_FROM_LE (nsections);
header->coff.coff_time = GUINT32_FROM_LE (time (NULL));
header->coff.coff_opt_header_size = GUINT16_FROM_LE (sizeof (MonoDotNetHeader) - sizeof (MonoCOFFHeader) - 4);
if (assemblyb->pekind == 1) {
/* it's a dll */
header->coff.coff_attributes = GUINT16_FROM_LE (0x210e);
} else {
/* it's an exe */
header->coff.coff_attributes = GUINT16_FROM_LE (0x010e);
}
virtual_base = 0x400000; /* FIXME: 0x10000000 if a DLL */
header->pe.pe_magic = GUINT16_FROM_LE (0x10B);
header->pe.pe_major = 6;
header->pe.pe_minor = 0;
size = assembly->sections [MONO_SECTION_TEXT].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_code_size = GUINT32_FROM_LE(size);
size = assembly->sections [MONO_SECTION_RSRC].size;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->pe.pe_data_size = GUINT32_FROM_LE(size);
g_assert (START_TEXT_RVA == assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_code_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->pe.pe_rva_data_base = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
/* pe_rva_entry_point always at the beginning of the text section */
header->pe.pe_rva_entry_point = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_TEXT].rva);
header->nt.pe_image_base = GUINT32_FROM_LE (virtual_base);
header->nt.pe_section_align = GUINT32_FROM_LE (VIRT_ALIGN);
header->nt.pe_file_alignment = GUINT32_FROM_LE (FILE_ALIGN);
header->nt.pe_os_major = GUINT16_FROM_LE (4);
header->nt.pe_os_minor = GUINT16_FROM_LE (0);
header->nt.pe_subsys_major = GUINT16_FROM_LE (4);
size = section_start;
size += FILE_ALIGN - 1;
size &= ~(FILE_ALIGN - 1);
header->nt.pe_header_size = GUINT32_FROM_LE (size);
size = image_size;
size += VIRT_ALIGN - 1;
size &= ~(VIRT_ALIGN - 1);
header->nt.pe_image_size = GUINT32_FROM_LE (size);
/*
// Translate the PEFileKind value to the value expected by the Windows loader
*/
{
short kind;
/*
// PEFileKinds.Dll == 1
// PEFileKinds.ConsoleApplication == 2
// PEFileKinds.WindowApplication == 3
//
// need to get:
// IMAGE_SUBSYSTEM_WINDOWS_GUI 2 // Image runs in the Windows GUI subsystem.
// IMAGE_SUBSYSTEM_WINDOWS_CUI 3 // Image runs in the Windows character subsystem.
*/
if (assemblyb->pekind == 3)
kind = 2;
else
kind = 3;
header->nt.pe_subsys_required = GUINT16_FROM_LE (kind);
}
header->nt.pe_stack_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_stack_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_heap_reserve = GUINT32_FROM_LE (0x00100000);
header->nt.pe_heap_commit = GUINT32_FROM_LE (0x00001000);
header->nt.pe_loader_flags = GUINT32_FROM_LE (0);
header->nt.pe_data_dir_count = GUINT32_FROM_LE (16);
/* fill data directory entries */
header->datadir.pe_resource_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].size);
header->datadir.pe_resource_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RSRC].rva);
header->datadir.pe_reloc_table.size = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].size);
header->datadir.pe_reloc_table.rva = GUINT32_FROM_LE (assembly->sections [MONO_SECTION_RELOC].rva);
header->datadir.pe_cli_header.size = GUINT32_FROM_LE (72);
header->datadir.pe_cli_header.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->cli_header_offset);
header->datadir.pe_iat.size = GUINT32_FROM_LE (8);
header->datadir.pe_iat.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
/* patch entrypoint name */
if (assemblyb->pekind == 1)
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorDllMain", 12);
else
memcpy (assembly->code.data + assembly->imp_names_offset + 2, "_CorExeMain", 12);
/* patch imported function RVA name */
rva = (guint32*)(assembly->code.data + assembly->iat_offset);
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset);
/* the import table */
header->datadir.pe_import_table.size = GUINT32_FROM_LE (79); /* FIXME: magic number? */
header->datadir.pe_import_table.rva = GUINT32_FROM_LE (assembly->text_rva + assembly->idt_offset);
/* patch imported dll RVA name and other entries in the dir */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, name_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->imp_names_offset + 14); /* 14 is hint+strlen+1 of func name */
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_address_table_rva));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->iat_offset);
rva = (guint32*)(assembly->code.data + assembly->idt_offset + G_STRUCT_OFFSET (MonoIDT, import_lookup_table));
*rva = GUINT32_FROM_LE (assembly->text_rva + assembly->ilt_offset);
p = (guchar*)(assembly->code.data + assembly->ilt_offset);
value = (assembly->text_rva + assembly->imp_names_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & (0xff);
*p++ = (value >> 16) & (0xff);
*p++ = (value >> 24) & (0xff);
/* the CLI header info */
cli_header = (MonoCLIHeader*)(assembly->code.data + assembly->cli_header_offset);
cli_header->ch_size = GUINT32_FROM_LE (72);
cli_header->ch_runtime_major = GUINT16_FROM_LE (2);
if (mono_framework_version () > 1)
cli_header->ch_runtime_minor = GUINT16_FROM_LE (5);
else
cli_header->ch_runtime_minor = GUINT16_FROM_LE (0);
cli_header->ch_flags = GUINT32_FROM_LE (assemblyb->pe_kind);
if (assemblyb->entry_point) {
guint32 table_idx = 0;
if (!strcmp (assemblyb->entry_point->object.vtable->klass->name, "MethodBuilder")) {
MonoReflectionMethodBuilder *methodb = (MonoReflectionMethodBuilder*)assemblyb->entry_point;
table_idx = methodb->table_idx;
} else {
table_idx = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->method_to_table_idx, assemblyb->entry_point->method));
}
cli_header->ch_entry_point = GUINT32_FROM_LE (table_idx | MONO_TOKEN_METHOD_DEF);
} else {
cli_header->ch_entry_point = GUINT32_FROM_LE (0);
}
/* The embedded managed resources */
text_offset = assembly->text_rva + assembly->code.index;
cli_header->ch_resources.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_resources.size = GUINT32_FROM_LE (assembly->resources.index);
text_offset += assembly->resources.index;
cli_header->ch_metadata.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_metadata.size = GUINT32_FROM_LE (assembly->meta_size);
text_offset += assembly->meta_size;
if (assembly->strong_name_size) {
cli_header->ch_strong_name.rva = GUINT32_FROM_LE (text_offset);
cli_header->ch_strong_name.size = GUINT32_FROM_LE (assembly->strong_name_size);
text_offset += assembly->strong_name_size;
}
/* write the section tables and section content */
section = (MonoSectionTable*)(pefile->data + section_start);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
static const char section_names [][7] = {
".text", ".rsrc", ".reloc"
};
if (!assembly->sections [i].size)
continue;
strcpy (section->st_name, section_names [i]);
/*g_print ("output section %s (%d), size: %d\n", section->st_name, i, assembly->sections [i].size);*/
section->st_virtual_address = GUINT32_FROM_LE (assembly->sections [i].rva);
section->st_virtual_size = GUINT32_FROM_LE (assembly->sections [i].size);
section->st_raw_data_size = GUINT32_FROM_LE (GUINT32_TO_LE (section->st_virtual_size) + (FILE_ALIGN - 1));
section->st_raw_data_size &= GUINT32_FROM_LE (~(FILE_ALIGN - 1));
section->st_raw_data_ptr = GUINT32_FROM_LE (assembly->sections [i].offset);
section->st_flags = GUINT32_FROM_LE (assembly->sections [i].attrs);
section ++;
}
checked_write_file (file, pefile->data, pefile->index);
mono_dynamic_stream_reset (pefile);
for (i = 0; i < MONO_SECTION_MAX; ++i) {
if (!assembly->sections [i].size)
continue;
if (SetFilePointer (file, assembly->sections [i].offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
switch (i) {
case MONO_SECTION_TEXT:
/* patch entry point */
p = (guchar*)(assembly->code.data + 2);
value = (virtual_base + assembly->text_rva + assembly->iat_offset);
*p++ = (value) & 0xff;
*p++ = (value >> 8) & 0xff;
*p++ = (value >> 16) & 0xff;
*p++ = (value >> 24) & 0xff;
checked_write_file (file, assembly->code.data, assembly->code.index);
checked_write_file (file, assembly->resources.data, assembly->resources.index);
checked_write_file (file, assembly->image.raw_metadata, assembly->meta_size);
checked_write_file (file, assembly->strong_name, assembly->strong_name_size);
g_free (assembly->image.raw_metadata);
break;
case MONO_SECTION_RELOC: {
struct {
guint32 page_rva;
guint32 block_size;
guint16 type_and_offset;
guint16 term;
} reloc;
g_assert (sizeof (reloc) == 12);
reloc.page_rva = GUINT32_FROM_LE (assembly->text_rva);
reloc.block_size = GUINT32_FROM_LE (12);
/*
* the entrypoint is always at the start of the text section
* 3 is IMAGE_REL_BASED_HIGHLOW
* 2 is patch_size_rva - text_rva
*/
reloc.type_and_offset = GUINT16_FROM_LE ((3 << 12) + (2));
reloc.term = 0;
checked_write_file (file, &reloc, sizeof (reloc));
break;
}
case MONO_SECTION_RSRC:
if (assembly->win32_res) {
/* Fixup the offsets in the IMAGE_RESOURCE_DATA_ENTRY structures */
fixup_resource_directory (assembly->win32_res, assembly->win32_res, assembly->sections [i].rva);
checked_write_file (file, assembly->win32_res, assembly->win32_res_size);
}
break;
default:
g_assert_not_reached ();
}
}
/* check that the file is properly padded */
if (SetFilePointer (file, file_offset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
g_error ("SetFilePointer returned %d\n", GetLastError ());
if (! SetEndOfFile (file))
g_error ("SetEndOfFile returned %d\n", GetLastError ());
mono_dynamic_stream_reset (&assembly->code);
mono_dynamic_stream_reset (&assembly->us);
mono_dynamic_stream_reset (&assembly->blob);
mono_dynamic_stream_reset (&assembly->guid);
mono_dynamic_stream_reset (&assembly->sheap);
g_hash_table_foreach (assembly->blob_cache, (GHFunc)g_free, NULL);
g_hash_table_destroy (assembly->blob_cache);
assembly->blob_cache = NULL;
}
#else /* DISABLE_REFLECTION_EMIT_SAVE */
void
mono_image_create_pefile (MonoReflectionModuleBuilder *mb, HANDLE file)
{
g_assert_not_reached ();
}
#endif /* DISABLE_REFLECTION_EMIT_SAVE */
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
char *name;
MonoImage *image;
MonoImageOpenStatus status;
MonoDynamicAssembly *assembly;
guint32 module_count;
MonoImage **new_modules;
gboolean *new_modules_loaded;
name = mono_string_to_utf8 (fileName);
image = mono_image_open (name, &status);
if (!image) {
MonoException *exc;
if (status == MONO_IMAGE_ERROR_ERRNO)
exc = mono_get_exception_file_not_found (fileName);
else
exc = mono_get_exception_bad_image_format (name);
g_free (name);
mono_raise_exception (exc);
}
g_free (name);
assembly = ab->dynamic_assembly;
image->assembly = (MonoAssembly*)assembly;
module_count = image->assembly->image->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
new_modules_loaded = g_new0 (gboolean, module_count + 1);
if (image->assembly->image->modules)
memcpy (new_modules, image->assembly->image->modules, module_count * sizeof (MonoImage *));
if (image->assembly->image->modules_loaded)
memcpy (new_modules_loaded, image->assembly->image->modules_loaded, module_count * sizeof (gboolean));
new_modules [module_count] = image;
new_modules_loaded [module_count] = TRUE;
mono_image_addref (image);
g_free (image->assembly->image->modules);
image->assembly->image->modules = new_modules;
image->assembly->image->modules_loaded = new_modules_loaded;
image->assembly->image->module_count ++;
mono_assembly_load_references (image, &status);
if (status) {
mono_image_close (image);
mono_raise_exception (mono_get_exception_file_not_found (fileName));
}
return mono_module_get_object (mono_domain_get (), image);
}
#endif /* DISABLE_REFLECTION_EMIT */
/*
* We need to return always the same object for MethodInfo, FieldInfo etc..
* but we need to consider the reflected type.
* type uses a different hash, since it uses custom hash/equal functions.
*/
typedef struct {
gpointer item;
MonoClass *refclass;
} ReflectedEntry;
static gboolean
reflected_equal (gconstpointer a, gconstpointer b) {
const ReflectedEntry *ea = a;
const ReflectedEntry *eb = b;
return (ea->item == eb->item) && (ea->refclass == eb->refclass);
}
static guint
reflected_hash (gconstpointer a) {
const ReflectedEntry *ea = a;
return mono_aligned_addr_hash (ea->item);
}
#define CHECK_OBJECT(t,p,k) \
do { \
t _obj; \
ReflectedEntry e; \
e.item = (p); \
e.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
if ((_obj = mono_g_hash_table_lookup (domain->refobject_hash, &e))) { \
mono_domain_unlock (domain); \
return _obj; \
} \
mono_domain_unlock (domain); \
} while (0)
#ifdef HAVE_BOEHM_GC
/* ReflectedEntry doesn't need to be GC tracked */
#define ALLOC_REFENTRY g_new0 (ReflectedEntry, 1)
#define FREE_REFENTRY(entry) g_free ((entry))
#define REFENTRY_REQUIRES_CLEANUP
#else
#define ALLOC_REFENTRY mono_mempool_alloc (domain->mp, sizeof (ReflectedEntry))
/* FIXME: */
#define FREE_REFENTRY(entry)
#endif
#define CACHE_OBJECT(t,p,o,k) \
do { \
t _obj; \
ReflectedEntry pe; \
pe.item = (p); \
pe.refclass = (k); \
mono_domain_lock (domain); \
if (!domain->refobject_hash) \
domain->refobject_hash = mono_g_hash_table_new_type (reflected_hash, reflected_equal, MONO_HASH_VALUE_GC); \
_obj = mono_g_hash_table_lookup (domain->refobject_hash, &pe); \
if (!_obj) { \
ReflectedEntry *e = ALLOC_REFENTRY; \
e->item = (p); \
e->refclass = (k); \
mono_g_hash_table_insert (domain->refobject_hash, e,o); \
_obj = o; \
} \
mono_domain_unlock (domain); \
return _obj; \
} while (0)
static void
clear_cached_object (MonoDomain *domain, gpointer o, MonoClass *klass)
{
mono_domain_lock (domain);
if (domain->refobject_hash) {
ReflectedEntry pe;
gpointer orig_pe, orig_value;
pe.item = o;
pe.refclass = klass;
if (mono_g_hash_table_lookup_extended (domain->refobject_hash, &pe, &orig_pe, &orig_value)) {
mono_g_hash_table_remove (domain->refobject_hash, &pe);
FREE_REFENTRY (orig_pe);
}
}
mono_domain_unlock (domain);
}
#ifdef REFENTRY_REQUIRES_CLEANUP
static void
cleanup_refobject_hash (gpointer key, gpointer value, gpointer user_data)
{
FREE_REFENTRY (key);
}
#endif
void
mono_reflection_cleanup_domain (MonoDomain *domain)
{
if (domain->refobject_hash) {
/*let's avoid scanning the whole hashtable if not needed*/
#ifdef REFENTRY_REQUIRES_CLEANUP
mono_g_hash_table_foreach (domain->refobject_hash, cleanup_refobject_hash, NULL);
#endif
mono_g_hash_table_destroy (domain->refobject_hash);
domain->refobject_hash = NULL;
}
}
#ifndef DISABLE_REFLECTION_EMIT
static gpointer
register_assembly (MonoDomain *domain, MonoReflectionAssembly *res, MonoAssembly *assembly)
{
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
static gpointer
register_module (MonoDomain *domain, MonoReflectionModuleBuilder *res, MonoDynamicImage *module)
{
CACHE_OBJECT (MonoReflectionModuleBuilder *, module, res, NULL);
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
MonoDynamicImage *image = moduleb->dynamic_image;
MonoReflectionAssemblyBuilder *ab = moduleb->assemblyb;
if (!image) {
MonoError error;
int module_count;
MonoImage **new_modules;
MonoImage *ass;
char *name, *fqname;
/*
* FIXME: we already created an image in mono_image_basic_init (), but
* we don't know which module it belongs to, since that is only
* determined at assembly save time.
*/
/*image = (MonoDynamicImage*)ab->dynamic_assembly->assembly.image; */
name = mono_string_to_utf8 (ab->name);
fqname = mono_string_to_utf8_checked (moduleb->module.fqname, &error);
if (!mono_error_ok (&error)) {
g_free (name);
mono_error_raise_exception (&error);
}
image = create_dynamic_mono_image (ab->dynamic_assembly, name, fqname);
moduleb->module.image = &image->image;
moduleb->dynamic_image = image;
register_module (mono_object_domain (moduleb), moduleb, image);
/* register the module with the assembly */
ass = ab->dynamic_assembly->assembly.image;
module_count = ass->module_count;
new_modules = g_new0 (MonoImage *, module_count + 1);
if (ass->modules)
memcpy (new_modules, ass->modules, module_count * sizeof (MonoImage *));
new_modules [module_count] = &image->image;
mono_image_addref (&image->image);
g_free (ass->modules);
ass->modules = new_modules;
ass->module_count ++;
}
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
MonoDynamicImage *image = moduleb->dynamic_image;
g_assert (type->type);
image->wrappers_type = mono_class_from_mono_type (type->type);
}
#endif
/*
* mono_assembly_get_object:
* @domain: an app domain
* @assembly: an assembly
*
* Return an System.Reflection.Assembly object representing the MonoAssembly @assembly.
*/
MonoReflectionAssembly*
mono_assembly_get_object (MonoDomain *domain, MonoAssembly *assembly)
{
static MonoClass *System_Reflection_Assembly;
MonoReflectionAssembly *res;
CHECK_OBJECT (MonoReflectionAssembly *, assembly, NULL);
if (!System_Reflection_Assembly)
System_Reflection_Assembly = mono_class_from_name (
mono_defaults.corlib, "System.Reflection", "Assembly");
res = (MonoReflectionAssembly *)mono_object_new (domain, System_Reflection_Assembly);
res->assembly = assembly;
CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL);
}
MonoReflectionModule*
mono_module_get_object (MonoDomain *domain, MonoImage *image)
{
static MonoClass *System_Reflection_Module;
MonoReflectionModule *res;
char* basename;
CHECK_OBJECT (MonoReflectionModule *, image, NULL);
if (!System_Reflection_Module)
System_Reflection_Module = mono_class_from_name (
mono_defaults.corlib, "System.Reflection", "Module");
res = (MonoReflectionModule *)mono_object_new (domain, System_Reflection_Module);
res->image = image;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, image->name));
basename = g_path_get_basename (image->name);
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, basename));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, image->module_name));
g_free (basename);
if (image->assembly->image == image) {
res->token = mono_metadata_make_token (MONO_TABLE_MODULE, 1);
} else {
int i;
res->token = 0;
if (image->assembly->image->modules) {
for (i = 0; i < image->assembly->image->module_count; i++) {
if (image->assembly->image->modules [i] == image)
res->token = mono_metadata_make_token (MONO_TABLE_MODULEREF, i + 1);
}
g_assert (res->token);
}
}
CACHE_OBJECT (MonoReflectionModule *, image, res, NULL);
}
MonoReflectionModule*
mono_module_file_get_object (MonoDomain *domain, MonoImage *image, int table_index)
{
static MonoClass *System_Reflection_Module;
MonoReflectionModule *res;
MonoTableInfo *table;
guint32 cols [MONO_FILE_SIZE];
const char *name;
guint32 i, name_idx;
const char *val;
if (!System_Reflection_Module)
System_Reflection_Module = mono_class_from_name (
mono_defaults.corlib, "System.Reflection", "Module");
res = (MonoReflectionModule *)mono_object_new (domain, System_Reflection_Module);
table = &image->tables [MONO_TABLE_FILE];
g_assert (table_index < table->rows);
mono_metadata_decode_row (table, table_index, cols, MONO_FILE_SIZE);
res->image = NULL;
MONO_OBJECT_SETREF (res, assembly, (MonoReflectionAssembly *) mono_assembly_get_object(domain, image->assembly));
name = mono_metadata_string_heap (image, cols [MONO_FILE_NAME]);
/* Check whenever the row has a corresponding row in the moduleref table */
table = &image->tables [MONO_TABLE_MODULEREF];
for (i = 0; i < table->rows; ++i) {
name_idx = mono_metadata_decode_row_col (table, i, MONO_MODULEREF_NAME);
val = mono_metadata_string_heap (image, name_idx);
if (strcmp (val, name) == 0)
res->image = image->modules [i];
}
MONO_OBJECT_SETREF (res, fqname, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, name));
MONO_OBJECT_SETREF (res, scopename, mono_string_new (domain, name));
res->is_resource = cols [MONO_FILE_FLAGS] && FILE_CONTAINS_NO_METADATA;
res->token = mono_metadata_make_token (MONO_TABLE_FILE, table_index + 1);
return res;
}
static gboolean
mymono_metadata_type_equal (MonoType *t1, MonoType *t2)
{
if ((t1->type != t2->type) ||
(t1->byref != t2->byref))
return FALSE;
switch (t1->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_STRING:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_OBJECT:
case MONO_TYPE_TYPEDBYREF:
return TRUE;
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
return t1->data.klass == t2->data.klass;
case MONO_TYPE_PTR:
return mymono_metadata_type_equal (t1->data.type, t2->data.type);
case MONO_TYPE_ARRAY:
if (t1->data.array->rank != t2->data.array->rank)
return FALSE;
return t1->data.array->eklass == t2->data.array->eklass;
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *i1 = t1->data.generic_class->context.class_inst;
MonoGenericInst *i2 = t2->data.generic_class->context.class_inst;
if (i1->type_argc != i2->type_argc)
return FALSE;
if (!mono_metadata_type_equal (&t1->data.generic_class->container_class->byval_arg,
&t2->data.generic_class->container_class->byval_arg))
return FALSE;
/* FIXME: we should probably just compare the instance pointers directly. */
for (i = 0; i < i1->type_argc; ++i) {
if (!mono_metadata_type_equal (i1->type_argv [i], i2->type_argv [i]))
return FALSE;
}
return TRUE;
}
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return t1->data.generic_param == t2->data.generic_param;
default:
g_error ("implement type compare for %0x!", t1->type);
return FALSE;
}
return FALSE;
}
static guint
mymono_metadata_type_hash (MonoType *t1)
{
guint hash;
hash = t1->type;
hash |= t1->byref << 6; /* do not collide with t1->type values */
switch (t1->type) {
case MONO_TYPE_VALUETYPE:
case MONO_TYPE_CLASS:
case MONO_TYPE_SZARRAY:
/* check if the distribution is good enough */
return ((hash << 5) - hash) ^ g_str_hash (t1->data.klass->name);
case MONO_TYPE_PTR:
return ((hash << 5) - hash) ^ mymono_metadata_type_hash (t1->data.type);
case MONO_TYPE_GENERICINST: {
int i;
MonoGenericInst *inst = t1->data.generic_class->context.class_inst;
hash += g_str_hash (t1->data.generic_class->container_class->name);
hash *= 13;
for (i = 0; i < inst->type_argc; ++i) {
hash += mymono_metadata_type_hash (inst->type_argv [i]);
hash *= 13;
}
return hash;
}
}
return hash;
}
static MonoReflectionGenericClass*
mono_generic_class_get_object (MonoDomain *domain, MonoType *geninst)
{
static MonoClass *System_Reflection_MonoGenericClass;
MonoReflectionGenericClass *res;
MonoClass *klass, *gklass;
MonoGenericInst *ginst;
MonoArray *type_args;
int i;
if (!System_Reflection_MonoGenericClass) {
System_Reflection_MonoGenericClass = mono_class_from_name (
mono_defaults.corlib, "System.Reflection", "MonoGenericClass");
g_assert (System_Reflection_MonoGenericClass);
}
klass = mono_class_from_mono_type (geninst);
gklass = klass->generic_class->container_class;
mono_class_init (klass);
#ifdef HAVE_SGEN_GC
res = (MonoReflectionGenericClass *) mono_gc_alloc_pinned_obj (mono_class_vtable (domain, System_Reflection_MonoGenericClass), mono_class_instance_size (System_Reflection_MonoGenericClass));
#else
res = (MonoReflectionGenericClass *) mono_object_new (domain, System_Reflection_MonoGenericClass);
#endif
res->type.type = geninst;
g_assert (gklass->reflection_info);
g_assert (!strcmp (((MonoObject*)gklass->reflection_info)->vtable->klass->name, "TypeBuilder"));
MONO_OBJECT_SETREF (res, generic_type, gklass->reflection_info);
ginst = klass->generic_class->context.class_inst;
type_args = mono_array_new (domain, mono_defaults.systemtype_class, ginst->type_argc);
for (i = 0; i < ginst->type_argc; ++i)
mono_array_setref (type_args, i, mono_type_get_object (domain, ginst->type_argv [i]));
MONO_OBJECT_SETREF (res, type_arguments, type_args);
return res;
}
static gboolean
verify_safe_for_managed_space (MonoType *type)
{
switch (type->type) {
#ifdef DEBUG_HARDER
case MONO_TYPE_ARRAY:
return verify_safe_for_managed_space (&type->data.array->eklass->byval_arg);
case MONO_TYPE_PTR:
return verify_safe_for_managed_space (type->data.type);
case MONO_TYPE_SZARRAY:
return verify_safe_for_managed_space (&type->data.klass->byval_arg);
case MONO_TYPE_GENERICINST: {
MonoGenericInst *inst = type->data.generic_class->inst;
int i;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!verify_safe_for_managed_space (inst->type_argv [i]))
return FALSE;
break;
}
#endif
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
return TRUE;
}
return TRUE;
}
/*
* mono_type_get_object:
* @domain: an app domain
* @type: a type
*
* Return an System.MonoType object representing the type @type.
*/
MonoReflectionType*
mono_type_get_object (MonoDomain *domain, MonoType *type)
{
MonoReflectionType *res;
MonoClass *klass = mono_class_from_mono_type (type);
/*we must avoid using @type as it might have come
* from a mono_metadata_type_dup and the caller
* expects that is can be freed.
* Using the right type from
*/
type = klass->byval_arg.byref == type->byref ? &klass->byval_arg : &klass->this_arg;
/* void is very common */
if (type->type == MONO_TYPE_VOID && domain->typeof_void)
return (MonoReflectionType*)domain->typeof_void;
/*
* If the vtable of the given class was already created, we can use
* the MonoType from there and avoid all locking and hash table lookups.
*
* We cannot do this for TypeBuilders as mono_reflection_create_runtime_class expects
* that the resulting object is different.
*/
if (type == &klass->byval_arg && !klass->image->dynamic) {
MonoVTable *vtable = mono_class_try_get_vtable (domain, klass);
if (vtable && vtable->type)
return vtable->type;
}
mono_loader_lock (); /*FIXME mono_class_init and mono_class_vtable acquire it*/
mono_domain_lock (domain);
if (!domain->type_hash)
domain->type_hash = mono_g_hash_table_new_type ((GHashFunc)mymono_metadata_type_hash,
(GCompareFunc)mymono_metadata_type_equal, MONO_HASH_VALUE_GC);
if ((res = mono_g_hash_table_lookup (domain->type_hash, type))) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/* Create a MonoGenericClass object for instantiations of not finished TypeBuilders */
if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder) {
res = (MonoReflectionType *)mono_generic_class_get_object (domain, type);
mono_g_hash_table_insert (domain->type_hash, type, res);
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
if (!verify_safe_for_managed_space (type)) {
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_raise_exception (mono_get_exception_invalid_operation ("This type cannot be propagated to managed space"));
}
if (klass->reflection_info && !klass->wastypebuilder) {
gboolean is_type_done = TRUE;
/* Generic parameters have reflection_info set but they are not finished together with their enclosing type.
* We must ensure that once a type is finished we don't return a GenericTypeParameterBuilder.
* We can't simply close the types as this will interfere with other parts of the generics machinery.
*/
if (klass->byval_arg.type == MONO_TYPE_MVAR || klass->byval_arg.type == MONO_TYPE_VAR) {
MonoGenericParam *gparam = klass->byval_arg.data.generic_param;
if (gparam->owner && gparam->owner->is_method) {
MonoMethod *method = gparam->owner->owner.method;
if (method && mono_class_get_generic_type_definition (method->klass)->wastypebuilder)
is_type_done = FALSE;
} else if (gparam->owner && !gparam->owner->is_method) {
MonoClass *klass = gparam->owner->owner.klass;
if (klass && mono_class_get_generic_type_definition (klass)->wastypebuilder)
is_type_done = FALSE;
}
}
/* g_assert_not_reached (); */
/* should this be considered an error condition? */
if (is_type_done && !type->byref) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return klass->reflection_info;
}
}
// FIXME: Get rid of this, do it in the icalls for Type
mono_class_init (klass);
#ifdef HAVE_SGEN_GC
res = (MonoReflectionType *)mono_gc_alloc_pinned_obj (mono_class_vtable (domain, mono_defaults.monotype_class), mono_class_instance_size (mono_defaults.monotype_class));
#else
res = (MonoReflectionType *)mono_object_new (domain, mono_defaults.monotype_class);
#endif
res->type = type;
mono_g_hash_table_insert (domain->type_hash, type, res);
if (type->type == MONO_TYPE_VOID)
domain->typeof_void = (MonoObject*)res;
mono_domain_unlock (domain);
mono_loader_unlock ();
return res;
}
/*
* mono_method_get_object:
* @domain: an app domain
* @method: a method
* @refclass: the reflected type (can be NULL)
*
* Return an System.Reflection.MonoMethod object representing the method @method.
*/
MonoReflectionMethod*
mono_method_get_object (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
/*
* We use the same C representation for methods and constructors, but the type
* name in C# is different.
*/
static MonoClass *System_Reflection_MonoMethod = NULL;
static MonoClass *System_Reflection_MonoCMethod = NULL;
static MonoClass *System_Reflection_MonoGenericMethod = NULL;
static MonoClass *System_Reflection_MonoGenericCMethod = NULL;
MonoClass *klass;
MonoReflectionMethod *ret;
if (method->is_inflated) {
MonoReflectionGenericMethod *gret;
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if ((*method->name == '.') && (!strcmp (method->name, ".ctor") || !strcmp (method->name, ".cctor"))) {
if (!System_Reflection_MonoGenericCMethod)
System_Reflection_MonoGenericCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericCMethod");
klass = System_Reflection_MonoGenericCMethod;
} else {
if (!System_Reflection_MonoGenericMethod)
System_Reflection_MonoGenericMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoGenericMethod");
klass = System_Reflection_MonoGenericMethod;
}
gret = (MonoReflectionGenericMethod*)mono_object_new (domain, klass);
gret->method.method = method;
MONO_OBJECT_SETREF (gret, method.name, mono_string_new (domain, method->name));
MONO_OBJECT_SETREF (gret, method.reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, (MonoReflectionMethod*)gret, refclass);
}
if (!refclass)
refclass = method->klass;
CHECK_OBJECT (MonoReflectionMethod *, method, refclass);
if (*method->name == '.' && (strcmp (method->name, ".ctor") == 0 || strcmp (method->name, ".cctor") == 0)) {
if (!System_Reflection_MonoCMethod)
System_Reflection_MonoCMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoCMethod");
klass = System_Reflection_MonoCMethod;
}
else {
if (!System_Reflection_MonoMethod)
System_Reflection_MonoMethod = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoMethod");
klass = System_Reflection_MonoMethod;
}
ret = (MonoReflectionMethod*)mono_object_new (domain, klass);
ret->method = method;
MONO_OBJECT_SETREF (ret, reftype, mono_type_get_object (domain, &refclass->byval_arg));
CACHE_OBJECT (MonoReflectionMethod *, method, ret, refclass);
}
/*
* mono_method_clear_object:
*
* Clear the cached reflection objects for the dynamic method METHOD.
*/
void
mono_method_clear_object (MonoDomain *domain, MonoMethod *method)
{
MonoClass *klass;
g_assert (method->dynamic);
klass = method->klass;
while (klass) {
clear_cached_object (domain, method, klass);
klass = klass->parent;
}
/* Added by mono_param_get_objects () */
clear_cached_object (domain, &(method->signature), NULL);
klass = method->klass;
while (klass) {
clear_cached_object (domain, &(method->signature), klass);
klass = klass->parent;
}
}
/*
* mono_field_get_object:
* @domain: an app domain
* @klass: a type
* @field: a field
*
* Return an System.Reflection.MonoField object representing the field @field
* in class @klass.
*/
MonoReflectionField*
mono_field_get_object (MonoDomain *domain, MonoClass *klass, MonoClassField *field)
{
MonoReflectionField *res;
static MonoClass *monofield_klass;
CHECK_OBJECT (MonoReflectionField *, field, klass);
if (!monofield_klass)
monofield_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoField");
res = (MonoReflectionField *)mono_object_new (domain, monofield_klass);
res->klass = klass;
res->field = field;
MONO_OBJECT_SETREF (res, name, mono_string_new (domain, mono_field_get_name (field)));
if (is_field_on_inst (field))
res->attrs = get_field_on_inst_generic_type (field)->attrs;
else
res->attrs = field->type->attrs;
MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type));
CACHE_OBJECT (MonoReflectionField *, field, res, klass);
}
/*
* mono_property_get_object:
* @domain: an app domain
* @klass: a type
* @property: a property
*
* Return an System.Reflection.MonoProperty object representing the property @property
* in class @klass.
*/
MonoReflectionProperty*
mono_property_get_object (MonoDomain *domain, MonoClass *klass, MonoProperty *property)
{
MonoReflectionProperty *res;
static MonoClass *monoproperty_klass;
CHECK_OBJECT (MonoReflectionProperty *, property, klass);
if (!monoproperty_klass)
monoproperty_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoProperty");
res = (MonoReflectionProperty *)mono_object_new (domain, monoproperty_klass);
res->klass = klass;
res->property = property;
CACHE_OBJECT (MonoReflectionProperty *, property, res, klass);
}
/*
* mono_event_get_object:
* @domain: an app domain
* @klass: a type
* @event: a event
*
* Return an System.Reflection.MonoEvent object representing the event @event
* in class @klass.
*/
MonoReflectionEvent*
mono_event_get_object (MonoDomain *domain, MonoClass *klass, MonoEvent *event)
{
MonoReflectionEvent *res;
MonoReflectionMonoEvent *mono_event;
static MonoClass *monoevent_klass;
CHECK_OBJECT (MonoReflectionEvent *, event, klass);
if (!monoevent_klass)
monoevent_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MonoEvent");
mono_event = (MonoReflectionMonoEvent *)mono_object_new (domain, monoevent_klass);
mono_event->klass = klass;
mono_event->event = event;
res = (MonoReflectionEvent*)mono_event;
CACHE_OBJECT (MonoReflectionEvent *, event, res, klass);
}
/**
* mono_get_reflection_missing_object:
* @domain: Domain where the object lives
*
* Returns the System.Reflection.Missing.Value singleton object
* (of type System.Reflection.Missing).
*
* Used as the value for ParameterInfo.DefaultValue when Optional
* is present
*/
static MonoObject *
mono_get_reflection_missing_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *missing_value_field = NULL;
if (!missing_value_field) {
MonoClass *missing_klass;
missing_klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "Missing");
mono_class_init (missing_klass);
missing_value_field = mono_class_get_field_from_name (missing_klass, "Value");
g_assert (missing_value_field);
}
obj = mono_field_get_value_object (domain, missing_value_field, NULL);
g_assert (obj);
return obj;
}
static MonoObject*
get_dbnull (MonoDomain *domain, MonoObject **dbnull)
{
if (!*dbnull)
*dbnull = mono_get_dbnull_object (domain);
return *dbnull;
}
static MonoObject*
get_reflection_missing (MonoDomain *domain, MonoObject **reflection_missing)
{
if (!*reflection_missing)
*reflection_missing = mono_get_reflection_missing_object (domain);
return *reflection_missing;
}
/*
* mono_param_get_objects:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.ParameterInfo array object representing the parameters
* in the method @method.
*/
MonoArray*
mono_param_get_objects_internal (MonoDomain *domain, MonoMethod *method, MonoClass *refclass)
{
static MonoClass *System_Reflection_ParameterInfo;
static MonoClass *System_Reflection_ParameterInfo_array;
MonoArray *res = NULL;
MonoReflectionMethod *member = NULL;
MonoReflectionParameter *param = NULL;
char **names, **blobs = NULL;
guint32 *types = NULL;
MonoType *type = NULL;
MonoObject *dbnull = NULL;
MonoObject *missing = NULL;
MonoMarshalSpec **mspecs;
MonoMethodSignature *sig;
MonoVTable *pinfo_vtable;
int i;
if (!System_Reflection_ParameterInfo_array) {
MonoClass *klass;
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ParameterInfo");
mono_memory_barrier ();
System_Reflection_ParameterInfo = klass;
klass = mono_array_class_get (klass, 1);
mono_memory_barrier ();
System_Reflection_ParameterInfo_array = klass;
}
if (!mono_method_signature (method)->param_count)
return mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), 0);
/* Note: the cache is based on the address of the signature into the method
* since we already cache MethodInfos with the method as keys.
*/
CHECK_OBJECT (MonoArray*, &(method->signature), refclass);
sig = mono_method_signature (method);
member = mono_method_get_object (domain, method, refclass);
names = g_new (char *, sig->param_count);
mono_method_get_param_names (method, (const char **) names);
mspecs = g_new (MonoMarshalSpec*, sig->param_count + 1);
mono_method_get_marshal_info (method, mspecs);
res = mono_array_new_specific (mono_class_vtable (domain, System_Reflection_ParameterInfo_array), sig->param_count);
pinfo_vtable = mono_class_vtable (domain, System_Reflection_ParameterInfo);
for (i = 0; i < sig->param_count; ++i) {
param = (MonoReflectionParameter *)mono_object_new_specific (pinfo_vtable);
MONO_OBJECT_SETREF (param, ClassImpl, mono_type_get_object (domain, sig->params [i]));
MONO_OBJECT_SETREF (param, MemberImpl, (MonoObject*)member);
MONO_OBJECT_SETREF (param, NameImpl, mono_string_new (domain, names [i]));
param->PositionImpl = i;
param->AttrsImpl = sig->params [i]->attrs;
if (!(param->AttrsImpl & PARAM_ATTRIBUTE_HAS_DEFAULT)) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
} else {
if (!blobs) {
blobs = g_new0 (char *, sig->param_count);
types = g_new0 (guint32, sig->param_count);
get_default_param_value_blobs (method, blobs, types);
}
/* Build MonoType for the type from the Constant Table */
if (!type)
type = g_new0 (MonoType, 1);
type->type = types [i];
type->data.klass = NULL;
if (types [i] == MONO_TYPE_CLASS)
type->data.klass = mono_defaults.object_class;
else if ((sig->params [i]->type == MONO_TYPE_VALUETYPE) && sig->params [i]->data.klass->enumtype) {
/* For enums, types [i] contains the base type */
type->type = MONO_TYPE_VALUETYPE;
type->data.klass = mono_class_from_mono_type (sig->params [i]);
} else
type->data.klass = mono_class_from_mono_type (type);
MONO_OBJECT_SETREF (param, DefaultValueImpl, mono_get_object_from_blob (domain, type, blobs [i]));
/* Type in the Constant table is MONO_TYPE_CLASS for nulls */
if (types [i] != MONO_TYPE_CLASS && !param->DefaultValueImpl) {
if (param->AttrsImpl & PARAM_ATTRIBUTE_OPTIONAL)
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_reflection_missing (domain, &missing));
else
MONO_OBJECT_SETREF (param, DefaultValueImpl, get_dbnull (domain, &dbnull));
}
}
if (mspecs [i + 1])
MONO_OBJECT_SETREF (param, MarshalAsImpl, (MonoObject*)mono_reflection_marshal_from_marshal_spec (domain, method->klass, mspecs [i + 1]));
mono_array_setref (res, i, param);
}
g_free (names);
g_free (blobs);
g_free (types);
g_free (type);
for (i = mono_method_signature (method)->param_count; i >= 0; i--)
if (mspecs [i])
mono_metadata_free_marshal_spec (mspecs [i]);
g_free (mspecs);
CACHE_OBJECT (MonoArray *, &(method->signature), res, refclass);
}
MonoArray*
mono_param_get_objects (MonoDomain *domain, MonoMethod *method)
{
return mono_param_get_objects_internal (domain, method, NULL);
}
/*
* mono_method_body_get_object:
* @domain: an app domain
* @method: a method
*
* Return an System.Reflection.MethodBody object representing the method @method.
*/
MonoReflectionMethodBody*
mono_method_body_get_object (MonoDomain *domain, MonoMethod *method)
{
static MonoClass *System_Reflection_MethodBody = NULL;
static MonoClass *System_Reflection_LocalVariableInfo = NULL;
static MonoClass *System_Reflection_ExceptionHandlingClause = NULL;
MonoReflectionMethodBody *ret;
MonoMethodNormal *mn;
MonoMethodHeader *header;
MonoImage *image;
guint32 method_rva, local_var_sig_token;
char *ptr;
unsigned char format, flags;
int i;
if (!System_Reflection_MethodBody)
System_Reflection_MethodBody = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "MethodBody");
if (!System_Reflection_LocalVariableInfo)
System_Reflection_LocalVariableInfo = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "LocalVariableInfo");
if (!System_Reflection_ExceptionHandlingClause)
System_Reflection_ExceptionHandlingClause = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "ExceptionHandlingClause");
CHECK_OBJECT (MonoReflectionMethodBody *, method, NULL);
if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
(method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME))
return NULL;
mn = (MonoMethodNormal *)method;
image = method->klass->image;
header = mono_method_get_header (method);
if (!image->dynamic) {
/* Obtain local vars signature token */
method_rva = mono_metadata_decode_row_col (&image->tables [MONO_TABLE_METHOD], mono_metadata_token_index (method->token) - 1, MONO_METHOD_RVA);
ptr = mono_image_rva_map (image, method_rva);
flags = *(const unsigned char *) ptr;
format = flags & METHOD_HEADER_FORMAT_MASK;
switch (format){
case METHOD_HEADER_TINY_FORMAT:
local_var_sig_token = 0;
break;
case METHOD_HEADER_FAT_FORMAT:
ptr += 2;
ptr += 2;
ptr += 4;
local_var_sig_token = read32 (ptr);
break;
default:
g_assert_not_reached ();
}
} else
local_var_sig_token = 0; //FIXME
ret = (MonoReflectionMethodBody*)mono_object_new (domain, System_Reflection_MethodBody);
ret->init_locals = header->init_locals;
ret->max_stack = header->max_stack;
ret->local_var_sig_token = local_var_sig_token;
MONO_OBJECT_SETREF (ret, il, mono_array_new_cached (domain, mono_defaults.byte_class, header->code_size));
memcpy (mono_array_addr (ret->il, guint8, 0), header->code, header->code_size);
/* Locals */
MONO_OBJECT_SETREF (ret, locals, mono_array_new_cached (domain, System_Reflection_LocalVariableInfo, header->num_locals));
for (i = 0; i < header->num_locals; ++i) {
MonoReflectionLocalVariableInfo *info = (MonoReflectionLocalVariableInfo*)mono_object_new (domain, System_Reflection_LocalVariableInfo);
MONO_OBJECT_SETREF (info, local_type, mono_type_get_object (domain, header->locals [i]));
info->is_pinned = header->locals [i]->pinned;
info->local_index = i;
mono_array_setref (ret->locals, i, info);
}
/* Exceptions */
MONO_OBJECT_SETREF (ret, clauses, mono_array_new_cached (domain, System_Reflection_ExceptionHandlingClause, header->num_clauses));
for (i = 0; i < header->num_clauses; ++i) {
MonoReflectionExceptionHandlingClause *info = (MonoReflectionExceptionHandlingClause*)mono_object_new (domain, System_Reflection_ExceptionHandlingClause);
MonoExceptionClause *clause = &header->clauses [i];
info->flags = clause->flags;
info->try_offset = clause->try_offset;
info->try_length = clause->try_len;
info->handler_offset = clause->handler_offset;
info->handler_length = clause->handler_len;
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
info->filter_offset = clause->data.filter_offset;
else if (clause->data.catch_class)
MONO_OBJECT_SETREF (info, catch_type, mono_type_get_object (mono_domain_get (), &clause->data.catch_class->byval_arg));
mono_array_setref (ret->clauses, i, info);
}
CACHE_OBJECT (MonoReflectionMethodBody *, method, ret, NULL);
return ret;
}
/**
* mono_get_dbnull_object:
* @domain: Domain where the object lives
*
* Returns the System.DBNull.Value singleton object
*
* Used as the value for ParameterInfo.DefaultValue
*/
MonoObject *
mono_get_dbnull_object (MonoDomain *domain)
{
MonoObject *obj;
static MonoClassField *dbnull_value_field = NULL;
if (!dbnull_value_field) {
MonoClass *dbnull_klass;
dbnull_klass = mono_class_from_name (mono_defaults.corlib, "System", "DBNull");
mono_class_init (dbnull_klass);
dbnull_value_field = mono_class_get_field_from_name (dbnull_klass, "Value");
g_assert (dbnull_value_field);
}
obj = mono_field_get_value_object (domain, dbnull_value_field, NULL);
g_assert (obj);
return obj;
}
static void
get_default_param_value_blobs (MonoMethod *method, char **blobs, guint32 *types)
{
guint32 param_index, i, lastp, crow = 0;
guint32 param_cols [MONO_PARAM_SIZE], const_cols [MONO_CONSTANT_SIZE];
gint32 idx;
MonoClass *klass = method->klass;
MonoImage *image = klass->image;
MonoMethodSignature *methodsig = mono_method_signature (method);
MonoTableInfo *constt;
MonoTableInfo *methodt;
MonoTableInfo *paramt;
if (!methodsig->param_count)
return;
mono_class_init (klass);
if (klass->image->dynamic) {
MonoReflectionMethodAux *aux;
if (method->is_inflated)
method = ((MonoMethodInflated*)method)->declaring;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (aux && aux->param_defaults) {
memcpy (blobs, &(aux->param_defaults [1]), methodsig->param_count * sizeof (char*));
memcpy (types, &(aux->param_default_types [1]), methodsig->param_count * sizeof (guint32));
}
return;
}
methodt = &klass->image->tables [MONO_TABLE_METHOD];
paramt = &klass->image->tables [MONO_TABLE_PARAM];
constt = &image->tables [MONO_TABLE_CONSTANT];
idx = mono_method_get_index (method) - 1;
g_assert (idx != -1);
param_index = mono_metadata_decode_row_col (methodt, idx, MONO_METHOD_PARAMLIST);
if (idx + 1 < methodt->rows)
lastp = mono_metadata_decode_row_col (methodt, idx + 1, MONO_METHOD_PARAMLIST);
else
lastp = paramt->rows + 1;
for (i = param_index; i < lastp; ++i) {
guint32 paramseq;
mono_metadata_decode_row (paramt, i - 1, param_cols, MONO_PARAM_SIZE);
paramseq = param_cols [MONO_PARAM_SEQUENCE];
if (!(param_cols [MONO_PARAM_FLAGS] & PARAM_ATTRIBUTE_HAS_DEFAULT))
continue;
crow = mono_metadata_get_constant_index (image, MONO_TOKEN_PARAM_DEF | i, crow + 1);
if (!crow) {
continue;
}
mono_metadata_decode_row (constt, crow - 1, const_cols, MONO_CONSTANT_SIZE);
blobs [paramseq - 1] = (gpointer) mono_metadata_blob_heap (image, const_cols [MONO_CONSTANT_VALUE]);
types [paramseq - 1] = const_cols [MONO_CONSTANT_TYPE];
}
return;
}
static MonoObject *
mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob)
{
void *retval;
MonoClass *klass;
MonoObject *object;
MonoType *basetype = type;
if (!blob)
return NULL;
klass = mono_class_from_mono_type (type);
if (klass->valuetype) {
object = mono_object_new (domain, klass);
retval = ((gchar *) object + sizeof (MonoObject));
if (klass->enumtype)
basetype = mono_class_enum_basetype (klass);
} else {
retval = &object;
}
if (!mono_get_constant_value_from_blob (domain, basetype->type, blob, retval))
return object;
else
return NULL;
}
static int
assembly_name_to_aname (MonoAssemblyName *assembly, char *p) {
int found_sep;
char *s;
memset (assembly, 0, sizeof (MonoAssemblyName));
assembly->name = p;
assembly->culture = "";
memset (assembly->public_key_token, 0, MONO_PUBLIC_KEY_TOKEN_LENGTH);
while (*p && (isalnum (*p) || *p == '.' || *p == '-' || *p == '_' || *p == '$' || *p == '@'))
p++;
found_sep = 0;
while (g_ascii_isspace (*p) || *p == ',') {
*p++ = 0;
found_sep = 1;
continue;
}
/* failed */
if (!found_sep)
return 1;
while (*p) {
if (*p == 'V' && g_ascii_strncasecmp (p, "Version=", 8) == 0) {
p += 8;
assembly->major = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->minor = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->build = strtoul (p, &s, 10);
if (s == p || *s != '.')
return 1;
p = ++s;
assembly->revision = strtoul (p, &s, 10);
if (s == p)
return 1;
p = s;
} else if (*p == 'C' && g_ascii_strncasecmp (p, "Culture=", 8) == 0) {
p += 8;
if (g_ascii_strncasecmp (p, "neutral", 7) == 0) {
assembly->culture = "";
p += 7;
} else {
assembly->culture = p;
while (*p && *p != ',') {
p++;
}
}
} else if (*p == 'P' && g_ascii_strncasecmp (p, "PublicKeyToken=", 15) == 0) {
p += 15;
if (strncmp (p, "null", 4) == 0) {
p += 4;
} else {
int len;
gchar *start = p;
while (*p && *p != ',') {
p++;
}
len = (p - start + 1);
if (len > MONO_PUBLIC_KEY_TOKEN_LENGTH)
len = MONO_PUBLIC_KEY_TOKEN_LENGTH;
g_strlcpy ((char*)assembly->public_key_token, start, len);
}
} else {
while (*p && *p != ',')
p++;
}
found_sep = 0;
while (g_ascii_isspace (*p) || *p == ',') {
*p++ = 0;
found_sep = 1;
continue;
}
/* failed */
if (!found_sep)
return 1;
}
return 0;
}
/*
* mono_reflection_parse_type:
* @name: type name
*
* Parse a type name as accepted by the GetType () method and output the info
* extracted in the info structure.
* the name param will be mangled, so, make a copy before passing it to this function.
* The fields in info will be valid until the memory pointed to by name is valid.
*
* See also mono_type_get_name () below.
*
* Returns: 0 on parse error.
*/
static int
_mono_reflection_parse_type (char *name, char **endptr, gboolean is_recursed,
MonoTypeNameParse *info)
{
char *start, *p, *w, *temp, *last_point, *startn;
int in_modifiers = 0;
int isbyref = 0, rank, arity = 0, i;
start = p = w = name;
//FIXME could we just zero the whole struct? memset (&info, 0, sizeof (MonoTypeNameParse))
memset (&info->assembly, 0, sizeof (MonoAssemblyName));
info->name = info->name_space = NULL;
info->nested = NULL;
info->modifiers = NULL;
info->type_arguments = NULL;
/* last_point separates the namespace from the name */
last_point = NULL;
/* Skips spaces */
while (*p == ' ') p++, start++, w++, name++;
while (*p) {
switch (*p) {
case '+':
*p = 0; /* NULL terminate the name */
startn = p + 1;
info->nested = g_list_append (info->nested, startn);
/* we have parsed the nesting namespace + name */
if (info->name)
break;
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
break;
case '.':
last_point = p;
break;
case '\\':
++p;
break;
case '&':
case '*':
case '[':
case ',':
case ']':
in_modifiers = 1;
break;
case '`':
++p;
i = strtol (p, &temp, 10);
arity += i;
if (p == temp)
return 0;
p = temp-1;
break;
default:
break;
}
if (in_modifiers)
break;
// *w++ = *p++;
p++;
}
if (!info->name) {
if (last_point) {
info->name_space = start;
*last_point = 0;
info->name = last_point + 1;
} else {
info->name_space = (char *)"";
info->name = start;
}
}
while (*p) {
switch (*p) {
case '&':
if (isbyref) /* only one level allowed by the spec */
return 0;
isbyref = 1;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (0));
*p++ = 0;
break;
case '*':
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-1));
*p++ = 0;
break;
case '[':
if (arity != 0) {
*p++ = 0;
info->type_arguments = g_ptr_array_new ();
for (i = 0; i < arity; i++) {
MonoTypeNameParse *subinfo = g_new0 (MonoTypeNameParse, 1);
gboolean fqname = FALSE;
g_ptr_array_add (info->type_arguments, subinfo);
if (*p == '[') {
p++;
fqname = TRUE;
}
if (!_mono_reflection_parse_type (p, &p, TRUE, subinfo))
return 0;
/*MS is lenient on [] delimited parameters that aren't fqn - and F# uses them.*/
if (fqname && (*p != ']')) {
char *aname;
if (*p != ',')
return 0;
*p++ = 0;
aname = p;
while (*p && (*p != ']'))
p++;
if (*p != ']')
return 0;
*p++ = 0;
while (*aname) {
if (g_ascii_isspace (*aname)) {
++aname;
continue;
}
break;
}
if (!*aname ||
!assembly_name_to_aname (&subinfo->assembly, aname))
return 0;
} else if (fqname && (*p == ']')) {
*p++ = 0;
}
if (i + 1 < arity) {
if (*p != ',')
return 0;
} else {
if (*p != ']')
return 0;
}
*p++ = 0;
}
arity = 0;
break;
}
rank = 1;
*p++ = 0;
while (*p) {
if (*p == ']')
break;
if (*p == ',')
rank++;
else if (*p == '*') /* '*' means unknown lower bound */
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (-2));
else
return 0;
++p;
}
if (*p++ != ']')
return 0;
info->modifiers = g_list_append (info->modifiers, GUINT_TO_POINTER (rank));
break;
case ']':
if (is_recursed)
goto end;
return 0;
case ',':
if (is_recursed)
goto end;
*p++ = 0;
while (*p) {
if (g_ascii_isspace (*p)) {
++p;
continue;
}
break;
}
if (!*p)
return 0; /* missing assembly name */
if (!assembly_name_to_aname (&info->assembly, p))
return 0;
break;
default:
return 0;
}
if (info->assembly.name)
break;
}
// *w = 0; /* terminate class name */
end:
if (!info->name || !*info->name)
return 0;
if (endptr)
*endptr = p;
/* add other consistency checks */
return 1;
}
int
mono_reflection_parse_type (char *name, MonoTypeNameParse *info)
{
return _mono_reflection_parse_type (name, NULL, FALSE, info);
}
static MonoType*
_mono_reflection_get_type_from_info (MonoTypeNameParse *info, MonoImage *image, gboolean ignorecase)
{
gboolean type_resolve = FALSE;
MonoType *type;
MonoImage *rootimage = image;
if (info->assembly.name) {
MonoAssembly *assembly = mono_assembly_loaded (&info->assembly);
if (!assembly && image && image->assembly && mono_assembly_names_equal (&info->assembly, &image->assembly->aname))
/*
* This could happen in the AOT compiler case when the search hook is not
* installed.
*/
assembly = image->assembly;
if (!assembly) {
/* then we must load the assembly ourselve - see #60439 */
assembly = mono_assembly_load (&info->assembly, NULL, NULL);
if (!assembly)
return NULL;
}
image = assembly->image;
} else if (!image) {
image = mono_defaults.corlib;
}
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
if (type == NULL && !info->assembly.name && image != mono_defaults.corlib) {
image = mono_defaults.corlib;
type = mono_reflection_get_type_with_rootimage (rootimage, image, info, ignorecase, &type_resolve);
}
return type;
}
static MonoType*
mono_reflection_get_type_internal (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoClass *klass;
GList *mod;
int modval;
gboolean bounded = FALSE;
if (!image)
image = mono_defaults.corlib;
if (ignorecase)
klass = mono_class_from_name_case (image, info->name_space, info->name);
else
klass = mono_class_from_name (image, info->name_space, info->name);
if (!klass)
return NULL;
for (mod = info->nested; mod; mod = mod->next) {
gpointer iter = NULL;
MonoClass *parent;
parent = klass;
mono_class_init (parent);
while ((klass = mono_class_get_nested_types (parent, &iter))) {
if (ignorecase) {
if (mono_utf8_strcasecmp (klass->name, mod->data) == 0)
break;
} else {
if (strcmp (klass->name, mod->data) == 0)
break;
}
}
if (!klass)
break;
}
if (!klass)
return NULL;
mono_class_init (klass);
if (info->type_arguments) {
MonoType **type_args = g_new0 (MonoType *, info->type_arguments->len);
MonoReflectionType *the_type;
MonoType *instance;
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
type_args [i] = _mono_reflection_get_type_from_info (subinfo, rootimage, ignorecase);
if (!type_args [i]) {
g_free (type_args);
return NULL;
}
}
the_type = mono_type_get_object (mono_domain_get (), &klass->byval_arg);
instance = mono_reflection_bind_generic_parameters (
the_type, info->type_arguments->len, type_args);
g_free (type_args);
if (!instance)
return NULL;
klass = mono_class_from_mono_type (instance);
}
for (mod = info->modifiers; mod; mod = mod->next) {
modval = GPOINTER_TO_UINT (mod->data);
if (!modval) { /* byref: must be last modifier */
return &klass->this_arg;
} else if (modval == -1) {
klass = mono_ptr_class_get (&klass->byval_arg);
} else if (modval == -2) {
bounded = TRUE;
} else { /* array rank */
klass = mono_bounded_array_class_get (klass, modval, bounded);
}
mono_class_init (klass);
}
return &klass->byval_arg;
}
/*
* mono_reflection_get_type:
* @image: a metadata context
* @info: type description structure
* @ignorecase: flag for case-insensitive string compares
* @type_resolve: whenever type resolve was already tried
*
* Build a MonoType from the type description in @info.
*
*/
MonoType*
mono_reflection_get_type (MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve) {
return mono_reflection_get_type_with_rootimage(image, image, info, ignorecase, type_resolve);
}
static MonoType*
mono_reflection_get_type_internal_dynamic (MonoImage *rootimage, MonoAssembly *assembly, MonoTypeNameParse *info, gboolean ignorecase)
{
MonoReflectionAssemblyBuilder *abuilder;
MonoType *type;
int i;
g_assert (assembly->dynamic);
abuilder = (MonoReflectionAssemblyBuilder*)mono_assembly_get_object (((MonoDynamicAssembly*)assembly)->domain, assembly);
/* Enumerate all modules */
type = NULL;
if (abuilder->modules) {
for (i = 0; i < mono_array_length (abuilder->modules); ++i) {
MonoReflectionModuleBuilder *mb = mono_array_get (abuilder->modules, MonoReflectionModuleBuilder*, i);
type = mono_reflection_get_type_internal (rootimage, &mb->dynamic_image->image, info, ignorecase);
if (type)
break;
}
}
if (!type && abuilder->loaded_modules) {
for (i = 0; i < mono_array_length (abuilder->loaded_modules); ++i) {
MonoReflectionModule *mod = mono_array_get (abuilder->loaded_modules, MonoReflectionModule*, i);
type = mono_reflection_get_type_internal (rootimage, mod->image, info, ignorecase);
if (type)
break;
}
}
return type;
}
MonoType*
mono_reflection_get_type_with_rootimage (MonoImage *rootimage, MonoImage* image, MonoTypeNameParse *info, gboolean ignorecase, gboolean *type_resolve)
{
MonoType *type;
MonoReflectionAssembly *assembly;
GString *fullName;
GList *mod;
if (image && image->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, image->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, image, info, ignorecase);
if (type)
return type;
if (!mono_domain_has_type_resolve (mono_domain_get ()))
return NULL;
if (type_resolve) {
if (*type_resolve)
return NULL;
else
*type_resolve = TRUE;
}
/* Reconstruct the type name */
fullName = g_string_new ("");
if (info->name_space && (info->name_space [0] != '\0'))
g_string_printf (fullName, "%s.%s", info->name_space, info->name);
else
g_string_printf (fullName, "%s", info->name);
for (mod = info->nested; mod; mod = mod->next)
g_string_append_printf (fullName, "+%s", (char*)mod->data);
assembly = mono_domain_try_type_resolve ( mono_domain_get (), fullName->str, NULL);
if (assembly) {
if (assembly->assembly->dynamic)
type = mono_reflection_get_type_internal_dynamic (rootimage, assembly->assembly, info, ignorecase);
else
type = mono_reflection_get_type_internal (rootimage, assembly->assembly->image,
info, ignorecase);
}
g_string_free (fullName, TRUE);
return type;
}
void
mono_reflection_free_type_info (MonoTypeNameParse *info)
{
g_list_free (info->modifiers);
g_list_free (info->nested);
if (info->type_arguments) {
int i;
for (i = 0; i < info->type_arguments->len; i++) {
MonoTypeNameParse *subinfo = g_ptr_array_index (info->type_arguments, i);
mono_reflection_free_type_info (subinfo);
/*We free the subinfo since it is allocated by _mono_reflection_parse_type*/
g_free (subinfo);
}
g_ptr_array_free (info->type_arguments, TRUE);
}
}
/*
* mono_reflection_type_from_name:
* @name: type name.
* @image: a metadata context (can be NULL).
*
* Retrieves a MonoType from its @name. If the name is not fully qualified,
* it defaults to get the type from @image or, if @image is NULL or loading
* from it fails, uses corlib.
*
*/
MonoType*
mono_reflection_type_from_name (char *name, MonoImage *image)
{
MonoType *type = NULL;
MonoTypeNameParse info;
char *tmp;
/* Make a copy since parse_type modifies its argument */
tmp = g_strdup (name);
/*g_print ("requested type %s\n", str);*/
if (mono_reflection_parse_type (tmp, &info)) {
type = _mono_reflection_get_type_from_info (&info, image, FALSE);
}
g_free (tmp);
mono_reflection_free_type_info (&info);
return type;
}
/*
* mono_reflection_get_token:
*
* Return the metadata token of OBJ which should be an object
* representing a metadata element.
*/
guint32
mono_reflection_get_token (MonoObject *obj)
{
MonoClass *klass;
guint32 token = 0;
klass = obj->vtable->klass;
if (strcmp (klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *mb = (MonoReflectionCtorBuilder *)obj;
token = mb->table_idx | MONO_TOKEN_METHOD_DEF;
} else if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)obj;
/* Call mono_image_create_token so the object gets added to the tokens hash table */
token = mono_image_create_token (((MonoReflectionTypeBuilder*)fb->typeb)->module->dynamic_image, obj, FALSE, TRUE);
} else if (strcmp (klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)obj;
token = tb->table_idx | MONO_TOKEN_TYPE_DEF;
} else if (strcmp (klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
token = mono_class_from_mono_type (type)->type_token;
} else if (strcmp (klass->name, "MonoCMethod") == 0 ||
strcmp (klass->name, "MonoMethod") == 0 ||
strcmp (klass->name, "MonoGenericMethod") == 0 ||
strcmp (klass->name, "MonoGenericCMethod") == 0) {
MonoReflectionMethod *m = (MonoReflectionMethod *)obj;
if (m->method->is_inflated) {
MonoMethodInflated *inflated = (MonoMethodInflated *) m->method;
return inflated->declaring->token;
} else {
token = m->method->token;
}
} else if (strcmp (klass->name, "MonoField") == 0) {
MonoReflectionField *f = (MonoReflectionField*)obj;
if (is_field_on_inst (f->field)) {
MonoDynamicGenericClass *dgclass = (MonoDynamicGenericClass*)f->field->parent->generic_class;
int field_index = f->field - dgclass->fields;
MonoObject *obj;
g_assert (field_index >= 0 && field_index < dgclass->count_fields);
obj = dgclass->field_objects [field_index];
return mono_reflection_get_token (obj);
}
token = mono_class_get_field_token (f->field);
} else if (strcmp (klass->name, "MonoProperty") == 0) {
MonoReflectionProperty *p = (MonoReflectionProperty*)obj;
token = mono_class_get_property_token (p->property);
} else if (strcmp (klass->name, "MonoEvent") == 0) {
MonoReflectionMonoEvent *p = (MonoReflectionMonoEvent*)obj;
token = mono_class_get_event_token (p->event);
} else if (strcmp (klass->name, "ParameterInfo") == 0) {
MonoReflectionParameter *p = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (p->MemberImpl);
g_assert (mono_class_is_reflection_method_or_constructor (member_class));
token = mono_method_get_param_token (((MonoReflectionMethod*)p->MemberImpl)->method, p->PositionImpl);
} else if (strcmp (klass->name, "Module") == 0) {
MonoReflectionModule *m = (MonoReflectionModule*)obj;
token = m->token;
} else if (strcmp (klass->name, "Assembly") == 0) {
token = mono_metadata_make_token (MONO_TABLE_ASSEMBLY, 1);
} else {
gchar *msg = g_strdup_printf ("MetadataToken is not supported for type '%s.%s'", klass->name_space, klass->name);
MonoException *ex = mono_get_exception_not_implemented (msg);
g_free (msg);
mono_raise_exception (ex);
}
return token;
}
static void*
load_cattr_value (MonoImage *image, MonoType *t, const char *p, const char **end)
{
int slen, type = t->type;
MonoClass *tklass = t->data.klass;
handle_enum:
switch (type) {
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN: {
MonoBoolean *bval = g_malloc (sizeof (MonoBoolean));
*bval = *p;
*end = p + 1;
return bval;
}
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2: {
guint16 *val = g_malloc (sizeof (guint16));
*val = read16 (p);
*end = p + 2;
return val;
}
#if SIZEOF_VOID_P == 4
case MONO_TYPE_U:
case MONO_TYPE_I:
#endif
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4: {
guint32 *val = g_malloc (sizeof (guint32));
*val = read32 (p);
*end = p + 4;
return val;
}
#if SIZEOF_VOID_P == 8
case MONO_TYPE_U: /* error out instead? this should probably not happen */
case MONO_TYPE_I:
#endif
case MONO_TYPE_U8:
case MONO_TYPE_I8: {
guint64 *val = g_malloc (sizeof (guint64));
*val = read64 (p);
*end = p + 8;
return val;
}
case MONO_TYPE_R8: {
double *val = g_malloc (sizeof (double));
readr8 (p, val);
*end = p + 8;
return val;
}
case MONO_TYPE_VALUETYPE:
if (t->data.klass->enumtype) {
type = mono_class_enum_basetype (t->data.klass)->type;
goto handle_enum;
} else {
g_error ("generic valutype %s not handled in custom attr value decoding", t->data.klass->name);
}
break;
case MONO_TYPE_STRING:
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
slen = mono_metadata_decode_value (p, &p);
*end = p + slen;
return mono_string_new_len (mono_domain_get (), p, slen);
case MONO_TYPE_CLASS: {
char *n;
MonoType *t;
if (*p == (char)0xFF) {
*end = p + 1;
return NULL;
}
handle_type:
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_warning ("Cannot load type '%s'", n);
g_free (n);
*end = p + slen;
if (t)
return mono_type_get_object (mono_domain_get (), t);
else
return NULL;
}
case MONO_TYPE_OBJECT: {
char subt = *p++;
MonoObject *obj;
MonoClass *subc = NULL;
void *val;
if (subt == 0x50) {
goto handle_type;
} else if (subt == 0x0E) {
type = MONO_TYPE_STRING;
goto handle_enum;
} else if (subt == 0x1D) {
MonoType simple_type = {{0}};
int etype = *p;
p ++;
if (etype == 0x51)
/* See Partition II, Appendix B3 */
etype = MONO_TYPE_OBJECT;
type = MONO_TYPE_SZARRAY;
simple_type.type = etype;
tklass = mono_class_from_mono_type (&simple_type);
goto handle_enum;
} else if (subt == 0x55) {
char *n;
MonoType *t;
slen = mono_metadata_decode_value (p, &p);
n = g_memdup (p, slen + 1);
n [slen] = 0;
t = mono_reflection_type_from_name (n, image);
if (!t)
g_error ("Cannot load type '%s'", n);
g_free (n);
p += slen;
subc = mono_class_from_mono_type (t);
} else if (subt >= MONO_TYPE_BOOLEAN && subt <= MONO_TYPE_R8) {
MonoType simple_type = {{0}};
simple_type.type = subt;
subc = mono_class_from_mono_type (&simple_type);
} else {
g_error ("Unknown type 0x%02x for object type encoding in custom attr", subt);
}
val = load_cattr_value (image, &subc->byval_arg, p, end);
obj = mono_object_new (mono_domain_get (), subc);
memcpy ((char*)obj + sizeof (MonoObject), val, mono_class_value_size (subc, NULL));
g_free (val);
return obj;
}
case MONO_TYPE_SZARRAY: {
MonoArray *arr;
guint32 i, alen, basetype;
alen = read32 (p);
p += 4;
if (alen == 0xffffffff) {
*end = p;
return NULL;
}
arr = mono_array_new (mono_domain_get(), tklass, alen);
basetype = tklass->byval_arg.type;
if (basetype == MONO_TYPE_VALUETYPE && tklass->enumtype)
basetype = mono_class_enum_basetype (tklass)->type;
switch (basetype)
{
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_BOOLEAN:
for (i = 0; i < alen; i++) {
MonoBoolean val = *p++;
mono_array_set (arr, MonoBoolean, i, val);
}
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
for (i = 0; i < alen; i++) {
guint16 val = read16 (p);
mono_array_set (arr, guint16, i, val);
p += 2;
}
break;
case MONO_TYPE_R4:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
for (i = 0; i < alen; i++) {
guint32 val = read32 (p);
mono_array_set (arr, guint32, i, val);
p += 4;
}
break;
case MONO_TYPE_R8:
for (i = 0; i < alen; i++) {
double val;
readr8 (p, &val);
mono_array_set (arr, double, i, val);
p += 8;
}
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
for (i = 0; i < alen; i++) {
guint64 val = read64 (p);
mono_array_set (arr, guint64, i, val);
p += 8;
}
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_OBJECT:
case MONO_TYPE_STRING:
for (i = 0; i < alen; i++) {
MonoObject *item = load_cattr_value (image, &tklass->byval_arg, p, &p);
mono_array_setref (arr, i, item);
}
break;
default:
g_error ("Type 0x%02x not handled in custom attr array decoding", basetype);
}
*end=p;
return arr;
}
default:
g_error ("Type 0x%02x not handled in custom attr value decoding", type);
}
return NULL;
}
static MonoObject*
create_cattr_typed_arg (MonoType *t, MonoObject *val)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *params [2], *unboxed;
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeTypedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = mono_type_get_object (mono_domain_get (), t);
params [1] = val;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static MonoObject*
create_cattr_named_arg (void *minfo, MonoObject *typedarg)
{
static MonoClass *klass;
static MonoMethod *ctor;
MonoObject *retval;
void *unboxed, *params [2];
if (!klass)
klass = mono_class_from_name (mono_defaults.corlib, "System.Reflection", "CustomAttributeNamedArgument");
if (!ctor)
ctor = mono_class_get_method_from_name (klass, ".ctor", 2);
params [0] = minfo;
params [1] = typedarg;
retval = mono_object_new (mono_domain_get (), klass);
unboxed = mono_object_unbox (retval);
mono_runtime_invoke (ctor, unboxed, params, NULL);
return retval;
}
static gboolean
type_is_reference (MonoType *type)
{
switch (type->type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_CHAR:
case MONO_TYPE_U:
case MONO_TYPE_I:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_U8:
case MONO_TYPE_I8:
case MONO_TYPE_R8:
case MONO_TYPE_R4:
case MONO_TYPE_VALUETYPE:
return FALSE;
default:
return TRUE;
}
}
static void
free_param_data (MonoMethodSignature *sig, void **params) {
int i;
for (i = 0; i < sig->param_count; ++i) {
if (!type_is_reference (sig->params [i]))
g_free (params [i]);
}
}
/*
* Find the field index in the metadata FieldDef table.
*/
static guint32
find_field_index (MonoClass *klass, MonoClassField *field) {
int i;
for (i = 0; i < klass->field.count; ++i) {
if (field == &klass->fields [i])
return klass->field.first + 1 + i;
}
return 0;
}
/*
* Find the property index in the metadata Property table.
*/
static guint32
find_property_index (MonoClass *klass, MonoProperty *property) {
int i;
for (i = 0; i < klass->ext->property.count; ++i) {
if (property == &klass->ext->properties [i])
return klass->ext->property.first + 1 + i;
}
return 0;
}
/*
* Find the event index in the metadata Event table.
*/
static guint32
find_event_index (MonoClass *klass, MonoEvent *event) {
int i;
for (i = 0; i < klass->ext->event.count; ++i) {
if (event == &klass->ext->events [i])
return klass->ext->event.first + 1 + i;
}
return 0;
}
static MonoObject*
create_custom_attr (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len)
{
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
MonoObject *attr;
void *params_buf [32];
void **params;
MonoMethodSignature *sig;
mono_class_init (method->klass);
if (len == 0) {
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, NULL, NULL);
return attr;
}
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return NULL;
/*g_print ("got attr %s\n", method->klass->name);*/
sig = mono_method_signature (method);
if (sig->param_count < 32)
params = params_buf;
else
/* Allocate using GC so it gets GC tracking */
params = mono_gc_alloc_fixed (sig->param_count * sizeof (void*), NULL);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
params [i] = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
}
named = p;
attr = mono_object_new (mono_domain_get (), method->klass);
mono_runtime_invoke (method, attr, params, NULL);
free_param_data (method->signature, params);
num_named = read16 (named);
named += 2;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoClassField *field = mono_class_get_field_from_name (mono_object_class (attr), name);
void *val = load_cattr_value (image, field->type, named, &named);
mono_field_set_value (attr, field, val);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoProperty *prop;
void *pparams [1];
MonoType *prop_type;
prop = mono_class_get_property_from_name (mono_object_class (attr), name);
/* can we have more that 1 arg in a custom attr named property? */
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
pparams [0] = load_cattr_value (image, prop_type, named, &named);
mono_property_set_value (prop, attr, pparams, NULL);
if (!type_is_reference (prop_type))
g_free (pparams [0]);
}
g_free (name);
}
if (params != params_buf)
mono_gc_free_fixed (params);
return attr;
}
/*
* mono_reflection_create_custom_attr_data_args:
*
* Create an array of typed and named arguments from the cattr blob given by DATA.
* TYPED_ARGS and NAMED_ARGS will contain the objects representing the arguments,
* NAMED_ARG_INFO will contain information about the named arguments.
*/
void
mono_reflection_create_custom_attr_data_args (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len, MonoArray **typed_args, MonoArray **named_args, CattrNamedArg **named_arg_info)
{
MonoArray *typedargs, *namedargs;
MonoClass *attrklass;
MonoDomain *domain;
const char *p = (const char*)data;
const char *named;
guint32 i, j, num_named;
CattrNamedArg *arginfo = NULL;
mono_class_init (method->klass);
*typed_args = NULL;
*named_args = NULL;
*named_arg_info = NULL;
domain = mono_domain_get ();
if (len < 2 || read16 (p) != 0x0001) /* Prolog */
return;
typedargs = mono_array_new (domain, mono_get_object_class (), mono_method_signature (method)->param_count);
/* skip prolog */
p += 2;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj;
void *val;
val = load_cattr_value (image, mono_method_signature (method)->params [i], p, &p);
obj = type_is_reference (mono_method_signature (method)->params [i]) ?
val : mono_value_box (domain, mono_class_from_mono_type (mono_method_signature (method)->params [i]), val);
mono_array_setref (typedargs, i, obj);
if (!type_is_reference (mono_method_signature (method)->params [i]))
g_free (val);
}
named = p;
num_named = read16 (named);
namedargs = mono_array_new (domain, mono_get_object_class (), num_named);
named += 2;
attrklass = method->klass;
arginfo = g_new0 (CattrNamedArg, num_named);
*named_arg_info = arginfo;
for (j = 0; j < num_named; j++) {
gint name_len;
char *name, named_type, data_type;
named_type = *named++;
data_type = *named++; /* type of data */
if (data_type == MONO_TYPE_SZARRAY)
data_type = *named++;
if (data_type == MONO_TYPE_ENUM) {
gint type_len;
char *type_name;
type_len = mono_metadata_decode_blob_size (named, &named);
type_name = g_malloc (type_len + 1);
memcpy (type_name, named, type_len);
type_name [type_len] = 0;
named += type_len;
/* FIXME: lookup the type and check type consistency */
g_free (type_name);
}
name_len = mono_metadata_decode_blob_size (named, &named);
name = g_malloc (name_len + 1);
memcpy (name, named, name_len);
name [name_len] = 0;
named += name_len;
if (named_type == 0x53) {
MonoObject *obj;
MonoClassField *field = mono_class_get_field_from_name (attrklass, name);
void *val;
arginfo [j].type = field->type;
arginfo [j].field = field;
val = load_cattr_value (image, field->type, named, &named);
obj = type_is_reference (field->type) ? val : mono_value_box (domain, mono_class_from_mono_type (field->type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (field->type))
g_free (val);
} else if (named_type == 0x54) {
MonoObject *obj;
MonoType *prop_type;
MonoProperty *prop = mono_class_get_property_from_name (attrklass, name);
void *val;
prop_type = prop->get? mono_method_signature (prop->get)->ret :
mono_method_signature (prop->set)->params [mono_method_signature (prop->set)->param_count - 1];
arginfo [j].type = prop_type;
arginfo [j].prop = prop;
val = load_cattr_value (image, prop_type, named, &named);
obj = type_is_reference (prop_type) ? val : mono_value_box (domain, mono_class_from_mono_type (prop_type), val);
mono_array_setref (namedargs, j, obj);
if (!type_is_reference (prop_type))
g_free (val);
}
g_free (name);
}
*typed_args = typedargs;
*named_args = namedargs;
}
static MonoObject*
create_custom_attr_data (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len)
{
MonoArray *typedargs, *namedargs;
static MonoMethod *ctor;
MonoDomain *domain;
MonoObject *attr;
void *params [3];
CattrNamedArg *arginfo;
int i;
mono_class_init (method->klass);
if (!ctor)
ctor = mono_class_get_method_from_name (mono_defaults.customattribute_data_class, ".ctor", 3);
domain = mono_domain_get ();
if (len == 0) {
/* This is for Attributes with no parameters */
attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
params [0] = mono_method_get_object (domain, method, NULL);
params [1] = params [2] = NULL;
mono_runtime_invoke (method, attr, params, NULL);
return attr;
}
mono_reflection_create_custom_attr_data_args (image, method, data, len, &typedargs, &namedargs, &arginfo);
if (!typedargs || !namedargs)
return NULL;
for (i = 0; i < mono_method_signature (method)->param_count; ++i) {
MonoObject *obj = mono_array_get (typedargs, MonoObject*, i);
MonoObject *typedarg;
typedarg = create_cattr_typed_arg (mono_method_signature (method)->params [i], obj);
mono_array_setref (typedargs, i, typedarg);
}
for (i = 0; i < mono_array_length (namedargs); ++i) {
MonoObject *obj = mono_array_get (namedargs, MonoObject*, i);
MonoObject *typedarg, *namedarg, *minfo;
if (arginfo [i].prop)
minfo = (MonoObject*)mono_property_get_object (domain, NULL, arginfo [i].prop);
else
minfo = (MonoObject*)mono_field_get_object (domain, NULL, arginfo [i].field);
typedarg = create_cattr_typed_arg (arginfo [i].type, obj);
namedarg = create_cattr_named_arg (minfo, typedarg);
mono_array_setref (namedargs, i, namedarg);
}
attr = mono_object_new (domain, mono_defaults.customattribute_data_class);
params [0] = mono_method_get_object (domain, method, NULL);
params [1] = typedargs;
params [2] = namedargs;
mono_runtime_invoke (ctor, attr, params, NULL);
return attr;
}
MonoArray*
mono_custom_attrs_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
if (!cinfo->attrs [i].ctor)
/* The cattr type is not finished yet */
/* We should include the type name but cinfo doesn't contain it */
mono_raise_exception (mono_get_exception_type_load (NULL, NULL));
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, i, attr);
}
return result;
}
static MonoArray*
mono_custom_attrs_construct_by_type (MonoCustomAttrInfo *cinfo, MonoClass *attr_klass)
{
MonoArray *result;
MonoObject *attr;
int i, n;
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass))
n ++;
}
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, n);
n = 0;
for (i = 0; i < cinfo->num_attrs; ++i) {
if (mono_class_is_assignable_from (attr_klass, cinfo->attrs [i].ctor->klass)) {
attr = create_custom_attr (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, n, attr);
n ++;
}
}
return result;
}
static MonoArray*
mono_custom_attrs_data_construct (MonoCustomAttrInfo *cinfo)
{
MonoArray *result;
MonoObject *attr;
int i;
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, cinfo->num_attrs);
for (i = 0; i < cinfo->num_attrs; ++i) {
attr = create_custom_attr_data (cinfo->image, cinfo->attrs [i].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size);
mono_array_setref (result, i, attr);
}
return result;
}
/**
* mono_custom_attrs_from_index:
*
* Returns: NULL if no attributes are found or if a loading error occurs.
*/
MonoCustomAttrInfo*
mono_custom_attrs_from_index (MonoImage *image, guint32 idx)
{
guint32 mtoken, i, len;
guint32 cols [MONO_CUSTOM_ATTR_SIZE];
MonoTableInfo *ca;
MonoCustomAttrInfo *ainfo;
GList *tmp, *list = NULL;
const char *data;
ca = &image->tables [MONO_TABLE_CUSTOMATTRIBUTE];
i = mono_metadata_custom_attrs_from_index (image, idx);
if (!i)
return NULL;
i --;
while (i < ca->rows) {
if (mono_metadata_decode_row_col (ca, i, MONO_CUSTOM_ATTR_PARENT) != idx)
break;
list = g_list_prepend (list, GUINT_TO_POINTER (i));
++i;
}
len = g_list_length (list);
if (!len)
return NULL;
ainfo = g_malloc0 (MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * len);
ainfo->num_attrs = len;
ainfo->image = image;
for (i = 0, tmp = list; i < len; ++i, tmp = tmp->next) {
mono_metadata_decode_row (ca, GPOINTER_TO_UINT (tmp->data), cols, MONO_CUSTOM_ATTR_SIZE);
mtoken = cols [MONO_CUSTOM_ATTR_TYPE] >> MONO_CUSTOM_ATTR_TYPE_BITS;
switch (cols [MONO_CUSTOM_ATTR_TYPE] & MONO_CUSTOM_ATTR_TYPE_MASK) {
case MONO_CUSTOM_ATTR_TYPE_METHODDEF:
mtoken |= MONO_TOKEN_METHOD_DEF;
break;
case MONO_CUSTOM_ATTR_TYPE_MEMBERREF:
mtoken |= MONO_TOKEN_MEMBER_REF;
break;
default:
g_error ("Unknown table for custom attr type %08x", cols [MONO_CUSTOM_ATTR_TYPE]);
break;
}
ainfo->attrs [i].ctor = mono_get_method (image, mtoken, NULL);
if (!ainfo->attrs [i].ctor) {
g_warning ("Can't find custom attr constructor image: %s mtoken: 0x%08x", image->name, mtoken);
g_list_free (list);
g_free (ainfo);
return NULL;
}
data = mono_metadata_blob_heap (image, cols [MONO_CUSTOM_ATTR_VALUE]);
ainfo->attrs [i].data_size = mono_metadata_decode_value (data, &data);
ainfo->attrs [i].data = (guchar*)data;
}
g_list_free (list);
return ainfo;
}
MonoCustomAttrInfo*
mono_custom_attrs_from_method (MonoMethod *method)
{
guint32 idx;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->dynamic || method->klass->image->dynamic)
return lookup_custom_attr (method->klass->image, method);
if (!method->token)
/* Synthetic methods */
return NULL;
idx = mono_method_get_index (method);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_METHODDEF;
return mono_custom_attrs_from_index (method->klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_class (MonoClass *klass)
{
guint32 idx;
if (klass->generic_class)
klass = klass->generic_class->container_class;
if (klass->image->dynamic)
return lookup_custom_attr (klass->image, klass);
if (klass->byval_arg.type == MONO_TYPE_VAR || klass->byval_arg.type == MONO_TYPE_MVAR) {
idx = mono_metadata_token_index (klass->sizes.generic_param_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_GENERICPAR;
} else {
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_TYPEDEF;
}
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_assembly (MonoAssembly *assembly)
{
guint32 idx;
if (assembly->image->dynamic)
return lookup_custom_attr (assembly->image, assembly);
idx = 1; /* there is only one assembly */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_ASSEMBLY;
return mono_custom_attrs_from_index (assembly->image, idx);
}
static MonoCustomAttrInfo*
mono_custom_attrs_from_module (MonoImage *image)
{
guint32 idx;
if (image->dynamic)
return lookup_custom_attr (image, image);
idx = 1; /* there is only one module */
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_MODULE;
return mono_custom_attrs_from_index (image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_property (MonoClass *klass, MonoProperty *property)
{
guint32 idx;
if (klass->image->dynamic) {
property = mono_metadata_get_corresponding_property_from_generic_type_definition (property);
return lookup_custom_attr (klass->image, property);
}
idx = find_property_index (klass, property);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PROPERTY;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_event (MonoClass *klass, MonoEvent *event)
{
guint32 idx;
if (klass->image->dynamic) {
event = mono_metadata_get_corresponding_event_from_generic_type_definition (event);
return lookup_custom_attr (klass->image, event);
}
idx = find_event_index (klass, event);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_EVENT;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_field (MonoClass *klass, MonoClassField *field)
{
guint32 idx;
if (klass->image->dynamic) {
field = mono_metadata_get_corresponding_field_from_generic_type_definition (field);
return lookup_custom_attr (klass->image, field);
}
idx = find_field_index (klass, field);
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_FIELDDEF;
return mono_custom_attrs_from_index (klass->image, idx);
}
MonoCustomAttrInfo*
mono_custom_attrs_from_param (MonoMethod *method, guint32 param)
{
MonoTableInfo *ca;
guint32 i, idx, method_index;
guint32 param_list, param_last, param_pos, found;
MonoImage *image;
MonoReflectionMethodAux *aux;
/*
* An instantiated method has the same cattrs as the generic method definition.
*
* LAMESPEC: The .NET SRE throws an exception for instantiations of generic method builders
* Note that this stanza is not necessary for non-SRE types, but it's a micro-optimization
*/
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
if (method->klass->image->dynamic) {
MonoCustomAttrInfo *res, *ainfo;
int size;
aux = g_hash_table_lookup (((MonoDynamicImage*)method->klass->image)->method_aux_hash, method);
if (!aux || !aux->param_cattr)
return NULL;
/* Need to copy since it will be freed later */
ainfo = aux->param_cattr [param];
if (!ainfo)
return NULL;
size = MONO_SIZEOF_CUSTOM_ATTR_INFO + sizeof (MonoCustomAttrEntry) * ainfo->num_attrs;
res = g_malloc0 (size);
memcpy (res, ainfo, size);
return res;
}
image = method->klass->image;
method_index = mono_method_get_index (method);
ca = &image->tables [MONO_TABLE_METHOD];
param_list = mono_metadata_decode_row_col (ca, method_index - 1, MONO_METHOD_PARAMLIST);
if (method_index == ca->rows) {
ca = &image->tables [MONO_TABLE_PARAM];
param_last = ca->rows + 1;
} else {
param_last = mono_metadata_decode_row_col (ca, method_index, MONO_METHOD_PARAMLIST);
ca = &image->tables [MONO_TABLE_PARAM];
}
found = FALSE;
for (i = param_list; i < param_last; ++i) {
param_pos = mono_metadata_decode_row_col (ca, i - 1, MONO_PARAM_SEQUENCE);
if (param_pos == param) {
found = TRUE;
break;
}
}
if (!found)
return NULL;
idx = i;
idx <<= MONO_CUSTOM_ATTR_BITS;
idx |= MONO_CUSTOM_ATTR_PARAMDEF;
return mono_custom_attrs_from_index (image, idx);
}
gboolean
mono_custom_attrs_has_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i;
MonoClass *klass;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass) || (MONO_CLASS_IS_INTERFACE (attr_klass) && mono_class_is_assignable_from (attr_klass, klass)))
return TRUE;
}
return FALSE;
}
MonoObject*
mono_custom_attrs_get_attr (MonoCustomAttrInfo *ainfo, MonoClass *attr_klass)
{
int i, attr_index;
MonoClass *klass;
MonoArray *attrs;
attr_index = -1;
for (i = 0; i < ainfo->num_attrs; ++i) {
klass = ainfo->attrs [i].ctor->klass;
if (mono_class_has_parent (klass, attr_klass)) {
attr_index = i;
break;
}
}
if (attr_index == -1)
return NULL;
attrs = mono_custom_attrs_construct (ainfo);
if (attrs)
return mono_array_get (attrs, MonoObject*, attr_index);
else
return NULL;
}
/*
* mono_reflection_get_custom_attrs_info:
* @obj: a reflection object handle
*
* Return the custom attribute info for attributes defined for the
* reflection handle @obj. The objects.
*
* FIXME this function leaks like a sieve for SRE objects.
*/
MonoCustomAttrInfo*
mono_reflection_get_custom_attrs_info (MonoObject *obj)
{
MonoClass *klass;
MonoCustomAttrInfo *cinfo = NULL;
klass = obj->vtable->klass;
if (klass == mono_defaults.monotype_class) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType *)obj);
klass = mono_class_from_mono_type (type);
cinfo = mono_custom_attrs_from_class (klass);
} else if (strcmp ("Assembly", klass->name) == 0) {
MonoReflectionAssembly *rassembly = (MonoReflectionAssembly*)obj;
cinfo = mono_custom_attrs_from_assembly (rassembly->assembly);
} else if (strcmp ("Module", klass->name) == 0) {
MonoReflectionModule *module = (MonoReflectionModule*)obj;
cinfo = mono_custom_attrs_from_module (module->image);
} else if (strcmp ("MonoProperty", klass->name) == 0) {
MonoReflectionProperty *rprop = (MonoReflectionProperty*)obj;
cinfo = mono_custom_attrs_from_property (rprop->property->parent, rprop->property);
} else if (strcmp ("MonoEvent", klass->name) == 0) {
MonoReflectionMonoEvent *revent = (MonoReflectionMonoEvent*)obj;
cinfo = mono_custom_attrs_from_event (revent->event->parent, revent->event);
} else if (strcmp ("MonoField", klass->name) == 0) {
MonoReflectionField *rfield = (MonoReflectionField*)obj;
cinfo = mono_custom_attrs_from_field (rfield->field->parent, rfield->field);
} else if ((strcmp ("MonoMethod", klass->name) == 0) || (strcmp ("MonoCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if ((strcmp ("MonoGenericMethod", klass->name) == 0) || (strcmp ("MonoGenericCMethod", klass->name) == 0)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)obj;
cinfo = mono_custom_attrs_from_method (rmethod->method);
} else if (strcmp ("ParameterInfo", klass->name) == 0) {
MonoReflectionParameter *param = (MonoReflectionParameter*)obj;
MonoClass *member_class = mono_object_class (param->MemberImpl);
if (mono_class_is_reflection_method_or_constructor (member_class)) {
MonoReflectionMethod *rmethod = (MonoReflectionMethod*)param->MemberImpl;
cinfo = mono_custom_attrs_from_param (rmethod->method, param->PositionImpl + 1);
} else if (is_sr_mono_property (member_class)) {
MonoReflectionProperty *prop = (MonoReflectionProperty *)param->MemberImpl;
MonoMethod *method;
if (!(method = prop->property->get))
method = prop->property->set;
g_assert (method);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
} else if (is_sre_method_on_tb_inst (member_class)) {/*XXX This is a workaround for Compiler Context*/
MonoMethod *method = mono_reflection_method_on_tb_inst_get_handle ((MonoReflectionMethodOnTypeBuilderInst*)param->MemberImpl);
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
} else if (is_sre_ctor_on_tb_inst (member_class)) { /*XX This is a workaround for Compiler Context*/
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)param->MemberImpl;
MonoMethod *method = NULL;
if (is_sre_ctor_builder (mono_object_class (c->cb)))
method = ((MonoReflectionCtorBuilder *)c->cb)->mhandle;
else if (is_sr_mono_cmethod (mono_object_class (c->cb)))
method = ((MonoReflectionMethod *)c->cb)->method;
else
g_error ("mono_reflection_get_custom_attrs_info:: can't handle a CTBI with base_method of type %s", mono_type_get_full_name (member_class));
cinfo = mono_custom_attrs_from_param (method, param->PositionImpl + 1);
} else {
char *type_name = mono_type_get_full_name (member_class);
char *msg = g_strdup_printf ("Custom attributes on a ParamInfo with member %s are not supported", type_name);
MonoException *ex = mono_get_exception_not_supported (msg);
g_free (type_name);
g_free (msg);
mono_raise_exception (ex);
}
} else if (strcmp ("AssemblyBuilder", klass->name) == 0) {
MonoReflectionAssemblyBuilder *assemblyb = (MonoReflectionAssemblyBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, assemblyb->assembly.assembly->image, assemblyb->cattrs);
} else if (strcmp ("TypeBuilder", klass->name) == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &tb->module->dynamic_image->image, tb->cattrs);
} else if (strcmp ("ModuleBuilder", klass->name) == 0) {
MonoReflectionModuleBuilder *mb = (MonoReflectionModuleBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &mb->dynamic_image->image, mb->cattrs);
} else if (strcmp ("ConstructorBuilder", klass->name) == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, cb->mhandle->klass->image, cb->cattrs);
} else if (strcmp ("MethodBuilder", klass->name) == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, mb->mhandle->klass->image, mb->cattrs);
} else if (strcmp ("FieldBuilder", klass->name) == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
cinfo = mono_custom_attrs_from_builders (NULL, &((MonoReflectionTypeBuilder*)fb->typeb)->module->dynamic_image->image, fb->cattrs);
} else if (strcmp ("MonoGenericClass", klass->name) == 0) {
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)obj;
cinfo = mono_reflection_get_custom_attrs_info ((MonoObject*)gclass->generic_type);
} else { /* handle other types here... */
g_error ("get custom attrs not yet supported for %s", klass->name);
}
return cinfo;
}
/*
* mono_reflection_get_custom_attrs_by_type:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. If @attr_klass is non-NULL, only custom attributes
* of that type are returned. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs_by_type (MonoObject *obj, MonoClass *attr_klass)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
if (attr_klass)
result = mono_custom_attrs_construct_by_type (cinfo, attr_klass);
else
result = mono_custom_attrs_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else {
if (mono_loader_get_last_error ())
return NULL;
result = mono_array_new_cached (mono_domain_get (), mono_defaults.attribute_class, 0);
}
return result;
}
/*
* mono_reflection_get_custom_attrs:
* @obj: a reflection object handle
*
* Return an array with all the custom attributes defined of the
* reflection handle @obj. The objects are fully build. Return NULL if a loading error
* occurs.
*/
MonoArray*
mono_reflection_get_custom_attrs (MonoObject *obj)
{
return mono_reflection_get_custom_attrs_by_type (obj, NULL);
}
/*
* mono_reflection_get_custom_attrs_data:
* @obj: a reflection obj handle
*
* Returns an array of System.Reflection.CustomAttributeData,
* which include information about attributes reflected on
* types loaded using the Reflection Only methods
*/
MonoArray*
mono_reflection_get_custom_attrs_data (MonoObject *obj)
{
MonoArray *result;
MonoCustomAttrInfo *cinfo;
cinfo = mono_reflection_get_custom_attrs_info (obj);
if (cinfo) {
result = mono_custom_attrs_data_construct (cinfo);
if (!cinfo->cached)
mono_custom_attrs_free (cinfo);
} else
result = mono_array_new (mono_domain_get (), mono_defaults.customattribute_data_class, 0);
return result;
}
static MonoReflectionType*
mono_reflection_type_get_underlying_system_type (MonoReflectionType* t)
{
MonoMethod *method_get_underlying_system_type;
method_get_underlying_system_type = mono_object_get_virtual_method ((MonoObject *) t,
mono_class_get_method_from_name (mono_object_class (t),
"get_UnderlyingSystemType",
0));
return (MonoReflectionType *) mono_runtime_invoke (method_get_underlying_system_type, t, NULL, NULL);
}
#ifndef DISABLE_REFLECTION_EMIT
static gboolean
is_corlib_type (MonoClass *class)
{
return class->image == mono_defaults.corlib;
}
static gboolean
is_usertype (MonoReflectionType *ref)
{
MonoClass *class = mono_object_class (ref);
return class->image != mono_defaults.corlib || strcmp ("TypeDelegator", class->name) == 0;
}
#define check_corlib_type_cached(_class, _namespace, _name) do { \
static MonoClass *cached_class; \
if (cached_class) \
return cached_class == _class; \
if (is_corlib_type (_class) && !strcmp (_name, _class->name) && !strcmp (_namespace, _class->name_space)) { \
cached_class = _class; \
return TRUE; \
} \
return FALSE; \
} while (0) \
static gboolean
is_sre_array (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ArrayType");
}
static gboolean
is_sre_byref (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ByRefType");
}
static gboolean
is_sre_pointer (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "PointerType");
}
static gboolean
is_sre_generic_instance (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericClass");
}
static gboolean
is_sre_method_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodBuilder");
}
static gboolean
is_sre_ctor_builder (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorBuilder");
}
static gboolean
is_sr_mono_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoMethod");
}
static gboolean
is_sr_mono_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoCMethod");
}
static gboolean
is_sr_mono_generic_method (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericMethod");
}
static gboolean
is_sr_mono_generic_cmethod (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoGenericCMethod");
}
static gboolean
is_sr_mono_property (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection", "MonoProperty");
}
static gboolean
is_sre_method_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "MethodOnTypeBuilderInst");
}
static gboolean
is_sre_ctor_on_tb_inst (MonoClass *class)
{
check_corlib_type_cached (class, "System.Reflection.Emit", "ConstructorOnTypeBuilderInst");
}
gboolean
mono_class_is_reflection_method_or_constructor (MonoClass *class)
{
return is_sr_mono_method (class) || is_sr_mono_cmethod (class) || is_sr_mono_generic_method (class) || is_sr_mono_generic_cmethod (class);
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
MonoClass *class;
if (!ref)
return NULL;
if (ref->type)
return ref->type;
if (is_usertype (ref)) {
ref = mono_reflection_type_get_underlying_system_type (ref);
g_assert (!is_usertype (ref)); /*FIXME fail better*/
if (ref->type)
return ref->type;
}
class = mono_object_class (ref);
if (is_sre_array (class)) {
MonoType *res;
MonoReflectionArrayType *sre_array = (MonoReflectionArrayType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_array->element_type);
g_assert (base);
if (sre_array->rank == 0) //single dimentional array
res = &mono_array_class_get (mono_class_from_mono_type (base), 1)->byval_arg;
else
res = &mono_bounded_array_class_get (mono_class_from_mono_type (base), sre_array->rank, TRUE)->byval_arg;
sre_array->type.type = res;
return res;
} else if (is_sre_byref (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_byref = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_byref->element_type);
g_assert (base);
res = &mono_class_from_mono_type (base)->this_arg;
sre_byref->type.type = res;
return res;
} else if (is_sre_pointer (class)) {
MonoType *res;
MonoReflectionDerivedType *sre_pointer = (MonoReflectionDerivedType*)ref;
MonoType *base = mono_reflection_type_get_handle (sre_pointer->element_type);
g_assert (base);
res = &mono_ptr_class_get (base)->byval_arg;
sre_pointer->type.type = res;
return res;
} else if (is_sre_generic_instance (class)) {
MonoType *res, **types;
MonoReflectionGenericClass *gclass = (MonoReflectionGenericClass*)ref;
int i, count;
count = mono_array_length (gclass->type_arguments);
types = g_new0 (MonoType*, count);
for (i = 0; i < count; ++i) {
MonoReflectionType *t = mono_array_get (gclass->type_arguments, gpointer, i);
types [i] = mono_reflection_type_get_handle (t);
}
res = mono_reflection_bind_generic_parameters ((MonoReflectionType*)gclass->generic_type, count, types);
g_free (types);
g_assert (res);
gclass->type.type = res;
return res;
}
g_error ("Cannot handle corlib user type %s", mono_type_full_name (&mono_object_class(ref)->byval_arg));
return NULL;
}
static MonoReflectionType*
mono_reflection_type_resolve_user_types (MonoReflectionType *type)
{
if (!type || type->type)
return type;
if (is_usertype (type)) {
type = mono_reflection_type_get_underlying_system_type (type);
if (is_usertype (type))
mono_raise_exception (mono_get_exception_not_supported ("User defined subclasses of System.Type are not yet supported22"));
}
return type;
}
void
mono_reflection_create_unmanaged_type (MonoReflectionType *type)
{
mono_reflection_type_get_handle (type);
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
parameters_to_signature (MonoImage *image, MonoArray *parameters) {
MonoMethodSignature *sig;
int count, i;
count = parameters? mono_array_length (parameters): 0;
sig = image_g_malloc0 (image, MONO_SIZEOF_METHOD_SIGNATURE + sizeof (MonoType*) * count);
sig->param_count = count;
sig->sentinelpos = -1; /* FIXME */
for (i = 0; i < count; ++i)
sig->params [i] = mono_type_array_get_and_resolve (parameters, i);
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
ctor_builder_to_signature (MonoImage *image, MonoReflectionCtorBuilder *ctor) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, ctor->parameters);
sig->hasthis = ctor->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = &mono_defaults.void_class->byval_arg;
return sig;
}
/**
* LOCKING: Assumes the loader lock is held.
*/
static MonoMethodSignature*
method_builder_to_signature (MonoImage *image, MonoReflectionMethodBuilder *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (image, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle ((MonoReflectionType*)method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = method->generic_params ? mono_array_length (method->generic_params) : 0;
return sig;
}
static MonoMethodSignature*
dynamic_method_to_signature (MonoReflectionDynamicMethod *method) {
MonoMethodSignature *sig;
sig = parameters_to_signature (NULL, method->parameters);
sig->hasthis = method->attrs & METHOD_ATTRIBUTE_STATIC? 0: 1;
sig->ret = method->rtype? mono_reflection_type_get_handle (method->rtype): &mono_defaults.void_class->byval_arg;
sig->generic_param_count = 0;
return sig;
}
static void
get_prop_name_and_type (MonoObject *prop, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (prop);
if (strcmp (klass->name, "PropertyBuilder") == 0) {
MonoReflectionPropertyBuilder *pb = (MonoReflectionPropertyBuilder *)prop;
*name = mono_string_to_utf8 (pb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)pb->type);
} else {
MonoReflectionProperty *p = (MonoReflectionProperty *)prop;
*name = g_strdup (p->property->name);
if (p->property->get)
*type = mono_method_signature (p->property->get)->ret;
else
*type = mono_method_signature (p->property->set)->params [mono_method_signature (p->property->set)->param_count - 1];
}
}
static void
get_field_name_and_type (MonoObject *field, char **name, MonoType **type)
{
MonoClass *klass = mono_object_class (field);
if (strcmp (klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder *)field;
*name = mono_string_to_utf8 (fb->name);
*type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
} else {
MonoReflectionField *f = (MonoReflectionField *)field;
*name = g_strdup (mono_field_get_name (f->field));
*type = f->field->type;
}
}
#endif /* !DISABLE_REFLECTION_EMIT */
/*
* Encode a value in a custom attribute stream of bytes.
* The value to encode is either supplied as an object in argument val
* (valuetypes are boxed), or as a pointer to the data in the
* argument argval.
* @type represents the type of the value
* @buffer is the start of the buffer
* @p the current position in the buffer
* @buflen contains the size of the buffer and is used to return the new buffer size
* if this needs to be realloced.
* @retbuffer and @retp return the start and the position of the buffer
*/
static void
encode_cattr_value (MonoAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, MonoObject *arg, char *argval)
{
MonoTypeEnum simple_type;
if ((p-buffer) + 10 >= *buflen) {
char *newbuf;
*buflen *= 2;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
if (!argval)
argval = ((char*)arg + sizeof (MonoObject));
simple_type = type->type;
handle_enum:
switch (simple_type) {
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_U1:
case MONO_TYPE_I1:
*p++ = *argval;
break;
case MONO_TYPE_CHAR:
case MONO_TYPE_U2:
case MONO_TYPE_I2:
swap_with_size (p, argval, 2, 1);
p += 2;
break;
case MONO_TYPE_U4:
case MONO_TYPE_I4:
case MONO_TYPE_R4:
swap_with_size (p, argval, 4, 1);
p += 4;
break;
case MONO_TYPE_R8:
#if defined(ARM_FPU_FPA) && G_BYTE_ORDER == G_LITTLE_ENDIAN
p [0] = argval [4];
p [1] = argval [5];
p [2] = argval [6];
p [3] = argval [7];
p [4] = argval [0];
p [5] = argval [1];
p [6] = argval [2];
p [7] = argval [3];
#else
swap_with_size (p, argval, 8, 1);
#endif
p += 8;
break;
case MONO_TYPE_U8:
case MONO_TYPE_I8:
swap_with_size (p, argval, 8, 1);
p += 8;
break;
case MONO_TYPE_VALUETYPE:
if (type->data.klass->enumtype) {
simple_type = mono_class_enum_basetype (type->data.klass)->type;
goto handle_enum;
} else {
g_warning ("generic valutype %s not handled in custom attr value decoding", type->data.klass->name);
}
break;
case MONO_TYPE_STRING: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
str = mono_string_to_utf8 ((MonoString*)arg);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_CLASS: {
char *str;
guint32 slen;
if (!arg) {
*p++ = 0xFF;
break;
}
handle_type:
str = type_get_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)arg), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
break;
}
case MONO_TYPE_SZARRAY: {
int len, i;
MonoClass *eclass, *arg_eclass;
if (!arg) {
*p++ = 0xff; *p++ = 0xff; *p++ = 0xff; *p++ = 0xff;
break;
}
len = mono_array_length ((MonoArray*)arg);
*p++ = len & 0xff;
*p++ = (len >> 8) & 0xff;
*p++ = (len >> 16) & 0xff;
*p++ = (len >> 24) & 0xff;
*retp = p;
*retbuffer = buffer;
eclass = type->data.klass;
arg_eclass = mono_object_class (arg)->element_class;
if (!eclass) {
/* Happens when we are called from the MONO_TYPE_OBJECT case below */
eclass = mono_defaults.object_class;
}
if (eclass == mono_defaults.object_class && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (arg_eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &arg_eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else if (eclass->valuetype && arg_eclass->valuetype) {
char *elptr = mono_array_addr ((MonoArray*)arg, char, 0);
int elsize = mono_class_array_element_size (eclass);
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, NULL, elptr);
elptr += elsize;
}
} else {
for (i = 0; i < len; ++i) {
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &eclass->byval_arg, mono_array_get ((MonoArray*)arg, MonoObject*, i), NULL);
}
}
break;
}
case MONO_TYPE_OBJECT: {
MonoClass *klass;
char *str;
guint32 slen;
/*
* The parameter type is 'object' but the type of the actual
* argument is not. So we have to add type information to the blob
* too. This is completely undocumented in the spec.
*/
if (arg == NULL) {
*p++ = MONO_TYPE_STRING; // It's same hack as MS uses
*p++ = 0xFF;
break;
}
klass = mono_object_class (arg);
if (mono_object_isinst (arg, mono_defaults.systemtype_class)) {
*p++ = 0x50;
goto handle_type;
} else if (klass->enumtype) {
*p++ = 0x55;
} else if (klass == mono_defaults.string_class) {
simple_type = MONO_TYPE_STRING;
*p++ = 0x0E;
goto handle_enum;
} else if (klass->rank == 1) {
*p++ = 0x1D;
if (klass->element_class->byval_arg.type == MONO_TYPE_OBJECT)
/* See Partition II, Appendix B3 */
*p++ = 0x51;
else
*p++ = klass->element_class->byval_arg.type;
encode_cattr_value (assembly, buffer, p, &buffer, &p, buflen, &klass->byval_arg, arg, NULL);
break;
} else if (klass->byval_arg.type >= MONO_TYPE_BOOLEAN && klass->byval_arg.type <= MONO_TYPE_R8) {
*p++ = simple_type = klass->byval_arg.type;
goto handle_enum;
} else {
g_error ("unhandled type in custom attr");
}
str = type_get_qualified_name (mono_class_get_type(klass), NULL);
slen = strlen (str);
if ((p-buffer) + 10 + slen >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += slen;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
simple_type = mono_class_enum_basetype (klass)->type;
goto handle_enum;
}
default:
g_error ("type 0x%02x not yet supported in custom attr encoder", simple_type);
}
*retp = p;
*retbuffer = buffer;
}
static void
encode_field_or_prop_type (MonoType *type, char *p, char **retp)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
int slen = strlen (str);
*p++ = 0x55;
/*
* This seems to be optional...
* *p++ = 0x80;
*/
mono_metadata_encode_value (slen, p, &p);
memcpy (p, str, slen);
p += slen;
g_free (str);
} else if (type->type == MONO_TYPE_OBJECT) {
*p++ = 0x51;
} else if (type->type == MONO_TYPE_CLASS) {
/* it should be a type: encode_cattr_value () has the check */
*p++ = 0x50;
} else {
mono_metadata_encode_value (type->type, p, &p);
if (type->type == MONO_TYPE_SZARRAY)
/* See the examples in Partition VI, Annex B */
encode_field_or_prop_type (&type->data.klass->byval_arg, p, &p);
}
*retp = p;
}
#ifndef DISABLE_REFLECTION_EMIT
static void
encode_named_val (MonoReflectionAssembly *assembly, char *buffer, char *p, char **retbuffer, char **retp, guint32 *buflen, MonoType *type, char *name, MonoObject *value)
{
int len;
/* Preallocate a large enough buffer */
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype) {
char *str = type_get_qualified_name (type, NULL);
len = strlen (str);
g_free (str);
} else if (type->type == MONO_TYPE_SZARRAY && type->data.klass->enumtype) {
char *str = type_get_qualified_name (&type->data.klass->byval_arg, NULL);
len = strlen (str);
g_free (str);
} else {
len = 0;
}
len += strlen (name);
if ((p-buffer) + 20 + len >= *buflen) {
char *newbuf;
*buflen *= 2;
*buflen += len;
newbuf = g_realloc (buffer, *buflen);
p = newbuf + (p-buffer);
buffer = newbuf;
}
encode_field_or_prop_type (type, p, &p);
len = strlen (name);
mono_metadata_encode_value (len, p, &p);
memcpy (p, name, len);
p += len;
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, buflen, type, value, NULL);
*retp = p;
*retbuffer = buffer;
}
/*
* mono_reflection_get_custom_attrs_blob:
* @ctor: custom attribute constructor
* @ctorArgs: arguments o the constructor
* @properties:
* @propValues:
* @fields:
* @fieldValues:
*
* Creates the blob of data that needs to be saved in the metadata and that represents
* the custom attributed described by @ctor, @ctorArgs etc.
* Returns: a Byte array representing the blob of data.
*/
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
MonoArray *result;
MonoMethodSignature *sig;
MonoObject *arg;
char *buffer, *p;
guint32 buflen, i;
MONO_ARCH_SAVE_REGS;
if (strcmp (ctor->vtable->klass->name, "MonoCMethod")) {
/* sig is freed later so allocate it in the heap */
sig = ctor_builder_to_signature (NULL, (MonoReflectionCtorBuilder*)ctor);
} else {
sig = mono_method_signature (((MonoReflectionMethod*)ctor)->method);
}
g_assert (mono_array_length (ctorArgs) == sig->param_count);
buflen = 256;
p = buffer = g_malloc (buflen);
/* write the prolog */
*p++ = 1;
*p++ = 0;
for (i = 0; i < sig->param_count; ++i) {
arg = mono_array_get (ctorArgs, MonoObject*, i);
encode_cattr_value (assembly->assembly, buffer, p, &buffer, &p, &buflen, sig->params [i], arg, NULL);
}
i = 0;
if (properties)
i += mono_array_length (properties);
if (fields)
i += mono_array_length (fields);
*p++ = i & 0xff;
*p++ = (i >> 8) & 0xff;
if (properties) {
MonoObject *prop;
for (i = 0; i < mono_array_length (properties); ++i) {
MonoType *ptype;
char *pname;
prop = mono_array_get (properties, gpointer, i);
get_prop_name_and_type (prop, &pname, &ptype);
*p++ = 0x54; /* PROPERTY signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ptype, pname, (MonoObject*)mono_array_get (propValues, gpointer, i));
g_free (pname);
}
}
if (fields) {
MonoObject *field;
for (i = 0; i < mono_array_length (fields); ++i) {
MonoType *ftype;
char *fname;
field = mono_array_get (fields, gpointer, i);
get_field_name_and_type (field, &fname, &ftype);
*p++ = 0x53; /* FIELD signature */
encode_named_val (assembly, buffer, p, &buffer, &p, &buflen, ftype, fname, (MonoObject*)mono_array_get (fieldValues, gpointer, i));
g_free (fname);
}
}
g_assert (p - buffer <= buflen);
buflen = p - buffer;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
p = mono_array_addr (result, char, 0);
memcpy (p, buffer, buflen);
g_free (buffer);
if (strcmp (ctor->vtable->klass->name, "MonoCMethod"))
g_free (sig);
return result;
}
/*
* mono_reflection_setup_internal_class:
* @tb: a TypeBuilder object
*
* Creates a MonoClass that represents the TypeBuilder.
* This is a trick that lets us simplify a lot of reflection code
* (and will allow us to support Build and Run assemblies easier).
*/
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass, *parent;
MONO_ARCH_SAVE_REGS;
RESOLVE_TYPE (tb->parent);
mono_loader_lock ();
if (tb->parent) {
/* check so we can compile corlib correctly */
if (strcmp (mono_object_class (tb->parent)->name, "TypeBuilder") == 0) {
/* mono_class_setup_mono_type () guaranteess type->data.klass is valid */
parent = mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent)->data.klass;
} else {
parent = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb->parent));
}
} else {
parent = NULL;
}
/* the type has already being created: it means we just have to change the parent */
if (tb->type.type) {
klass = mono_class_from_mono_type (tb->type.type);
klass->parent = NULL;
/* fool mono_class_setup_parent */
klass->supertypes = NULL;
mono_class_setup_parent (klass, parent);
mono_class_setup_mono_type (klass);
mono_loader_unlock ();
return;
}
klass = mono_image_alloc0 (&tb->module->dynamic_image->image, sizeof (MonoClass));
klass->image = &tb->module->dynamic_image->image;
klass->inited = 1; /* we lie to the runtime */
klass->name = mono_string_to_utf8_image (klass->image, tb->name, &error);
if (!mono_error_ok (&error))
goto failure;
klass->name_space = mono_string_to_utf8_image (klass->image, tb->nspace, &error);
if (!mono_error_ok (&error))
goto failure;
klass->type_token = MONO_TOKEN_TYPE_DEF | tb->table_idx;
klass->flags = tb->attrs;
mono_profiler_class_event (klass, MONO_PROFILE_START_LOAD);
klass->element_class = klass;
MOVING_GC_REGISTER (&klass->reflection_info);
klass->reflection_info = tb;
/* Put into cache so mono_class_get () will find it */
mono_image_add_to_name_cache (klass->image, klass->name_space, klass->name, tb->table_idx);
mono_g_hash_table_insert (tb->module->dynamic_image->tokens,
GUINT_TO_POINTER (MONO_TOKEN_TYPE_DEF | tb->table_idx), tb);
if (parent != NULL) {
mono_class_setup_parent (klass, parent);
} else if (strcmp (klass->name, "Object") == 0 && strcmp (klass->name_space, "System") == 0) {
const char *old_n = klass->name;
/* trick to get relative numbering right when compiling corlib */
klass->name = "BuildingObject";
mono_class_setup_parent (klass, mono_defaults.object_class);
klass->name = old_n;
}
if ((!strcmp (klass->name, "ValueType") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Object") && !strcmp (klass->name_space, "System")) ||
(!strcmp (klass->name, "Enum") && !strcmp (klass->name_space, "System"))) {
klass->instance_size = sizeof (MonoObject);
klass->size_inited = 1;
mono_class_setup_vtable_general (klass, NULL, 0);
}
mono_class_setup_mono_type (klass);
mono_class_setup_supertypes (klass);
/*
* FIXME: handle interfaces.
*/
tb->type.type = &klass->byval_arg;
if (tb->nesting_type) {
g_assert (tb->nesting_type->type);
klass->nested_in = mono_class_from_mono_type (mono_reflection_type_get_handle (tb->nesting_type));
}
/*g_print ("setup %s as %s (%p)\n", klass->name, ((MonoObject*)tb)->vtable->klass->name, tb);*/
mono_profiler_class_loaded (klass, MONO_PROFILE_OK);
mono_loader_unlock ();
return;
failure:
mono_loader_unlock ();
mono_error_raise_exception (&error);
}
/*
* mono_reflection_setup_generic_class:
* @tb: a TypeBuilder object
*
* Setup the generic class before adding the first generic parameter.
*/
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
}
/*
* mono_reflection_create_generic_class:
* @tb: a TypeBuilder object
*
* Creates the generic class after all generic parameters have been added.
*/
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
int count, i;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
count = tb->generic_params ? mono_array_length (tb->generic_params) : 0;
if (klass->generic_container || (count == 0))
return;
g_assert (tb->generic_container && (tb->generic_container->owner.klass == klass));
klass->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
klass->generic_container->owner.klass = klass;
klass->generic_container->type_argc = count;
klass->generic_container->type_params = mono_image_alloc0 (klass->image, sizeof (MonoGenericParamFull) * count);
klass->is_generic = 1;
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gparam = mono_array_get (tb->generic_params, gpointer, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gparam)->data.generic_param;
klass->generic_container->type_params [i] = *param;
/*Make sure we are a diferent type instance */
klass->generic_container->type_params [i].param.owner = klass->generic_container;
klass->generic_container->type_params [i].info.pklass = NULL;
klass->generic_container->type_params [i].info.flags = gparam->attrs;
g_assert (klass->generic_container->type_params [i].param.owner);
}
klass->generic_container->context.class_inst = mono_get_shared_generic_inst (klass->generic_container);
}
/*
* mono_reflection_create_internal_class:
* @tb: a TypeBuilder object
*
* Actually create the MonoClass that is associated with the TypeBuilder.
*/
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
MonoClass *klass;
MONO_ARCH_SAVE_REGS;
klass = mono_class_from_mono_type (tb->type.type);
mono_loader_lock ();
if (klass->enumtype && mono_class_enum_basetype (klass) == NULL) {
MonoReflectionFieldBuilder *fb;
MonoClass *ec;
MonoType *enum_basetype;
g_assert (tb->fields != NULL);
g_assert (mono_array_length (tb->fields) >= 1);
fb = mono_array_get (tb->fields, MonoReflectionFieldBuilder*, 0);
if (!mono_type_is_valid_enum_basetype (mono_reflection_type_get_handle ((MonoReflectionType*)fb->type))) {
mono_loader_unlock ();
return;
}
enum_basetype = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
klass->element_class = mono_class_from_mono_type (enum_basetype);
if (!klass->element_class)
klass->element_class = mono_class_from_mono_type (enum_basetype);
/*
* get the element_class from the current corlib.
*/
ec = default_class_from_mono_type (enum_basetype);
klass->instance_size = ec->instance_size;
klass->size_inited = 1;
/*
* this is almost safe to do with enums and it's needed to be able
* to create objects of the enum type (for use in SetConstant).
*/
/* FIXME: Does this mean enums can't have method overrides ? */
mono_class_setup_vtable_general (klass, NULL, 0);
}
mono_loader_unlock ();
}
static MonoMarshalSpec*
mono_marshal_spec_from_builder (MonoImage *image, MonoAssembly *assembly,
MonoReflectionMarshal *minfo)
{
MonoMarshalSpec *res;
res = image_g_new0 (image, MonoMarshalSpec, 1);
res->native = minfo->type;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
res->data.array_data.elem_type = minfo->eltype;
if (minfo->has_size) {
res->data.array_data.param_num = minfo->param_num;
res->data.array_data.num_elem = minfo->count;
res->data.array_data.elem_mult = minfo->param_num == -1 ? 0 : 1;
}
else {
res->data.array_data.param_num = -1;
res->data.array_data.num_elem = -1;
res->data.array_data.elem_mult = -1;
}
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
res->data.array_data.num_elem = minfo->count;
break;
case MONO_NATIVE_CUSTOM:
if (minfo->marshaltyperef)
res->data.custom_data.custom_name =
type_get_fully_qualified_name (mono_reflection_type_get_handle ((MonoReflectionType*)minfo->marshaltyperef));
if (minfo->mcookie)
res->data.custom_data.cookie = mono_string_to_utf8 (minfo->mcookie);
break;
default:
break;
}
return res;
}
#endif /* !DISABLE_REFLECTION_EMIT */
MonoReflectionMarshal*
mono_reflection_marshal_from_marshal_spec (MonoDomain *domain, MonoClass *klass,
MonoMarshalSpec *spec)
{
static MonoClass *System_Reflection_Emit_UnmanagedMarshalClass;
MonoReflectionMarshal *minfo;
MonoType *mtype;
if (!System_Reflection_Emit_UnmanagedMarshalClass) {
System_Reflection_Emit_UnmanagedMarshalClass = mono_class_from_name (
mono_defaults.corlib, "System.Reflection.Emit", "UnmanagedMarshal");
g_assert (System_Reflection_Emit_UnmanagedMarshalClass);
}
minfo = (MonoReflectionMarshal*)mono_object_new (domain, System_Reflection_Emit_UnmanagedMarshalClass);
minfo->type = spec->native;
switch (minfo->type) {
case MONO_NATIVE_LPARRAY:
minfo->eltype = spec->data.array_data.elem_type;
minfo->count = spec->data.array_data.num_elem;
minfo->param_num = spec->data.array_data.param_num;
break;
case MONO_NATIVE_BYVALTSTR:
case MONO_NATIVE_BYVALARRAY:
minfo->count = spec->data.array_data.num_elem;
break;
case MONO_NATIVE_CUSTOM:
if (spec->data.custom_data.custom_name) {
mtype = mono_reflection_type_from_name (spec->data.custom_data.custom_name, klass->image);
if (mtype)
MONO_OBJECT_SETREF (minfo, marshaltyperef, mono_type_get_object (domain, mtype));
MONO_OBJECT_SETREF (minfo, marshaltype, mono_string_new (domain, spec->data.custom_data.custom_name));
}
if (spec->data.custom_data.cookie)
MONO_OBJECT_SETREF (minfo, mcookie, mono_string_new (domain, spec->data.custom_data.cookie));
break;
default:
break;
}
return minfo;
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod*
reflection_methodbuilder_to_mono_method (MonoClass *klass,
ReflectionMethodBuilder *rmb,
MonoMethodSignature *sig)
{
MonoError error;
MonoMethod *m;
MonoMethodNormal *pm;
MonoMarshalSpec **specs;
MonoReflectionMethodAux *method_aux;
MonoImage *image;
gboolean dynamic;
int i;
mono_error_init (&error);
/*
* Methods created using a MethodBuilder should have their memory allocated
* inside the image mempool, while dynamic methods should have their memory
* malloc'd.
*/
dynamic = rmb->refs != NULL;
image = dynamic ? NULL : klass->image;
if (!dynamic)
g_assert (!klass->generic_class);
mono_loader_lock ();
if ((rmb->attrs & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
(rmb->iattrs & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))
m = (MonoMethod *)image_g_new0 (image, MonoMethodPInvoke, 1);
else if (rmb->refs)
m = (MonoMethod *)image_g_new0 (image, MonoMethodWrapper, 1);
else
m = (MonoMethod *)image_g_new0 (image, MonoMethodNormal, 1);
pm = (MonoMethodNormal*)m;
m->dynamic = dynamic;
m->slot = -1;
m->flags = rmb->attrs;
m->iflags = rmb->iattrs;
m->name = mono_string_to_utf8_image (image, rmb->name, &error);
g_assert (mono_error_ok (&error));
m->klass = klass;
m->signature = sig;
m->skip_visibility = rmb->skip_visibility;
if (rmb->table_idx)
m->token = MONO_TOKEN_METHOD_DEF | (*rmb->table_idx);
if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
if (klass == mono_defaults.string_class && !strcmp (m->name, ".ctor"))
m->string_ctor = 1;
m->signature->pinvoke = 1;
} else if (m->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
m->signature->pinvoke = 1;
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->dllentry = rmb->dllentry ? mono_string_to_utf8_image (image, rmb->dllentry, &error) : image_strdup (image, m->name);
g_assert (mono_error_ok (&error));
method_aux->dll = mono_string_to_utf8_image (image, rmb->dll, &error);
g_assert (mono_error_ok (&error));
((MonoMethodPInvoke*)m)->piflags = (rmb->native_cc << 8) | (rmb->charset ? (rmb->charset - 1) * 2 : 0) | rmb->extra_flags;
if (klass->image->dynamic)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
} else if (!(m->flags & METHOD_ATTRIBUTE_ABSTRACT) &&
!(m->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
MonoMethodHeader *header;
guint32 code_size;
gint32 max_stack, i;
gint32 num_locals = 0;
gint32 num_clauses = 0;
guint8 *code;
if (rmb->ilgen) {
code = mono_array_addr (rmb->ilgen->code, guint8, 0);
code_size = rmb->ilgen->code_len;
max_stack = rmb->ilgen->max_stack;
num_locals = rmb->ilgen->locals ? mono_array_length (rmb->ilgen->locals) : 0;
if (rmb->ilgen->ex_handlers)
num_clauses = method_count_clauses (rmb->ilgen);
} else {
if (rmb->code) {
code = mono_array_addr (rmb->code, guint8, 0);
code_size = mono_array_length (rmb->code);
/* we probably need to run a verifier on the code... */
max_stack = 8;
}
else {
code = NULL;
code_size = 0;
max_stack = 8;
}
}
header = image_g_malloc0 (image, MONO_SIZEOF_METHOD_HEADER + num_locals * sizeof (MonoType*));
header->code_size = code_size;
header->code = image_g_malloc (image, code_size);
memcpy ((char*)header->code, code, code_size);
header->max_stack = max_stack;
header->init_locals = rmb->init_locals;
header->num_locals = num_locals;
for (i = 0; i < num_locals; ++i) {
MonoReflectionLocalBuilder *lb =
mono_array_get (rmb->ilgen->locals, MonoReflectionLocalBuilder*, i);
header->locals [i] = image_g_new0 (image, MonoType, 1);
memcpy (header->locals [i], mono_reflection_type_get_handle ((MonoReflectionType*)lb->type), MONO_SIZEOF_TYPE);
}
header->num_clauses = num_clauses;
if (num_clauses) {
header->clauses = method_encode_clauses (image, (MonoDynamicImage*)klass->image,
rmb->ilgen, num_clauses);
}
pm->header = header;
}
if (rmb->generic_params) {
int count = mono_array_length (rmb->generic_params);
MonoGenericContainer *container;
container = rmb->generic_container;
if (container) {
m->is_generic = TRUE;
mono_method_set_generic_container (m, container);
}
container->type_argc = count;
container->type_params = image_g_new0 (image, MonoGenericParamFull, count);
container->owner.method = m;
for (i = 0; i < count; i++) {
MonoReflectionGenericParam *gp =
mono_array_get (rmb->generic_params, MonoReflectionGenericParam*, i);
MonoGenericParamFull *param = (MonoGenericParamFull *) mono_reflection_type_get_handle ((MonoReflectionType*)gp)->data.generic_param;
container->type_params [i] = *param;
}
if (klass->generic_container) {
container->parent = klass->generic_container;
container->context.class_inst = klass->generic_container->context.class_inst;
}
container->context.method_inst = mono_get_shared_generic_inst (container);
}
if (rmb->refs) {
MonoMethodWrapper *mw = (MonoMethodWrapper*)m;
int i;
void **data;
m->wrapper_type = MONO_WRAPPER_DYNAMIC_METHOD;
mw->method_data = data = image_g_new (image, gpointer, rmb->nrefs + 1);
data [0] = GUINT_TO_POINTER (rmb->nrefs);
for (i = 0; i < rmb->nrefs; ++i)
data [i + 1] = rmb->refs [i];
}
method_aux = NULL;
/* Parameter info */
if (rmb->pinfo) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_names = image_g_new0 (image, char *, mono_method_signature (m)->param_count + 1);
for (i = 0; i <= m->signature->param_count; ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if ((i > 0) && (pb->attrs)) {
/* Make a copy since it might point to a shared type structure */
m->signature->params [i - 1] = mono_metadata_type_dup (klass->image, m->signature->params [i - 1]);
m->signature->params [i - 1]->attrs = pb->attrs;
}
if (pb->attrs & PARAM_ATTRIBUTE_HAS_DEFAULT) {
MonoDynamicImage *assembly;
guint32 idx, def_type, len;
char *p;
const char *p2;
if (!method_aux->param_defaults) {
method_aux->param_defaults = image_g_new0 (image, guint8*, m->signature->param_count + 1);
method_aux->param_default_types = image_g_new0 (image, guint32, m->signature->param_count + 1);
}
assembly = (MonoDynamicImage*)klass->image;
idx = encode_constant (assembly, pb->def_value, &def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
method_aux->param_defaults [i] = image_g_malloc (image, len);
method_aux->param_default_types [i] = def_type;
memcpy ((gpointer)method_aux->param_defaults [i], p, len);
}
if (pb->name) {
method_aux->param_names [i] = mono_string_to_utf8_image (image, pb->name, &error);
g_assert (mono_error_ok (&error));
}
if (pb->cattrs) {
if (!method_aux->param_cattr)
method_aux->param_cattr = image_g_new0 (image, MonoCustomAttrInfo*, m->signature->param_count + 1);
method_aux->param_cattr [i] = mono_custom_attrs_from_builders (image, klass->image, pb->cattrs);
}
}
}
}
/* Parameter marshalling */
specs = NULL;
if (rmb->pinfo)
for (i = 0; i < mono_array_length (rmb->pinfo); ++i) {
MonoReflectionParamBuilder *pb;
if ((pb = mono_array_get (rmb->pinfo, MonoReflectionParamBuilder*, i))) {
if (pb->marshal_info) {
if (specs == NULL)
specs = image_g_new0 (image, MonoMarshalSpec*, sig->param_count + 1);
specs [pb->position] =
mono_marshal_spec_from_builder (image, klass->image->assembly, pb->marshal_info);
}
}
}
if (specs != NULL) {
if (!method_aux)
method_aux = image_g_new0 (image, MonoReflectionMethodAux, 1);
method_aux->param_marshall = specs;
}
if (klass->image->dynamic && method_aux)
g_hash_table_insert (((MonoDynamicImage*)klass->image)->method_aux_hash, m, method_aux);
mono_loader_unlock ();
return m;
}
static MonoMethod*
ctorbuilder_to_mono_method (MonoClass *klass, MonoReflectionCtorBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = ctor_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_ctor_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoMethod*
methodbuilder_to_mono_method (MonoClass *klass, MonoReflectionMethodBuilder* mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
mono_loader_lock ();
sig = method_builder_to_signature (klass->image, mb);
mono_loader_unlock ();
reflection_methodbuilder_from_method_builder (&rmb, mb);
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
mono_save_custom_attrs (klass->image, mb->mhandle, mb->cattrs);
/* If we are in a generic class, we might be called multiple times from inflate_method */
if (!((MonoDynamicImage*)(MonoDynamicImage*)klass->image)->save && !klass->generic_container) {
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
return mb->mhandle;
}
static MonoClassField*
fieldbuilder_to_mono_class_field (MonoClass *klass, MonoReflectionFieldBuilder* fb)
{
MonoClassField *field;
MonoType *custom;
field = g_new0 (MonoClassField, 1);
field->name = mono_string_to_utf8 (fb->name);
if (fb->attrs || fb->modreq || fb->modopt) {
field->type = mono_metadata_type_dup (NULL, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
g_assert (klass->image->dynamic);
custom = add_custom_modifiers ((MonoDynamicImage*)klass->image, field->type, fb->modreq, fb->modopt);
g_free (field->type);
field->type = custom;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
// FIXME: Can't store fb->def_value/RVA, is it needed for field_on_insts ?
return field;
}
#endif
MonoType*
mono_reflection_bind_generic_parameters (MonoReflectionType *type, int type_argc, MonoType **types)
{
MonoClass *klass;
MonoReflectionTypeBuilder *tb = NULL;
gboolean is_dynamic = FALSE;
MonoDomain *domain;
MonoClass *geninst;
mono_loader_lock ();
domain = mono_object_domain (type);
if (!strcmp (((MonoObject *) type)->vtable->klass->name, "TypeBuilder")) {
tb = (MonoReflectionTypeBuilder *) type;
is_dynamic = TRUE;
} else if (!strcmp (((MonoObject *) type)->vtable->klass->name, "MonoGenericClass")) {
MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type;
tb = rgi->generic_type;
is_dynamic = TRUE;
}
/* FIXME: fix the CreateGenericParameters protocol to avoid the two stage setup of TypeBuilders */
if (tb && tb->generic_container)
mono_reflection_create_generic_class (tb);
klass = mono_class_from_mono_type (mono_reflection_type_get_handle (type));
if (!klass->generic_container) {
mono_loader_unlock ();
return NULL;
}
if (klass->wastypebuilder) {
tb = (MonoReflectionTypeBuilder *) klass->reflection_info;
is_dynamic = TRUE;
}
mono_loader_unlock ();
geninst = mono_class_bind_generic_parameters (klass, type_argc, types, is_dynamic);
return &geninst->byval_arg;
}
MonoClass*
mono_class_bind_generic_parameters (MonoClass *klass, int type_argc, MonoType **types, gboolean is_dynamic)
{
MonoGenericClass *gclass;
MonoGenericInst *inst;
g_assert (klass->generic_container);
inst = mono_metadata_get_generic_inst (type_argc, types);
gclass = mono_metadata_lookup_generic_class (klass, inst, is_dynamic);
return mono_generic_class_get_class (gclass);
}
MonoReflectionMethod*
mono_reflection_bind_generic_method_parameters (MonoReflectionMethod *rmethod, MonoArray *types)
{
MonoClass *klass;
MonoMethod *method, *inflated;
MonoMethodInflated *imethod;
MonoGenericContext tmp_context;
MonoGenericInst *ginst;
MonoType **type_argv;
int count, i;
MONO_ARCH_SAVE_REGS;
if (!strcmp (rmethod->object.vtable->klass->name, "MethodBuilder")) {
#ifndef DISABLE_REFLECTION_EMIT
MonoReflectionMethodBuilder *mb = NULL;
MonoReflectionTypeBuilder *tb;
MonoClass *klass;
mb = (MonoReflectionMethodBuilder *) rmethod;
tb = (MonoReflectionTypeBuilder *) mb->type;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
method = methodbuilder_to_mono_method (klass, mb);
#else
g_assert_not_reached ();
method = NULL;
#endif
} else {
method = rmethod->method;
}
klass = method->klass;
if (method->is_inflated)
method = ((MonoMethodInflated *) method)->declaring;
count = mono_method_signature (method)->generic_param_count;
if (count != mono_array_length (types))
return NULL;
type_argv = g_new0 (MonoType *, count);
for (i = 0; i < count; i++) {
MonoReflectionType *garg = mono_array_get (types, gpointer, i);
type_argv [i] = mono_reflection_type_get_handle (garg);
}
ginst = mono_metadata_get_generic_inst (count, type_argv);
g_free (type_argv);
tmp_context.class_inst = klass->generic_class ? klass->generic_class->context.class_inst : NULL;
tmp_context.method_inst = ginst;
inflated = mono_class_inflate_generic_method (method, &tmp_context);
imethod = (MonoMethodInflated *) inflated;
if (method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
/*
* This table maps metadata structures representing inflated methods/fields
* to the reflection objects representing their generic definitions.
*/
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, rmethod);
mono_loader_unlock ();
}
return mono_method_get_object (mono_object_domain (rmethod), inflated, NULL);
}
#ifndef DISABLE_REFLECTION_EMIT
static MonoMethod *
inflate_mono_method (MonoClass *klass, MonoMethod *method, MonoObject *obj)
{
MonoMethodInflated *imethod;
MonoGenericContext *context;
int i;
/*
* With generic code sharing the klass might not be inflated.
* This can happen because classes inflated with their own
* type arguments are "normalized" to the uninflated class.
*/
if (!klass->generic_class)
return method;
context = mono_class_get_context (klass);
if (klass->method.count) {
/* Find the already created inflated method */
for (i = 0; i < klass->method.count; ++i) {
g_assert (klass->methods [i]->is_inflated);
if (((MonoMethodInflated*)klass->methods [i])->declaring == method)
break;
}
g_assert (i < klass->method.count);
imethod = (MonoMethodInflated*)klass->methods [i];
} else {
imethod = (MonoMethodInflated *) mono_class_inflate_generic_method_full (method, klass, context);
}
if (method->is_generic && method->klass->image->dynamic) {
MonoDynamicImage *image = (MonoDynamicImage*)method->klass->image;
mono_loader_lock ();
mono_g_hash_table_insert (image->generic_def_objects, imethod, obj);
mono_loader_unlock ();
}
return (MonoMethod *) imethod;
}
static MonoMethod *
inflate_method (MonoReflectionGenericClass *type, MonoObject *obj)
{
MonoMethod *method;
MonoClass *gklass;
gklass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)type->generic_type));
if (!strcmp (obj->vtable->klass->name, "MethodBuilder"))
if (((MonoReflectionMethodBuilder*)obj)->mhandle)
method = ((MonoReflectionMethodBuilder*)obj)->mhandle;
else
method = methodbuilder_to_mono_method (gklass, (MonoReflectionMethodBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "ConstructorBuilder"))
method = ctorbuilder_to_mono_method (gklass, (MonoReflectionCtorBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoMethod") || !strcmp (obj->vtable->klass->name, "MonoCMethod"))
method = ((MonoReflectionMethod *) obj)->method;
else {
method = NULL; /* prevent compiler warning */
g_error ("can't handle type %s", obj->vtable->klass->name);
}
return inflate_mono_method (mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)type)), method, obj);
}
/*TODO avoid saving custom attrs for generic classes as it's enough to have them on the generic type definition.*/
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
MonoGenericClass *gclass;
MonoDynamicGenericClass *dgclass;
MonoClass *klass, *gklass;
MonoType *gtype;
int i;
MONO_ARCH_SAVE_REGS;
gtype = mono_reflection_type_get_handle ((MonoReflectionType*)type);
klass = mono_class_from_mono_type (gtype);
g_assert (gtype->type == MONO_TYPE_GENERICINST);
gclass = gtype->data.generic_class;
g_assert (gclass->is_dynamic);
dgclass = (MonoDynamicGenericClass *) gclass;
if (dgclass->initialized)
return;
gklass = gclass->container_class;
mono_class_init (gklass);
dgclass->count_methods = methods ? mono_array_length (methods) : 0;
dgclass->count_ctors = ctors ? mono_array_length (ctors) : 0;
dgclass->count_fields = fields ? mono_array_length (fields) : 0;
dgclass->count_properties = properties ? mono_array_length (properties) : 0;
dgclass->count_events = events ? mono_array_length (events) : 0;
dgclass->methods = g_new0 (MonoMethod *, dgclass->count_methods);
dgclass->ctors = g_new0 (MonoMethod *, dgclass->count_ctors);
dgclass->fields = g_new0 (MonoClassField, dgclass->count_fields);
dgclass->properties = g_new0 (MonoProperty, dgclass->count_properties);
dgclass->events = g_new0 (MonoEvent, dgclass->count_events);
dgclass->field_objects = g_new0 (MonoObject*, dgclass->count_fields);
dgclass->field_generic_types = g_new0 (MonoType*, dgclass->count_fields);
for (i = 0; i < dgclass->count_methods; i++) {
MonoObject *obj = mono_array_get (methods, gpointer, i);
dgclass->methods [i] = inflate_method (type, obj);
}
for (i = 0; i < dgclass->count_ctors; i++) {
MonoObject *obj = mono_array_get (ctors, gpointer, i);
dgclass->ctors [i] = inflate_method (type, obj);
}
for (i = 0; i < dgclass->count_fields; i++) {
MonoObject *obj = mono_array_get (fields, gpointer, i);
MonoClassField *field, *inflated_field = NULL;
if (!strcmp (obj->vtable->klass->name, "FieldBuilder"))
inflated_field = field = fieldbuilder_to_mono_class_field (klass, (MonoReflectionFieldBuilder *) obj);
else if (!strcmp (obj->vtable->klass->name, "MonoField"))
field = ((MonoReflectionField *) obj)->field;
else {
field = NULL; /* prevent compiler warning */
g_assert_not_reached ();
}
dgclass->fields [i] = *field;
dgclass->fields [i].parent = klass;
dgclass->fields [i].type = mono_class_inflate_generic_type (
field->type, mono_generic_class_get_context ((MonoGenericClass *) dgclass));
dgclass->field_generic_types [i] = field->type;
MOVING_GC_REGISTER (&dgclass->field_objects [i]);
dgclass->field_objects [i] = obj;
if (inflated_field) {
g_free (inflated_field);
} else {
dgclass->fields [i].name = g_strdup (dgclass->fields [i].name);
}
}
for (i = 0; i < dgclass->count_properties; i++) {
MonoObject *obj = mono_array_get (properties, gpointer, i);
MonoProperty *property = &dgclass->properties [i];
if (!strcmp (obj->vtable->klass->name, "PropertyBuilder")) {
MonoReflectionPropertyBuilder *pb = (MonoReflectionPropertyBuilder *) obj;
property->parent = klass;
property->attrs = pb->attrs;
property->name = mono_string_to_utf8 (pb->name);
if (pb->get_method)
property->get = inflate_method (type, (MonoObject *) pb->get_method);
if (pb->set_method)
property->set = inflate_method (type, (MonoObject *) pb->set_method);
} else if (!strcmp (obj->vtable->klass->name, "MonoProperty")) {
*property = *((MonoReflectionProperty *) obj)->property;
property->name = g_strdup (property->name);
if (property->get)
property->get = inflate_mono_method (klass, property->get, NULL);
if (property->set)
property->set = inflate_mono_method (klass, property->set, NULL);
} else
g_assert_not_reached ();
}
for (i = 0; i < dgclass->count_events; i++) {
MonoObject *obj = mono_array_get (events, gpointer, i);
MonoEvent *event = &dgclass->events [i];
if (!strcmp (obj->vtable->klass->name, "EventBuilder")) {
MonoReflectionEventBuilder *eb = (MonoReflectionEventBuilder *) obj;
event->parent = klass;
event->attrs = eb->attrs;
event->name = mono_string_to_utf8 (eb->name);
if (eb->add_method)
event->add = inflate_method (type, (MonoObject *) eb->add_method);
if (eb->remove_method)
event->remove = inflate_method (type, (MonoObject *) eb->remove_method);
} else if (!strcmp (obj->vtable->klass->name, "MonoEvent")) {
*event = *((MonoReflectionMonoEvent *) obj)->event;
event->name = g_strdup (event->name);
if (event->add)
event->add = inflate_mono_method (klass, event->add, NULL);
if (event->remove)
event->remove = inflate_mono_method (klass, event->remove, NULL);
} else
g_assert_not_reached ();
}
dgclass->initialized = TRUE;
}
static void
ensure_generic_class_runtime_vtable (MonoClass *klass)
{
MonoClass *gklass = klass->generic_class->container_class;
int i;
if (klass->wastypebuilder)
return;
ensure_runtime_vtable (gklass);
klass->method.count = gklass->method.count;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * (klass->method.count + 1));
for (i = 0; i < klass->method.count; i++) {
klass->methods [i] = mono_class_inflate_generic_method_full (
gklass->methods [i], klass, mono_class_get_context (klass));
}
klass->interface_count = gklass->interface_count;
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * klass->interface_count);
for (i = 0; i < klass->interface_count; ++i) {
MonoType *iface_type = mono_class_inflate_generic_type (&gklass->interfaces [i]->byval_arg, mono_class_get_context (klass));
klass->interfaces [i] = mono_class_from_mono_type (iface_type);
mono_metadata_free_type (iface_type);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
/*We can only finish with this klass once it's parent has as well*/
if (gklass->wastypebuilder)
klass->wastypebuilder = TRUE;
return;
}
static void
ensure_runtime_vtable (MonoClass *klass)
{
MonoReflectionTypeBuilder *tb = klass->reflection_info;
int i, num, j;
if (!klass->image->dynamic || (!tb && !klass->generic_class) || klass->wastypebuilder)
return;
if (klass->parent)
ensure_runtime_vtable (klass->parent);
if (tb) {
num = tb->ctors? mono_array_length (tb->ctors): 0;
num += tb->num_methods;
klass->method.count = num;
klass->methods = mono_image_alloc (klass->image, sizeof (MonoMethod*) * num);
num = tb->ctors? mono_array_length (tb->ctors): 0;
for (i = 0; i < num; ++i)
klass->methods [i] = ctorbuilder_to_mono_method (klass, mono_array_get (tb->ctors, MonoReflectionCtorBuilder*, i));
num = tb->num_methods;
j = i;
for (i = 0; i < num; ++i)
klass->methods [j++] = methodbuilder_to_mono_method (klass, mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i));
if (tb->interfaces) {
klass->interface_count = mono_array_length (tb->interfaces);
klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * klass->interface_count);
for (i = 0; i < klass->interface_count; ++i) {
MonoType *iface = mono_type_array_get_and_resolve (tb->interfaces, i);
klass->interfaces [i] = mono_class_from_mono_type (iface);
ensure_runtime_vtable (klass->interfaces [i]);
}
klass->interfaces_inited = 1;
}
} else if (klass->generic_class){
ensure_generic_class_runtime_vtable (klass);
}
if (klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
for (i = 0; i < klass->method.count; ++i)
klass->methods [i]->slot = i;
mono_class_setup_interface_offsets (klass);
mono_class_setup_interface_id (klass);
}
/*
* The generic vtable is needed even if image->run is not set since some
* runtime code like ves_icall_Type_GetMethodsByName depends on
* method->slot being defined.
*/
/*
* tb->methods could not be freed since it is used for determining
* overrides during dynamic vtable construction.
*/
}
static MonoMethod*
mono_reflection_method_get_handle (MonoObject *method)
{
MonoClass *class = mono_object_class (method);
if (is_sr_mono_method (class) || is_sr_mono_generic_method (class)) {
MonoReflectionMethod *sr_method = (MonoReflectionMethod*)method;
return sr_method->method;
}
if (is_sre_method_builder (class)) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)method;
return mb->mhandle;
}
if (is_sre_method_on_tb_inst (class)) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)method;
MonoMethod *result;
/*FIXME move this to a proper method and unify with resolve_object*/
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
} else {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)m->inst);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
MonoMethod *mono_method;
if (is_sre_method_builder (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethodBuilder *)m->mb)->mhandle;
else if (is_sr_mono_method (mono_object_class (m->mb)))
mono_method = ((MonoReflectionMethod *)m->mb)->method;
else
g_error ("resolve_object:: can't handle a MTBI with base_method of type %s", mono_type_get_full_name (mono_object_class (m->mb)));
result = inflate_mono_method (inflated_klass, mono_method, (MonoObject*)m->mb);
}
return result;
}
g_error ("Can't handle methods of type %s:%s", class->name_space, class->name);
return NULL;
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
MonoReflectionTypeBuilder *tb;
int i, onum;
*overrides = NULL;
*num_overrides = 0;
g_assert (klass->image->dynamic);
if (!klass->reflection_info)
return;
g_assert (strcmp (((MonoObject*)klass->reflection_info)->vtable->klass->name, "TypeBuilder") == 0);
tb = (MonoReflectionTypeBuilder*)klass->reflection_info;
onum = 0;
if (tb->methods) {
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method)
onum ++;
}
}
if (onum) {
*overrides = g_new0 (MonoMethod*, onum * 2);
onum = 0;
for (i = 0; i < tb->num_methods; ++i) {
MonoReflectionMethodBuilder *mb =
mono_array_get (tb->methods, MonoReflectionMethodBuilder*, i);
if (mb->override_method) {
(*overrides) [onum * 2] = mono_reflection_method_get_handle ((MonoObject *)mb->override_method);
(*overrides) [onum * 2 + 1] = mb->mhandle;
g_assert (mb->mhandle);
onum ++;
}
}
}
*num_overrides = onum;
}
static void
typebuilder_setup_fields (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = klass->reflection_info;
MonoReflectionFieldBuilder *fb;
MonoClassField *field;
MonoImage *image = klass->image;
const char *p, *p2;
int i;
guint32 len, idx, real_size = 0;
klass->field.count = tb->num_fields;
klass->field.first = 0;
mono_error_init (error);
if (tb->class_size) {
g_assert ((tb->packing_size & 0xfffffff0) == 0);
klass->packing_size = tb->packing_size;
real_size = klass->instance_size + tb->class_size;
}
if (!klass->field.count) {
klass->instance_size = MAX (klass->instance_size, real_size);
return;
}
klass->fields = image_g_new0 (image, MonoClassField, klass->field.count);
mono_class_alloc_ext (klass);
klass->ext->field_def_values = image_g_new0 (image, MonoFieldDefaultValue, klass->field.count);
/*
This is, guess what, a hack.
The issue is that the runtime doesn't know how to setup the fields of a typebuider and crash.
On the static path no field class is resolved, only types are built. This is the right thing to do
but we suck.
Setting size_inited is harmless because we're doing the same job as mono_class_setup_fields anyway.
*/
klass->size_inited = 1;
for (i = 0; i < klass->field.count; ++i) {
fb = mono_array_get (tb->fields, gpointer, i);
field = &klass->fields [i];
field->name = mono_string_to_utf8_image (image, fb->name, error);
if (!mono_error_ok (error))
return;
if (fb->attrs) {
field->type = mono_metadata_type_dup (klass->image, mono_reflection_type_get_handle ((MonoReflectionType*)fb->type));
field->type->attrs = fb->attrs;
} else {
field->type = mono_reflection_type_get_handle ((MonoReflectionType*)fb->type);
}
if ((fb->attrs & FIELD_ATTRIBUTE_HAS_FIELD_RVA) && fb->rva_data)
klass->ext->field_def_values [i].data = mono_array_addr (fb->rva_data, char, 0);
if (fb->offset != -1)
field->offset = fb->offset;
field->parent = klass;
fb->handle = field;
mono_save_custom_attrs (klass->image, field, fb->cattrs);
if (fb->def_value) {
MonoDynamicImage *assembly = (MonoDynamicImage*)klass->image;
field->type->attrs |= FIELD_ATTRIBUTE_HAS_DEFAULT;
idx = encode_constant (assembly, fb->def_value, &klass->ext->field_def_values [i].def_type);
/* Copy the data from the blob since it might get realloc-ed */
p = assembly->blob.data + idx;
len = mono_metadata_decode_blob_size (p, &p2);
len += p2 - p;
klass->ext->field_def_values [i].data = mono_image_alloc (image, len);
memcpy ((gpointer)klass->ext->field_def_values [i].data, p, len);
}
}
klass->instance_size = MAX (klass->instance_size, real_size);
mono_class_layout_fields (klass);
}
static void
typebuilder_setup_properties (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = klass->reflection_info;
MonoReflectionPropertyBuilder *pb;
MonoImage *image = klass->image;
MonoProperty *properties;
int i;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->property.count = tb->properties ? mono_array_length (tb->properties) : 0;
klass->ext->property.first = 0;
properties = image_g_new0 (image, MonoProperty, klass->ext->property.count);
klass->ext->properties = properties;
for (i = 0; i < klass->ext->property.count; ++i) {
pb = mono_array_get (tb->properties, MonoReflectionPropertyBuilder*, i);
properties [i].parent = klass;
properties [i].attrs = pb->attrs;
properties [i].name = mono_string_to_utf8_image (image, pb->name, error);
if (!mono_error_ok (error))
return;
if (pb->get_method)
properties [i].get = pb->get_method->mhandle;
if (pb->set_method)
properties [i].set = pb->set_method->mhandle;
mono_save_custom_attrs (klass->image, &properties [i], pb->cattrs);
}
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
MonoEvent *event = g_new0 (MonoEvent, 1);
MonoClass *klass;
int j;
klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
event->parent = klass;
event->attrs = eb->attrs;
event->name = mono_string_to_utf8 (eb->name);
if (eb->add_method)
event->add = eb->add_method->mhandle;
if (eb->remove_method)
event->remove = eb->remove_method->mhandle;
if (eb->raise_method)
event->raise = eb->raise_method->mhandle;
if (eb->other_methods) {
event->other = g_new0 (MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
event->other [j] = mb->mhandle;
}
}
return mono_event_get_object (mono_object_domain (tb), klass, event);
}
static void
typebuilder_setup_events (MonoClass *klass, MonoError *error)
{
MonoReflectionTypeBuilder *tb = klass->reflection_info;
MonoReflectionEventBuilder *eb;
MonoImage *image = klass->image;
MonoEvent *events;
int i, j;
mono_error_init (error);
if (!klass->ext)
klass->ext = image_g_new0 (image, MonoClassExt, 1);
klass->ext->event.count = tb->events ? mono_array_length (tb->events) : 0;
klass->ext->event.first = 0;
events = image_g_new0 (image, MonoEvent, klass->ext->event.count);
klass->ext->events = events;
for (i = 0; i < klass->ext->event.count; ++i) {
eb = mono_array_get (tb->events, MonoReflectionEventBuilder*, i);
events [i].parent = klass;
events [i].attrs = eb->attrs;
events [i].name = mono_string_to_utf8_image (image, eb->name, error);
if (!mono_error_ok (error))
return;
if (eb->add_method)
events [i].add = eb->add_method->mhandle;
if (eb->remove_method)
events [i].remove = eb->remove_method->mhandle;
if (eb->raise_method)
events [i].raise = eb->raise_method->mhandle;
if (eb->other_methods) {
events [i].other = image_g_new0 (image, MonoMethod*, mono_array_length (eb->other_methods) + 1);
for (j = 0; j < mono_array_length (eb->other_methods); ++j) {
MonoReflectionMethodBuilder *mb =
mono_array_get (eb->other_methods,
MonoReflectionMethodBuilder*, j);
events [i].other [j] = mb->mhandle;
}
}
mono_save_custom_attrs (klass->image, &events [i], eb->cattrs);
}
}
static gboolean
remove_instantiations_of (gpointer key,
gpointer value,
gpointer user_data)
{
MonoType *type = (MonoType*)key;
MonoClass *klass = (MonoClass*)user_data;
if ((type->type == MONO_TYPE_GENERICINST) && (type->data.generic_class->container_class == klass))
return TRUE;
else
return FALSE;
}
static void
check_array_for_usertypes (MonoArray *arr)
{
int i;
if (!arr)
return;
for (i = 0; i < mono_array_length (arr); ++i)
RESOLVE_ARRAY_TYPE_ELEMENT (arr, i);
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
MonoError error;
MonoClass *klass;
MonoDomain* domain;
MonoReflectionType* res;
int i, j;
MONO_ARCH_SAVE_REGS;
domain = mono_object_domain (tb);
klass = mono_class_from_mono_type (tb->type.type);
/*
* Check for user defined Type subclasses.
*/
RESOLVE_TYPE (tb->parent);
check_array_for_usertypes (tb->interfaces);
if (tb->fields) {
for (i = 0; i < mono_array_length (tb->fields); ++i) {
MonoReflectionFieldBuilder *fb = mono_array_get (tb->fields, gpointer, i);
if (fb) {
RESOLVE_TYPE (fb->type);
check_array_for_usertypes (fb->modreq);
check_array_for_usertypes (fb->modopt);
if (fb->marshal_info && fb->marshal_info->marshaltyperef)
RESOLVE_TYPE (fb->marshal_info->marshaltyperef);
}
}
}
if (tb->methods) {
for (i = 0; i < mono_array_length (tb->methods); ++i) {
MonoReflectionMethodBuilder *mb = mono_array_get (tb->methods, gpointer, i);
if (mb) {
RESOLVE_TYPE (mb->rtype);
check_array_for_usertypes (mb->return_modreq);
check_array_for_usertypes (mb->return_modopt);
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
if (tb->ctors) {
for (i = 0; i < mono_array_length (tb->ctors); ++i) {
MonoReflectionCtorBuilder *mb = mono_array_get (tb->ctors, gpointer, i);
if (mb) {
check_array_for_usertypes (mb->parameters);
if (mb->param_modreq)
for (j = 0; j < mono_array_length (mb->param_modreq); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modreq, MonoArray*, j));
if (mb->param_modopt)
for (j = 0; j < mono_array_length (mb->param_modopt); ++j)
check_array_for_usertypes (mono_array_get (mb->param_modopt, MonoArray*, j));
}
}
}
mono_save_custom_attrs (klass->image, klass, tb->cattrs);
/*
* we need to lock the domain because the lock will be taken inside
* So, we need to keep the locking order correct.
*/
mono_loader_lock ();
mono_domain_lock (domain);
if (klass->wastypebuilder) {
mono_domain_unlock (domain);
mono_loader_unlock ();
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
/*
* Fields to set in klass:
* the various flags: delegate/unicode/contextbound etc.
*/
klass->flags = tb->attrs;
klass->has_cctor = 1;
klass->has_finalize = 1;
#if 0
if (!((MonoDynamicImage*)klass->image)->run) {
if (klass->generic_container) {
/* FIXME: The code below can't handle generic classes */
klass->wastypebuilder = TRUE;
mono_loader_unlock ();
mono_domain_unlock (domain);
return mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
}
}
#endif
/* enums are done right away */
if (!klass->enumtype)
ensure_runtime_vtable (klass);
if (tb->subtypes) {
for (i = 0; i < mono_array_length (tb->subtypes); ++i) {
MonoReflectionTypeBuilder *subtb = mono_array_get (tb->subtypes, MonoReflectionTypeBuilder*, i);
mono_class_alloc_ext (klass);
klass->ext->nested_classes = g_list_prepend_image (klass->image, klass->ext->nested_classes, mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)subtb)));
}
}
klass->nested_classes_inited = TRUE;
/* fields and object layout */
if (klass->parent) {
if (!klass->parent->size_inited)
mono_class_init (klass->parent);
klass->instance_size = klass->parent->instance_size;
klass->sizes.class_size = 0;
klass->min_align = klass->parent->min_align;
/* if the type has no fields we won't call the field_setup
* routine which sets up klass->has_references.
*/
klass->has_references |= klass->parent->has_references;
} else {
klass->instance_size = sizeof (MonoObject);
klass->min_align = 1;
}
/* FIXME: handle packing_size and instance_size */
typebuilder_setup_fields (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_properties (klass, &error);
if (!mono_error_ok (&error))
goto failure;
typebuilder_setup_events (klass, &error);
if (!mono_error_ok (&error))
goto failure;
klass->wastypebuilder = TRUE;
/*
* If we are a generic TypeBuilder, there might be instantiations in the type cache
* which have type System.Reflection.MonoGenericClass, but after the type is created,
* we want to return normal System.MonoType objects, so clear these out from the cache.
*/
if (domain->type_hash && klass->generic_container)
mono_g_hash_table_foreach_remove (domain->type_hash, remove_instantiations_of, klass);
mono_domain_unlock (domain);
mono_loader_unlock ();
if (klass->enumtype && !mono_class_is_valid_enum (klass)) {
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
mono_raise_exception (mono_get_exception_type_load (tb->name, NULL));
}
res = mono_type_get_object (mono_object_domain (tb), &klass->byval_arg);
g_assert (res != (MonoReflectionType*)tb);
return res;
failure:
mono_class_set_failure (klass, MONO_EXCEPTION_TYPE_LOAD, NULL);
klass->wastypebuilder = TRUE;
mono_domain_unlock (domain);
mono_loader_unlock ();
mono_error_raise_exception (&error);
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
MonoGenericParamFull *param;
MonoImage *image;
MonoClass *pklass;
MONO_ARCH_SAVE_REGS;
param = g_new0 (MonoGenericParamFull, 1);
if (gparam->mbuilder) {
if (!gparam->mbuilder->generic_container) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder *)gparam->mbuilder->type;
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)tb));
gparam->mbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->mbuilder->generic_container->is_method = TRUE;
/*
* Cannot set owner.method, since the MonoMethod is not created yet.
* Set the image field instead, so type_in_image () works.
*/
gparam->mbuilder->generic_container->image = klass->image;
}
param->param.owner = gparam->mbuilder->generic_container;
} else if (gparam->tbuilder) {
if (!gparam->tbuilder->generic_container) {
MonoClass *klass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)gparam->tbuilder));
gparam->tbuilder->generic_container = mono_image_alloc0 (klass->image, sizeof (MonoGenericContainer));
gparam->tbuilder->generic_container->owner.klass = klass;
}
param->param.owner = gparam->tbuilder->generic_container;
}
param->info.name = mono_string_to_utf8 (gparam->name);
param->param.num = gparam->index;
image = &gparam->tbuilder->module->dynamic_image->image;
pklass = mono_class_from_generic_parameter ((MonoGenericParam *) param, image, gparam->mbuilder != NULL);
gparam->type.type = &pklass->byval_arg;
MOVING_GC_REGISTER (&pklass->reflection_info);
pklass->reflection_info = gparam; /* FIXME: GC pin gparam */
mono_image_lock (image);
image->reflection_info_unregister_classes = g_slist_prepend (image->reflection_info_unregister_classes, pklass);
mono_image_unlock (image);
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
MonoReflectionModuleBuilder *module = sig->module;
MonoDynamicImage *assembly = module != NULL ? module->dynamic_image : NULL;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x07);
sigbuffer_add_value (&buf, na);
if (assembly != NULL){
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
MonoDynamicImage *assembly = sig->module->dynamic_image;
guint32 na = sig->arguments ? mono_array_length (sig->arguments) : 0;
guint32 buflen, i;
MonoArray *result;
SigBuffer buf;
check_array_for_usertypes (sig->arguments);
sigbuffer_init (&buf, 32);
sigbuffer_add_value (&buf, 0x06);
for (i = 0; i < na; ++i) {
MonoReflectionType *type = mono_array_get (sig->arguments, MonoReflectionType*, i);
encode_reflection_type (assembly, type, &buf);
}
buflen = buf.p - buf.buf;
result = mono_array_new (mono_domain_get (), mono_defaults.byte_class, buflen);
memcpy (mono_array_addr (result, char, 0), buf.buf, buflen);
sigbuffer_free (&buf);
return result;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
ReflectionMethodBuilder rmb;
MonoMethodSignature *sig;
MonoClass *klass;
GSList *l;
int i;
sig = dynamic_method_to_signature (mb);
reflection_methodbuilder_from_dynamic_method (&rmb, mb);
/*
* Resolve references.
*/
/*
* Every second entry in the refs array is reserved for storing handle_class,
* which is needed by the ldtoken implementation in the JIT.
*/
rmb.nrefs = mb->nrefs;
rmb.refs = g_new0 (gpointer, mb->nrefs + 1);
for (i = 0; i < mb->nrefs; i += 2) {
MonoClass *handle_class;
gpointer ref;
MonoObject *obj = mono_array_get (mb->refs, MonoObject*, i);
if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/*
* The referenced DynamicMethod should already be created by the managed
* code, except in the case of circular references. In that case, we store
* method in the refs array, and fix it up later when the referenced
* DynamicMethod is created.
*/
if (method->mhandle) {
ref = method->mhandle;
} else {
/* FIXME: GC object stored in unmanaged memory */
ref = method;
/* FIXME: GC object stored in unmanaged memory */
method->referenced_by = g_slist_append (method->referenced_by, mb);
}
handle_class = mono_defaults.methodhandle_class;
} else {
MonoException *ex = NULL;
ref = resolve_object (mb->module->image, obj, &handle_class, NULL);
if (!ref)
ex = mono_get_exception_type_load (NULL, NULL);
else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
ex = mono_security_core_clr_ensure_dynamic_method_resolved_object (ref, handle_class);
if (ex) {
g_free (rmb.refs);
mono_raise_exception (ex);
return;
}
}
rmb.refs [i] = ref; /* FIXME: GC object stored in unmanaged memory (change also resolve_object() signature) */
rmb.refs [i + 1] = handle_class;
}
klass = mb->owner ? mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)mb->owner)) : mono_defaults.object_class;
mb->mhandle = reflection_methodbuilder_to_mono_method (klass, &rmb, sig);
/* Fix up refs entries pointing at us */
for (l = mb->referenced_by; l; l = l->next) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)l->data;
MonoMethodWrapper *wrapper = (MonoMethodWrapper*)method->mhandle;
gpointer *data;
g_assert (method->mhandle);
data = (gpointer*)wrapper->method_data;
for (i = 0; i < GPOINTER_TO_UINT (data [0]); i += 2) {
if ((data [i + 1] == mb) && (data [i + 1 + 1] == mono_defaults.methodhandle_class))
data [i + 1] = mb->mhandle;
}
}
g_slist_free (mb->referenced_by);
g_free (rmb.refs);
/* ilgen is no longer needed */
mb->ilgen = NULL;
}
#endif /* DISABLE_REFLECTION_EMIT */
void
mono_reflection_destroy_dynamic_method (MonoReflectionDynamicMethod *mb)
{
g_assert (mb);
if (mb->mhandle)
mono_runtime_free_method (
mono_object_get_domain ((MonoObject*)mb), mb->mhandle);
}
/**
*
* mono_reflection_is_valid_dynamic_token:
*
* Returns TRUE if token is valid.
*
*/
gboolean
mono_reflection_is_valid_dynamic_token (MonoDynamicImage *image, guint32 token)
{
return mono_g_hash_table_lookup (image->tokens, GUINT_TO_POINTER (token)) != NULL;
}
#ifndef DISABLE_REFLECTION_EMIT
/**
* mono_reflection_lookup_dynamic_token:
*
* Finish the Builder object pointed to by TOKEN and return the corresponding
* runtime structure. If HANDLE_CLASS is not NULL, it is set to the class required by
* mono_ldtoken. If valid_token is TRUE, assert if it is not found in the token->object
* mapping table.
*
* LOCKING: Take the loader lock
*/
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
MonoDynamicImage *assembly = (MonoDynamicImage*)image;
MonoObject *obj;
MonoClass *klass;
mono_loader_lock ();
obj = mono_g_hash_table_lookup (assembly->tokens, GUINT_TO_POINTER (token));
mono_loader_unlock ();
if (!obj) {
if (valid_token)
g_error ("Could not find required dynamic token 0x%08x", token);
else
return NULL;
}
if (!handle_class)
handle_class = &klass;
return resolve_object (image, obj, handle_class, context);
}
/*
* ensure_complete_type:
*
* Ensure that KLASS is completed if it is a dynamic type, or references
* dynamic types.
*/
static void
ensure_complete_type (MonoClass *klass)
{
if (klass->image->dynamic && !klass->wastypebuilder) {
MonoReflectionTypeBuilder *tb = klass->reflection_info;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
// Asserting here could break a lot of code
//g_assert (klass->wastypebuilder);
}
if (klass->generic_class) {
MonoGenericInst *inst = klass->generic_class->context.class_inst;
int i;
for (i = 0; i < inst->type_argc; ++i) {
ensure_complete_type (mono_class_from_mono_type (inst->type_argv [i]));
}
}
}
static gpointer
resolve_object (MonoImage *image, MonoObject *obj, MonoClass **handle_class, MonoGenericContext *context)
{
gpointer result = NULL;
if (strcmp (obj->vtable->klass->name, "String") == 0) {
result = mono_string_intern ((MonoString*)obj);
*handle_class = mono_defaults.string_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoType") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
} else {
result = mono_class_from_mono_type (type);
}
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MonoMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericCMethod") == 0 ||
strcmp (obj->vtable->klass->name, "MonoGenericMethod") == 0) {
result = ((MonoReflectionMethod*)obj)->method;
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "MethodBuilder") == 0) {
MonoReflectionMethodBuilder *mb = (MonoReflectionMethodBuilder*)obj;
result = mb->mhandle;
if (!result) {
/* Type is not yet created */
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)mb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
/*
* Hopefully this has been filled in by calling CreateType() on the
* TypeBuilder.
*/
/*
* TODO: This won't work if the application finishes another
* TypeBuilder instance instead of this one.
*/
result = mb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorBuilder") == 0) {
MonoReflectionCtorBuilder *cb = (MonoReflectionCtorBuilder*)obj;
result = cb->mhandle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)cb->type;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = cb->mhandle;
}
if (context)
result = mono_class_inflate_generic_method (result, context);
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoField") == 0) {
MonoClassField *field = ((MonoReflectionField*)obj)->field;
ensure_complete_type (field->parent);
if (context) {
MonoType *inflated = mono_class_inflate_generic_type (&field->parent->byval_arg, context);
MonoClass *class = mono_class_from_mono_type (inflated);
MonoClassField *inflated_field;
gpointer iter = NULL;
mono_metadata_free_type (inflated);
while ((inflated_field = mono_class_get_fields (class, &iter))) {
if (!strcmp (field->name, inflated_field->name))
break;
}
g_assert (inflated_field && !strcmp (field->name, inflated_field->name));
result = inflated_field;
} else {
result = field;
}
*handle_class = mono_defaults.fieldhandle_class;
g_assert (result);
} else if (strcmp (obj->vtable->klass->name, "FieldBuilder") == 0) {
MonoReflectionFieldBuilder *fb = (MonoReflectionFieldBuilder*)obj;
result = fb->handle;
if (!result) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)fb->typeb;
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = fb->handle;
}
if (fb->handle && fb->handle->parent->generic_container) {
MonoClass *klass = fb->handle->parent;
MonoType *type = mono_class_inflate_generic_type (&klass->byval_arg, context);
MonoClass *inflated = mono_class_from_mono_type (type);
result = mono_class_get_field_from_name (inflated, mono_field_get_name (fb->handle));
g_assert (result);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "TypeBuilder") == 0) {
MonoReflectionTypeBuilder *tb = (MonoReflectionTypeBuilder*)obj;
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)tb);
MonoClass *klass;
klass = type->data.klass;
if (klass->wastypebuilder) {
/* Already created */
result = klass;
}
else {
mono_domain_try_type_resolve (mono_domain_get (), NULL, (MonoObject*)tb);
result = type->data.klass;
g_assert (result);
}
*handle_class = mono_defaults.typehandle_class;
} else if (strcmp (obj->vtable->klass->name, "SignatureHelper") == 0) {
MonoReflectionSigHelper *helper = (MonoReflectionSigHelper*)obj;
MonoMethodSignature *sig;
int nargs, i;
if (helper->arguments)
nargs = mono_array_length (helper->arguments);
else
nargs = 0;
sig = mono_metadata_signature_alloc (image, nargs);
sig->explicit_this = helper->call_conv & 64 ? 1 : 0;
sig->hasthis = helper->call_conv & 32 ? 1 : 0;
if (helper->unmanaged_call_conv) { /* unmanaged */
sig->call_convention = helper->unmanaged_call_conv - 1;
sig->pinvoke = TRUE;
} else if (helper->call_conv & 0x02) {
sig->call_convention = MONO_CALL_VARARG;
} else {
sig->call_convention = MONO_CALL_DEFAULT;
}
sig->param_count = nargs;
/* TODO: Copy type ? */
sig->ret = helper->return_type->type;
for (i = 0; i < nargs; ++i)
sig->params [i] = mono_type_array_get_and_resolve (helper->arguments, i);
result = sig;
*handle_class = NULL;
} else if (strcmp (obj->vtable->klass->name, "DynamicMethod") == 0) {
MonoReflectionDynamicMethod *method = (MonoReflectionDynamicMethod*)obj;
/* Already created by the managed code */
g_assert (method->mhandle);
result = method->mhandle;
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "GenericTypeParameterBuilder") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MonoGenericClass") == 0) {
MonoType *type = mono_reflection_type_get_handle ((MonoReflectionType*)obj);
type = mono_class_inflate_generic_type (type, context);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
g_assert (result);
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "FieldOnTypeBuilderInst") == 0) {
MonoReflectionFieldOnTypeBuilderInst *f = (MonoReflectionFieldOnTypeBuilderInst*)obj;
MonoClass *inflated;
MonoType *type;
type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)f->inst), context);
inflated = mono_class_from_mono_type (type);
g_assert (f->fb->handle);
result = mono_class_get_field_from_name (inflated, mono_field_get_name (f->fb->handle));
g_assert (result);
mono_metadata_free_type (type);
*handle_class = mono_defaults.fieldhandle_class;
} else if (strcmp (obj->vtable->klass->name, "ConstructorOnTypeBuilderInst") == 0) {
MonoReflectionCtorOnTypeBuilderInst *c = (MonoReflectionCtorOnTypeBuilderInst*)obj;
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)c->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
g_assert (c->cb->mhandle);
result = inflate_mono_method (inflated_klass, c->cb->mhandle, (MonoObject*)c->cb);
*handle_class = mono_defaults.methodhandle_class;
mono_metadata_free_type (type);
} else if (strcmp (obj->vtable->klass->name, "MethodOnTypeBuilderInst") == 0) {
MonoReflectionMethodOnTypeBuilderInst *m = (MonoReflectionMethodOnTypeBuilderInst*)obj;
if (m->method_args) {
result = mono_reflection_method_on_tb_inst_get_handle (m);
} else {
MonoType *type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)m->inst), context);
MonoClass *inflated_klass = mono_class_from_mono_type (type);
g_assert (m->mb->mhandle);
result = inflate_mono_method (inflated_klass, m->mb->mhandle, (MonoObject*)m->mb);
mono_metadata_free_type (type);
}
*handle_class = mono_defaults.methodhandle_class;
} else if (strcmp (obj->vtable->klass->name, "MonoArrayMethod") == 0) {
MonoReflectionArrayMethod *m = (MonoReflectionArrayMethod*)obj;
MonoType *mtype;
MonoClass *klass;
MonoMethod *method;
gpointer iter;
char *name;
mtype = mono_reflection_type_get_handle (m->parent);
klass = mono_class_from_mono_type (mtype);
/* Find the method */
name = mono_string_to_utf8 (m->name);
iter = NULL;
while ((method = mono_class_get_methods (klass, &iter))) {
if (!strcmp (method->name, name))
break;
}
g_free (name);
// FIXME:
g_assert (method);
// FIXME: Check parameters/return value etc. match
result = method;
*handle_class = mono_defaults.methodhandle_class;
} else if (is_sre_array (mono_object_get_class(obj)) ||
is_sre_byref (mono_object_get_class(obj)) ||
is_sre_pointer (mono_object_get_class(obj))) {
MonoReflectionType *ref_type = (MonoReflectionType *)obj;
MonoType *type = mono_reflection_type_get_handle (ref_type);
result = mono_class_from_mono_type (type);
*handle_class = mono_defaults.typehandle_class;
} else {
g_print ("%s\n", obj->vtable->klass->name);
g_assert_not_reached ();
}
return result;
}
#else /* DISABLE_REFLECTION_EMIT */
MonoArray*
mono_reflection_get_custom_attrs_blob (MonoReflectionAssembly *assembly, MonoObject *ctor, MonoArray *ctorArgs, MonoArray *properties, MonoArray *propValues, MonoArray *fields, MonoArray* fieldValues)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_setup_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_setup_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_generic_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_reflection_create_internal_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
}
void
mono_image_basic_init (MonoReflectionAssemblyBuilder *assemblyb)
{
g_error ("This mono runtime was configured with --enable-minimal=reflection_emit, so System.Reflection.Emit is not supported.");
}
void
mono_image_module_basic_init (MonoReflectionModuleBuilder *moduleb)
{
g_assert_not_reached ();
}
void
mono_image_set_wrappers_type (MonoReflectionModuleBuilder *moduleb, MonoReflectionType *type)
{
g_assert_not_reached ();
}
MonoReflectionModule *
mono_image_load_module_dynamic (MonoReflectionAssemblyBuilder *ab, MonoString *fileName)
{
g_assert_not_reached ();
return NULL;
}
guint32
mono_image_insert_string (MonoReflectionModuleBuilder *module, MonoString *str)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_method_token (MonoDynamicImage *assembly, MonoObject *obj, MonoArray *opt_param_types)
{
g_assert_not_reached ();
return 0;
}
guint32
mono_image_create_token (MonoDynamicImage *assembly, MonoObject *obj,
gboolean create_methodspec, gboolean register_token)
{
g_assert_not_reached ();
return 0;
}
void
mono_image_register_token (MonoDynamicImage *assembly, guint32 token, MonoObject *obj)
{
}
void
mono_reflection_generic_class_initialize (MonoReflectionGenericClass *type, MonoArray *methods,
MonoArray *ctors, MonoArray *fields, MonoArray *properties,
MonoArray *events)
{
g_assert_not_reached ();
}
void
mono_reflection_get_dynamic_overrides (MonoClass *klass, MonoMethod ***overrides, int *num_overrides)
{
*overrides = NULL;
*num_overrides = 0;
}
MonoReflectionEvent *
mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb)
{
g_assert_not_reached ();
return NULL;
}
MonoReflectionType*
mono_reflection_create_runtime_class (MonoReflectionTypeBuilder *tb)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_initialize_generic_parameter (MonoReflectionGenericParam *gparam)
{
g_assert_not_reached ();
}
MonoArray *
mono_reflection_sighelper_get_signature_local (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
MonoArray *
mono_reflection_sighelper_get_signature_field (MonoReflectionSigHelper *sig)
{
g_assert_not_reached ();
return NULL;
}
void
mono_reflection_create_dynamic_method (MonoReflectionDynamicMethod *mb)
{
}
gpointer
mono_reflection_lookup_dynamic_token (MonoImage *image, guint32 token, gboolean valid_token, MonoClass **handle_class, MonoGenericContext *context)
{
return NULL;
}
MonoType*
mono_reflection_type_get_handle (MonoReflectionType* ref)
{
if (!ref)
return NULL;
return ref->type;
}
#endif /* DISABLE_REFLECTION_EMIT */
/* SECURITY_ACTION_* are defined in mono/metadata/tabledefs.h */
const static guint32 declsec_flags_map[] = {
0x00000000, /* empty */
MONO_DECLSEC_FLAG_REQUEST, /* SECURITY_ACTION_REQUEST (x01) */
MONO_DECLSEC_FLAG_DEMAND, /* SECURITY_ACTION_DEMAND (x02) */
MONO_DECLSEC_FLAG_ASSERT, /* SECURITY_ACTION_ASSERT (x03) */
MONO_DECLSEC_FLAG_DENY, /* SECURITY_ACTION_DENY (x04) */
MONO_DECLSEC_FLAG_PERMITONLY, /* SECURITY_ACTION_PERMITONLY (x05) */
MONO_DECLSEC_FLAG_LINKDEMAND, /* SECURITY_ACTION_LINKDEMAND (x06) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND, /* SECURITY_ACTION_INHERITANCEDEMAND (x07) */
MONO_DECLSEC_FLAG_REQUEST_MINIMUM, /* SECURITY_ACTION_REQUEST_MINIMUM (x08) */
MONO_DECLSEC_FLAG_REQUEST_OPTIONAL, /* SECURITY_ACTION_REQUEST_OPTIONAL (x09) */
MONO_DECLSEC_FLAG_REQUEST_REFUSE, /* SECURITY_ACTION_REQUEST_REFUSE (x0A) */
MONO_DECLSEC_FLAG_PREJIT_GRANT, /* SECURITY_ACTION_PREJIT_GRANT (x0B) */
MONO_DECLSEC_FLAG_PREJIT_DENY, /* SECURITY_ACTION_PREJIT_DENY (x0C) */
MONO_DECLSEC_FLAG_NONCAS_DEMAND, /* SECURITY_ACTION_NONCAS_DEMAND (x0D) */
MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND, /* SECURITY_ACTION_NONCAS_LINKDEMAND (x0E) */
MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND, /* SECURITY_ACTION_NONCAS_INHERITANCEDEMAND (x0F) */
MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE, /* SECURITY_ACTION_LINKDEMAND_CHOICE (x10) */
MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE, /* SECURITY_ACTION_INHERITANCEDEMAND_CHOICE (x11) */
MONO_DECLSEC_FLAG_DEMAND_CHOICE, /* SECURITY_ACTION_DEMAND_CHOICE (x12) */
};
/*
* Returns flags that includes all available security action associated to the handle.
* @token: metadata token (either for a class or a method)
* @image: image where resides the metadata.
*/
static guint32
mono_declsec_get_flags (MonoImage *image, guint32 token)
{
int index = mono_metadata_declsec_from_index (image, token);
MonoTableInfo *t = &image->tables [MONO_TABLE_DECLSECURITY];
guint32 result = 0;
guint32 action;
int i;
/* HasSecurity can be present for other, not specially encoded, attributes,
e.g. SuppressUnmanagedCodeSecurityAttribute */
if (index < 0)
return 0;
for (i = index; i < t->rows; i++) {
guint32 cols [MONO_DECL_SECURITY_SIZE];
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
break;
action = cols [MONO_DECL_SECURITY_ACTION];
if ((action >= MONO_DECLSEC_ACTION_MIN) && (action <= MONO_DECLSEC_ACTION_MAX)) {
result |= declsec_flags_map [action];
} else {
g_assert_not_reached ();
}
}
return result;
}
/*
* Get the security actions (in the form of flags) associated with the specified method.
*
* @method: The method for which we want the declarative security flags.
* Return the declarative security flags for the method (only).
*
* Note: To keep MonoMethod size down we do not cache the declarative security flags
* (except for the stack modifiers which are kept in the MonoJitInfo structure)
*/
guint32
mono_declsec_flags_from_method (MonoMethod *method)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
/* FIXME: No cache (for the moment) */
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return mono_declsec_get_flags (method->klass->image, idx);
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified class.
*
* @klass: The class for which we want the declarative security flags.
* Return the declarative security flags for the class.
*
* Note: We cache the flags inside the MonoClass structure as this will get
* called very often (at least for each method).
*/
guint32
mono_declsec_flags_from_class (MonoClass *klass)
{
if (klass->flags & TYPE_ATTRIBUTE_HAS_SECURITY) {
if (!klass->ext || !klass->ext->declsec_flags) {
guint32 idx;
idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
mono_loader_lock ();
mono_class_alloc_ext (klass);
mono_loader_unlock ();
/* we cache the flags on classes */
klass->ext->declsec_flags = mono_declsec_get_flags (klass->image, idx);
}
return klass->ext->declsec_flags;
}
return 0;
}
/*
* Get the security actions (in the form of flags) associated with the specified assembly.
*
* @assembly: The assembly for which we want the declarative security flags.
* Return the declarative security flags for the assembly.
*/
guint32
mono_declsec_flags_from_assembly (MonoAssembly *assembly)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return mono_declsec_get_flags (assembly->image, idx);
}
/*
* Fill actions for the specific index (which may either be an encoded class token or
* an encoded method token) from the metadata image.
* Returns TRUE if some actions requiring code generation are present, FALSE otherwise.
*/
static MonoBoolean
fill_actions_from_index (MonoImage *image, guint32 token, MonoDeclSecurityActions* actions,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
MonoBoolean result = FALSE;
MonoTableInfo *t;
guint32 cols [MONO_DECL_SECURITY_SIZE];
int index = mono_metadata_declsec_from_index (image, token);
int i;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
if (cols [MONO_DECL_SECURITY_PARENT] != token)
return result;
/* if present only replace (class) permissions with method permissions */
/* if empty accept either class or method permissions */
if (cols [MONO_DECL_SECURITY_ACTION] == id_std) {
if (!actions->demand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demand.blob = (char*) (blob + 2);
actions->demand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_noncas) {
if (!actions->noncasdemand.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->noncasdemand.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->noncasdemand.blob = (char*) (blob + 2);
actions->noncasdemand.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
} else if (cols [MONO_DECL_SECURITY_ACTION] == id_choice) {
if (!actions->demandchoice.blob) {
const char *blob = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
actions->demandchoice.index = cols [MONO_DECL_SECURITY_PERMISSIONSET];
actions->demandchoice.blob = (char*) (blob + 2);
actions->demandchoice.size = mono_metadata_decode_blob_size (blob, &blob);
result = TRUE;
}
}
}
return result;
}
static MonoBoolean
mono_declsec_get_class_demands_params (MonoClass *klass, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return fill_actions_from_index (klass->image, idx, demands, id_std, id_noncas, id_choice);
}
static MonoBoolean
mono_declsec_get_method_demands_params (MonoMethod *method, MonoDeclSecurityActions* demands,
guint32 id_std, guint32 id_noncas, guint32 id_choice)
{
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return fill_actions_from_index (method->klass->image, idx, demands, id_std, id_noncas, id_choice);
}
/*
* Collect all actions (that requires to generate code in mini) assigned for
* the specified method.
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_demands (MonoMethod *method, MonoDeclSecurityActions* demands)
{
guint32 mask = MONO_DECLSEC_FLAG_DEMAND | MONO_DECLSEC_FLAG_NONCAS_DEMAND |
MONO_DECLSEC_FLAG_DEMAND_CHOICE;
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result = mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & mask) {
if (!result) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
}
result |= mono_declsec_get_class_demands_params (method->klass, demands,
SECURITY_ACTION_DEMAND, SECURITY_ACTION_NONCASDEMAND, SECURITY_ACTION_DEMANDCHOICE);
}
/* The boolean return value is used as a shortcut in case nothing needs to
be generated (e.g. LinkDemand[Choice] and InheritanceDemand[Choice]) */
return result;
}
/*
* Collect all Link actions: LinkDemand, NonCasLinkDemand and LinkDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_linkdemands (MonoMethod *method, MonoDeclSecurityActions* klass, MonoDeclSecurityActions *cmethod)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
/* results are independant - zeroize both */
memset (cmethod, 0, sizeof (MonoDeclSecurityActions));
memset (klass, 0, sizeof (MonoDeclSecurityActions));
/* First we look for method-level attributes */
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
result = mono_declsec_get_method_demands_params (method, cmethod,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (method->klass);
if (flags & (MONO_DECLSEC_FLAG_LINKDEMAND | MONO_DECLSEC_FLAG_NONCAS_LINKDEMAND | MONO_DECLSEC_FLAG_LINKDEMAND_CHOICE)) {
mono_class_init (method->klass);
result |= mono_declsec_get_class_demands_params (method->klass, klass,
SECURITY_ACTION_LINKDEMAND, SECURITY_ACTION_NONCASLINKDEMAND, SECURITY_ACTION_LINKDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* @klass The inherited class - this is the class that provides the security check (attributes)
* @demans
* return TRUE if inheritance demands (any kind) are present, FALSE otherwise.
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_class (MonoClass *klass, MonoDeclSecurityActions* demands)
{
MonoBoolean result = FALSE;
guint32 flags;
/* quick exit if no declarative security is present in the metadata */
if (!klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* Here we use (or create) the class declarative cache to look for demands */
flags = mono_declsec_flags_from_class (klass);
if (flags & (MONO_DECLSEC_FLAG_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_NONCAS_INHERITANCEDEMAND | MONO_DECLSEC_FLAG_INHERITANCEDEMAND_CHOICE)) {
mono_class_init (klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
result |= mono_declsec_get_class_demands_params (klass, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return result;
}
/*
* Collect all Inherit actions: InheritanceDemand, NonCasInheritanceDemand and InheritanceDemandChoice (2.0).
*
* Note: Don't use the content of actions if the function return FALSE.
*/
MonoBoolean
mono_declsec_get_inheritdemands_method (MonoMethod *method, MonoDeclSecurityActions* demands)
{
/* quick exit if no declarative security is present in the metadata */
if (!method->klass->image->tables [MONO_TABLE_DECLSECURITY].rows)
return FALSE;
/* we want the original as the wrapper is "free" of the security informations */
if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || method->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED) {
method = mono_marshal_method_from_wrapper (method);
if (!method)
return FALSE;
}
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
mono_class_init (method->klass);
memset (demands, 0, sizeof (MonoDeclSecurityActions));
return mono_declsec_get_method_demands_params (method, demands,
SECURITY_ACTION_INHERITDEMAND, SECURITY_ACTION_NONCASINHERITANCE, SECURITY_ACTION_INHERITDEMANDCHOICE);
}
return FALSE;
}
static MonoBoolean
get_declsec_action (MonoImage *image, guint32 token, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 cols [MONO_DECL_SECURITY_SIZE];
MonoTableInfo *t;
int i;
int index = mono_metadata_declsec_from_index (image, token);
if (index == -1)
return FALSE;
t = &image->tables [MONO_TABLE_DECLSECURITY];
for (i = index; i < t->rows; i++) {
mono_metadata_decode_row (t, i, cols, MONO_DECL_SECURITY_SIZE);
/* shortcut - index are ordered */
if (token != cols [MONO_DECL_SECURITY_PARENT])
return FALSE;
if (cols [MONO_DECL_SECURITY_ACTION] == action) {
const char *metadata = mono_metadata_blob_heap (image, cols [MONO_DECL_SECURITY_PERMISSIONSET]);
entry->blob = (char*) (metadata + 2);
entry->size = mono_metadata_decode_blob_size (metadata, &metadata);
return TRUE;
}
}
return FALSE;
}
MonoBoolean
mono_declsec_get_method_action (MonoMethod *method, guint32 action, MonoDeclSecurityEntry *entry)
{
if (method->flags & METHOD_ATTRIBUTE_HAS_SECURITY) {
guint32 idx = mono_method_get_index (method);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_METHODDEF;
return get_declsec_action (method->klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_class_action (MonoClass *klass, guint32 action, MonoDeclSecurityEntry *entry)
{
/* use cache */
guint32 flags = mono_declsec_flags_from_class (klass);
if (declsec_flags_map [action] & flags) {
guint32 idx = mono_metadata_token_index (klass->type_token);
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_TYPEDEF;
return get_declsec_action (klass->image, idx, action, entry);
}
return FALSE;
}
MonoBoolean
mono_declsec_get_assembly_action (MonoAssembly *assembly, guint32 action, MonoDeclSecurityEntry *entry)
{
guint32 idx = 1; /* there is only one assembly */
idx <<= MONO_HAS_DECL_SECURITY_BITS;
idx |= MONO_HAS_DECL_SECURITY_ASSEMBLY;
return get_declsec_action (assembly->image, idx, action, entry);
}
gboolean
mono_reflection_call_is_assignable_to (MonoClass *klass, MonoClass *oklass)
{
MonoObject *res, *exc;
void *params [1];
static MonoClass *System_Reflection_Emit_TypeBuilder = NULL;
static MonoMethod *method = NULL;
if (!System_Reflection_Emit_TypeBuilder) {
System_Reflection_Emit_TypeBuilder = mono_class_from_name (mono_defaults.corlib, "System.Reflection.Emit", "TypeBuilder");
g_assert (System_Reflection_Emit_TypeBuilder);
}
if (method == NULL) {
method = mono_class_get_method_from_name (System_Reflection_Emit_TypeBuilder, "IsAssignableTo", 1);
g_assert (method);
}
/*
* The result of mono_type_get_object () might be a System.MonoType but we
* need a TypeBuilder so use klass->reflection_info.
*/
g_assert (klass->reflection_info);
g_assert (!strcmp (((MonoObject*)(klass->reflection_info))->vtable->klass->name, "TypeBuilder"));
params [0] = mono_type_get_object (mono_domain_get (), &oklass->byval_arg);
res = mono_runtime_invoke (method, (MonoObject*)(klass->reflection_info), params, &exc);
if (exc)
return FALSE;
else
return *(MonoBoolean*)mono_object_unbox (res);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4716_0 |
crossvul-cpp_data_good_5653_0 | /*
* Per core/cpu state
*
* Used to coordinate shared registers between HT threads or
* among events on a single PMU.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/stddef.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/hardirq.h>
#include <asm/apic.h>
#include "perf_event.h"
/*
* Intel PerfMon, used on Core and later.
*/
static u64 intel_perfmon_event_map[PERF_COUNT_HW_MAX] __read_mostly =
{
[PERF_COUNT_HW_CPU_CYCLES] = 0x003c,
[PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0,
[PERF_COUNT_HW_CACHE_REFERENCES] = 0x4f2e,
[PERF_COUNT_HW_CACHE_MISSES] = 0x412e,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c4,
[PERF_COUNT_HW_BRANCH_MISSES] = 0x00c5,
[PERF_COUNT_HW_BUS_CYCLES] = 0x013c,
[PERF_COUNT_HW_REF_CPU_CYCLES] = 0x0300, /* pseudo-encoding */
};
static struct event_constraint intel_core_event_constraints[] __read_mostly =
{
INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */
INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */
INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */
INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */
INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */
INTEL_EVENT_CONSTRAINT(0xc1, 0x1), /* FP_COMP_INSTR_RET */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_core2_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x10, 0x1), /* FP_COMP_OPS_EXE */
INTEL_EVENT_CONSTRAINT(0x11, 0x2), /* FP_ASSIST */
INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */
INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */
INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */
INTEL_EVENT_CONSTRAINT(0x18, 0x1), /* IDLE_DURING_DIV */
INTEL_EVENT_CONSTRAINT(0x19, 0x2), /* DELAYED_BYPASS */
INTEL_EVENT_CONSTRAINT(0xa1, 0x1), /* RS_UOPS_DISPATCH_CYCLES */
INTEL_EVENT_CONSTRAINT(0xc9, 0x1), /* ITLB_MISS_RETIRED (T30-9) */
INTEL_EVENT_CONSTRAINT(0xcb, 0x1), /* MEM_LOAD_RETIRED */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_nehalem_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x40, 0x3), /* L1D_CACHE_LD */
INTEL_EVENT_CONSTRAINT(0x41, 0x3), /* L1D_CACHE_ST */
INTEL_EVENT_CONSTRAINT(0x42, 0x3), /* L1D_CACHE_LOCK */
INTEL_EVENT_CONSTRAINT(0x43, 0x3), /* L1D_ALL_REF */
INTEL_EVENT_CONSTRAINT(0x48, 0x3), /* L1D_PEND_MISS */
INTEL_EVENT_CONSTRAINT(0x4e, 0x3), /* L1D_PREFETCH */
INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */
INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_nehalem_extra_regs[] __read_mostly =
{
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0),
EVENT_EXTRA_END
};
static struct event_constraint intel_westmere_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_EVENT_CONSTRAINT(0x51, 0x3), /* L1D */
INTEL_EVENT_CONSTRAINT(0x60, 0x1), /* OFFCORE_REQUESTS_OUTSTANDING */
INTEL_EVENT_CONSTRAINT(0x63, 0x3), /* CACHE_LOCK_CYCLES */
INTEL_EVENT_CONSTRAINT(0xb3, 0x1), /* SNOOPQ_REQUEST_OUTSTANDING */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_snb_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_NO_DISPATCH */
INTEL_UEVENT_CONSTRAINT(0x05a3, 0xf), /* CYCLE_ACTIVITY.STALLS_L2_PENDING */
INTEL_UEVENT_CONSTRAINT(0x02a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */
INTEL_UEVENT_CONSTRAINT(0x06a3, 0x4), /* CYCLE_ACTIVITY.STALLS_L1D_PENDING */
INTEL_EVENT_CONSTRAINT(0x48, 0x4), /* L1D_PEND_MISS.PENDING */
INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */
INTEL_EVENT_CONSTRAINT(0xcd, 0x8), /* MEM_TRANS_RETIRED.LOAD_LATENCY */
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_ivb_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
INTEL_UEVENT_CONSTRAINT(0x0148, 0x4), /* L1D_PEND_MISS.PENDING */
INTEL_UEVENT_CONSTRAINT(0x0279, 0xf), /* IDQ.EMTPY */
INTEL_UEVENT_CONSTRAINT(0x019c, 0xf), /* IDQ_UOPS_NOT_DELIVERED.CORE */
INTEL_UEVENT_CONSTRAINT(0x04a3, 0xf), /* CYCLE_ACTIVITY.CYCLES_NO_EXECUTE */
INTEL_UEVENT_CONSTRAINT(0x05a3, 0xf), /* CYCLE_ACTIVITY.STALLS_L2_PENDING */
INTEL_UEVENT_CONSTRAINT(0x06a3, 0xf), /* CYCLE_ACTIVITY.STALLS_LDM_PENDING */
INTEL_UEVENT_CONSTRAINT(0x08a3, 0x4), /* CYCLE_ACTIVITY.CYCLES_L1D_PENDING */
INTEL_UEVENT_CONSTRAINT(0x0ca3, 0x4), /* CYCLE_ACTIVITY.STALLS_L1D_PENDING */
INTEL_UEVENT_CONSTRAINT(0x01c0, 0x2), /* INST_RETIRED.PREC_DIST */
INTEL_EVENT_CONSTRAINT(0xd0, 0xf), /* MEM_UOPS_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xd1, 0xf), /* MEM_LOAD_UOPS_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xd2, 0xf), /* MEM_LOAD_UOPS_LLC_HIT_RETIRED.* */
INTEL_EVENT_CONSTRAINT(0xd3, 0xf), /* MEM_LOAD_UOPS_LLC_MISS_RETIRED.* */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_westmere_extra_regs[] __read_mostly =
{
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0xffff, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0xffff, RSP_1),
EVENT_EXTRA_END
};
static struct event_constraint intel_v1_event_constraints[] __read_mostly =
{
EVENT_CONSTRAINT_END
};
static struct event_constraint intel_gen_event_constraints[] __read_mostly =
{
FIXED_EVENT_CONSTRAINT(0x00c0, 0), /* INST_RETIRED.ANY */
FIXED_EVENT_CONSTRAINT(0x003c, 1), /* CPU_CLK_UNHALTED.CORE */
FIXED_EVENT_CONSTRAINT(0x0300, 2), /* CPU_CLK_UNHALTED.REF */
EVENT_CONSTRAINT_END
};
static struct extra_reg intel_snb_extra_regs[] __read_mostly = {
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0x3f807f8fffull, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0x3f807f8fffull, RSP_1),
EVENT_EXTRA_END
};
static struct extra_reg intel_snbep_extra_regs[] __read_mostly = {
INTEL_EVENT_EXTRA_REG(0xb7, MSR_OFFCORE_RSP_0, 0x3fffff8fffull, RSP_0),
INTEL_EVENT_EXTRA_REG(0xbb, MSR_OFFCORE_RSP_1, 0x3fffff8fffull, RSP_1),
EVENT_EXTRA_END
};
static u64 intel_pmu_event_map(int hw_event)
{
return intel_perfmon_event_map[hw_event];
}
#define SNB_DMND_DATA_RD (1ULL << 0)
#define SNB_DMND_RFO (1ULL << 1)
#define SNB_DMND_IFETCH (1ULL << 2)
#define SNB_DMND_WB (1ULL << 3)
#define SNB_PF_DATA_RD (1ULL << 4)
#define SNB_PF_RFO (1ULL << 5)
#define SNB_PF_IFETCH (1ULL << 6)
#define SNB_LLC_DATA_RD (1ULL << 7)
#define SNB_LLC_RFO (1ULL << 8)
#define SNB_LLC_IFETCH (1ULL << 9)
#define SNB_BUS_LOCKS (1ULL << 10)
#define SNB_STRM_ST (1ULL << 11)
#define SNB_OTHER (1ULL << 15)
#define SNB_RESP_ANY (1ULL << 16)
#define SNB_NO_SUPP (1ULL << 17)
#define SNB_LLC_HITM (1ULL << 18)
#define SNB_LLC_HITE (1ULL << 19)
#define SNB_LLC_HITS (1ULL << 20)
#define SNB_LLC_HITF (1ULL << 21)
#define SNB_LOCAL (1ULL << 22)
#define SNB_REMOTE (0xffULL << 23)
#define SNB_SNP_NONE (1ULL << 31)
#define SNB_SNP_NOT_NEEDED (1ULL << 32)
#define SNB_SNP_MISS (1ULL << 33)
#define SNB_NO_FWD (1ULL << 34)
#define SNB_SNP_FWD (1ULL << 35)
#define SNB_HITM (1ULL << 36)
#define SNB_NON_DRAM (1ULL << 37)
#define SNB_DMND_READ (SNB_DMND_DATA_RD|SNB_LLC_DATA_RD)
#define SNB_DMND_WRITE (SNB_DMND_RFO|SNB_LLC_RFO)
#define SNB_DMND_PREFETCH (SNB_PF_DATA_RD|SNB_PF_RFO)
#define SNB_SNP_ANY (SNB_SNP_NONE|SNB_SNP_NOT_NEEDED| \
SNB_SNP_MISS|SNB_NO_FWD|SNB_SNP_FWD| \
SNB_HITM)
#define SNB_DRAM_ANY (SNB_LOCAL|SNB_REMOTE|SNB_SNP_ANY)
#define SNB_DRAM_REMOTE (SNB_REMOTE|SNB_SNP_ANY)
#define SNB_L3_ACCESS SNB_RESP_ANY
#define SNB_L3_MISS (SNB_DRAM_ANY|SNB_NON_DRAM)
static __initconst const u64 snb_hw_cache_extra_regs
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_READ|SNB_L3_ACCESS,
[ C(RESULT_MISS) ] = SNB_DMND_READ|SNB_L3_MISS,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_WRITE|SNB_L3_ACCESS,
[ C(RESULT_MISS) ] = SNB_DMND_WRITE|SNB_L3_MISS,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_PREFETCH|SNB_L3_ACCESS,
[ C(RESULT_MISS) ] = SNB_DMND_PREFETCH|SNB_L3_MISS,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_READ|SNB_DRAM_ANY,
[ C(RESULT_MISS) ] = SNB_DMND_READ|SNB_DRAM_REMOTE,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_WRITE|SNB_DRAM_ANY,
[ C(RESULT_MISS) ] = SNB_DMND_WRITE|SNB_DRAM_REMOTE,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = SNB_DMND_PREFETCH|SNB_DRAM_ANY,
[ C(RESULT_MISS) ] = SNB_DMND_PREFETCH|SNB_DRAM_REMOTE,
},
},
};
static __initconst const u64 snb_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0xf1d0, /* MEM_UOP_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPLACEMENT */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0xf2d0, /* MEM_UOP_RETIRED.STORES */
[ C(RESULT_MISS) ] = 0x0851, /* L1D.ALL_M_REPLACEMENT */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x024e, /* HW_PRE_REQ.DL1_MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0280, /* ICACHE.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x81d0, /* MEM_UOP_RETIRED.ALL_LOADS */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.CAUSES_A_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x82d0, /* MEM_UOP_RETIRED.ALL_STORES */
[ C(RESULT_MISS) ] = 0x0149, /* DTLB_STORE_MISSES.MISS_CAUSES_A_WALK */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x1085, /* ITLB_MISSES.STLB_HIT */
[ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.CAUSES_A_WALK */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x00c5, /* BR_MISP_RETIRED.ALL_BRANCHES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
static __initconst const u64 westmere_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
/*
* Use RFO, not WRITEBACK, because a write miss would typically occur
* on RFO.
*/
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x0185, /* ITLB_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
/*
* Nehalem/Westmere MSR_OFFCORE_RESPONSE bits;
* See IA32 SDM Vol 3B 30.6.1.3
*/
#define NHM_DMND_DATA_RD (1 << 0)
#define NHM_DMND_RFO (1 << 1)
#define NHM_DMND_IFETCH (1 << 2)
#define NHM_DMND_WB (1 << 3)
#define NHM_PF_DATA_RD (1 << 4)
#define NHM_PF_DATA_RFO (1 << 5)
#define NHM_PF_IFETCH (1 << 6)
#define NHM_OFFCORE_OTHER (1 << 7)
#define NHM_UNCORE_HIT (1 << 8)
#define NHM_OTHER_CORE_HIT_SNP (1 << 9)
#define NHM_OTHER_CORE_HITM (1 << 10)
/* reserved */
#define NHM_REMOTE_CACHE_FWD (1 << 12)
#define NHM_REMOTE_DRAM (1 << 13)
#define NHM_LOCAL_DRAM (1 << 14)
#define NHM_NON_DRAM (1 << 15)
#define NHM_LOCAL (NHM_LOCAL_DRAM|NHM_REMOTE_CACHE_FWD)
#define NHM_REMOTE (NHM_REMOTE_DRAM)
#define NHM_DMND_READ (NHM_DMND_DATA_RD)
#define NHM_DMND_WRITE (NHM_DMND_RFO|NHM_DMND_WB)
#define NHM_DMND_PREFETCH (NHM_PF_DATA_RD|NHM_PF_DATA_RFO)
#define NHM_L3_HIT (NHM_UNCORE_HIT|NHM_OTHER_CORE_HIT_SNP|NHM_OTHER_CORE_HITM)
#define NHM_L3_MISS (NHM_NON_DRAM|NHM_LOCAL_DRAM|NHM_REMOTE_DRAM|NHM_REMOTE_CACHE_FWD)
#define NHM_L3_ACCESS (NHM_L3_HIT|NHM_L3_MISS)
static __initconst const u64 nehalem_hw_cache_extra_regs
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_L3_MISS,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_L3_MISS,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_L3_ACCESS,
[ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_L3_MISS,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_READ|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_READ|NHM_REMOTE,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_WRITE|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_WRITE|NHM_REMOTE,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = NHM_DMND_PREFETCH|NHM_LOCAL|NHM_REMOTE,
[ C(RESULT_MISS) ] = NHM_DMND_PREFETCH|NHM_REMOTE,
},
},
};
static __initconst const u64 nehalem_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x010b, /* MEM_INST_RETIRED.LOADS */
[ C(RESULT_MISS) ] = 0x0151, /* L1D.REPL */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x020b, /* MEM_INST_RETURED.STORES */
[ C(RESULT_MISS) ] = 0x0251, /* L1D.M_REPL */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0x024e, /* L1D_PREFETCH.MISS */
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
/* OFFCORE_RESPONSE.ANY_DATA.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_DATA.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
/*
* Use RFO, not WRITEBACK, because a write miss would typically occur
* on RFO.
*/
[ C(OP_WRITE) ] = {
/* OFFCORE_RESPONSE.ANY_RFO.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.ANY_RFO.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
/* OFFCORE_RESPONSE.PREFETCH.LOCAL_CACHE */
[ C(RESULT_ACCESS) ] = 0x01b7,
/* OFFCORE_RESPONSE.PREFETCH.ANY_LLC_MISS */
[ C(RESULT_MISS) ] = 0x01b7,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0108, /* DTLB_LOAD_MISSES.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0x0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x20c8, /* ITLB_MISS_RETIRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
[ C(RESULT_MISS) ] = 0x03e8, /* BPU_CLEARS.ANY */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(NODE) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x01b7,
[ C(RESULT_MISS) ] = 0x01b7,
},
},
};
static __initconst const u64 core2_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI */
[ C(RESULT_MISS) ] = 0x0140, /* L1D_CACHE_LD.I_STATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI */
[ C(RESULT_MISS) ] = 0x0141, /* L1D_CACHE_ST.I_STATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x104e, /* L1D_PREFETCH.REQUESTS */
[ C(RESULT_MISS) ] = 0,
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0080, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0081, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */
[ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */
[ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0208, /* DTLB_MISSES.MISS_LD */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0808, /* DTLB_MISSES.MISS_ST */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x1282, /* ITLBMISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */
[ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static __initconst const u64 atom_hw_cache_event_ids
[PERF_COUNT_HW_CACHE_MAX]
[PERF_COUNT_HW_CACHE_OP_MAX]
[PERF_COUNT_HW_CACHE_RESULT_MAX] =
{
[ C(L1D) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE.LD */
[ C(RESULT_MISS) ] = 0,
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE.ST */
[ C(RESULT_MISS) ] = 0,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0x0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(L1I ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS */
[ C(RESULT_MISS) ] = 0x0280, /* L1I.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(LL ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI */
[ C(RESULT_MISS) ] = 0x4129, /* L2_LD.ISTATE */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI */
[ C(RESULT_MISS) ] = 0x412A, /* L2_ST.ISTATE */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(DTLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE_LD.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0508, /* DTLB_MISSES.MISS_LD */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE_ST.MESI (alias) */
[ C(RESULT_MISS) ] = 0x0608, /* DTLB_MISSES.MISS_ST */
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = 0,
[ C(RESULT_MISS) ] = 0,
},
},
[ C(ITLB) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P */
[ C(RESULT_MISS) ] = 0x0282, /* ITLB.MISSES */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
[ C(BPU ) ] = {
[ C(OP_READ) ] = {
[ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY */
[ C(RESULT_MISS) ] = 0x00c5, /* BP_INST_RETIRED.MISPRED */
},
[ C(OP_WRITE) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
[ C(OP_PREFETCH) ] = {
[ C(RESULT_ACCESS) ] = -1,
[ C(RESULT_MISS) ] = -1,
},
},
};
static inline bool intel_pmu_needs_lbr_smpl(struct perf_event *event)
{
/* user explicitly requested branch sampling */
if (has_branch_stack(event))
return true;
/* implicit branch sampling to correct PEBS skid */
if (x86_pmu.intel_cap.pebs_trap && event->attr.precise_ip > 1)
return true;
return false;
}
static void intel_pmu_disable_all(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0);
if (test_bit(INTEL_PMC_IDX_FIXED_BTS, cpuc->active_mask))
intel_pmu_disable_bts();
intel_pmu_pebs_disable_all();
intel_pmu_lbr_disable_all();
}
static void intel_pmu_enable_all(int added)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
intel_pmu_pebs_enable_all();
intel_pmu_lbr_enable_all();
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL,
x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_guest_mask);
if (test_bit(INTEL_PMC_IDX_FIXED_BTS, cpuc->active_mask)) {
struct perf_event *event =
cpuc->events[INTEL_PMC_IDX_FIXED_BTS];
if (WARN_ON_ONCE(!event))
return;
intel_pmu_enable_bts(event->hw.config);
}
}
/*
* Workaround for:
* Intel Errata AAK100 (model 26)
* Intel Errata AAP53 (model 30)
* Intel Errata BD53 (model 44)
*
* The official story:
* These chips need to be 'reset' when adding counters by programming the
* magic three (non-counting) events 0x4300B5, 0x4300D2, and 0x4300B1 either
* in sequence on the same PMC or on different PMCs.
*
* In practise it appears some of these events do in fact count, and
* we need to programm all 4 events.
*/
static void intel_pmu_nhm_workaround(void)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
static const unsigned long nhm_magic[4] = {
0x4300B5,
0x4300D2,
0x4300B1,
0x4300B1
};
struct perf_event *event;
int i;
/*
* The Errata requires below steps:
* 1) Clear MSR_IA32_PEBS_ENABLE and MSR_CORE_PERF_GLOBAL_CTRL;
* 2) Configure 4 PERFEVTSELx with the magic events and clear
* the corresponding PMCx;
* 3) set bit0~bit3 of MSR_CORE_PERF_GLOBAL_CTRL;
* 4) Clear MSR_CORE_PERF_GLOBAL_CTRL;
* 5) Clear 4 pairs of ERFEVTSELx and PMCx;
*/
/*
* The real steps we choose are a little different from above.
* A) To reduce MSR operations, we don't run step 1) as they
* are already cleared before this function is called;
* B) Call x86_perf_event_update to save PMCx before configuring
* PERFEVTSELx with magic number;
* C) With step 5), we do clear only when the PERFEVTSELx is
* not used currently.
* D) Call x86_perf_event_set_period to restore PMCx;
*/
/* We always operate 4 pairs of PERF Counters */
for (i = 0; i < 4; i++) {
event = cpuc->events[i];
if (event)
x86_perf_event_update(event);
}
for (i = 0; i < 4; i++) {
wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, nhm_magic[i]);
wrmsrl(MSR_ARCH_PERFMON_PERFCTR0 + i, 0x0);
}
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0xf);
wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0x0);
for (i = 0; i < 4; i++) {
event = cpuc->events[i];
if (event) {
x86_perf_event_set_period(event);
__x86_pmu_enable_event(&event->hw,
ARCH_PERFMON_EVENTSEL_ENABLE);
} else
wrmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + i, 0x0);
}
}
static void intel_pmu_nhm_enable_all(int added)
{
if (added)
intel_pmu_nhm_workaround();
intel_pmu_enable_all(added);
}
static inline u64 intel_pmu_get_status(void)
{
u64 status;
rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
return status;
}
static inline void intel_pmu_ack_status(u64 ack)
{
wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack);
}
static void intel_pmu_disable_fixed(struct hw_perf_event *hwc)
{
int idx = hwc->idx - INTEL_PMC_IDX_FIXED;
u64 ctrl_val, mask;
mask = 0xfULL << (idx * 4);
rdmsrl(hwc->config_base, ctrl_val);
ctrl_val &= ~mask;
wrmsrl(hwc->config_base, ctrl_val);
}
static void intel_pmu_disable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (unlikely(hwc->idx == INTEL_PMC_IDX_FIXED_BTS)) {
intel_pmu_disable_bts();
intel_pmu_drain_bts_buffer();
return;
}
cpuc->intel_ctrl_guest_mask &= ~(1ull << hwc->idx);
cpuc->intel_ctrl_host_mask &= ~(1ull << hwc->idx);
/*
* must disable before any actual event
* because any event may be combined with LBR
*/
if (intel_pmu_needs_lbr_smpl(event))
intel_pmu_lbr_disable(event);
if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
intel_pmu_disable_fixed(hwc);
return;
}
x86_pmu_disable_event(event);
if (unlikely(event->attr.precise_ip))
intel_pmu_pebs_disable(event);
}
static void intel_pmu_enable_fixed(struct hw_perf_event *hwc)
{
int idx = hwc->idx - INTEL_PMC_IDX_FIXED;
u64 ctrl_val, bits, mask;
/*
* Enable IRQ generation (0x8),
* and enable ring-3 counting (0x2) and ring-0 counting (0x1)
* if requested:
*/
bits = 0x8ULL;
if (hwc->config & ARCH_PERFMON_EVENTSEL_USR)
bits |= 0x2;
if (hwc->config & ARCH_PERFMON_EVENTSEL_OS)
bits |= 0x1;
/*
* ANY bit is supported in v3 and up
*/
if (x86_pmu.version > 2 && hwc->config & ARCH_PERFMON_EVENTSEL_ANY)
bits |= 0x4;
bits <<= (idx * 4);
mask = 0xfULL << (idx * 4);
rdmsrl(hwc->config_base, ctrl_val);
ctrl_val &= ~mask;
ctrl_val |= bits;
wrmsrl(hwc->config_base, ctrl_val);
}
static void intel_pmu_enable_event(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
if (unlikely(hwc->idx == INTEL_PMC_IDX_FIXED_BTS)) {
if (!__this_cpu_read(cpu_hw_events.enabled))
return;
intel_pmu_enable_bts(hwc->config);
return;
}
/*
* must enabled before any actual event
* because any event may be combined with LBR
*/
if (intel_pmu_needs_lbr_smpl(event))
intel_pmu_lbr_enable(event);
if (event->attr.exclude_host)
cpuc->intel_ctrl_guest_mask |= (1ull << hwc->idx);
if (event->attr.exclude_guest)
cpuc->intel_ctrl_host_mask |= (1ull << hwc->idx);
if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
intel_pmu_enable_fixed(hwc);
return;
}
if (unlikely(event->attr.precise_ip))
intel_pmu_pebs_enable(event);
__x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
}
/*
* Save and restart an expired event. Called by NMI contexts,
* so it has to be careful about preempting normal event ops:
*/
int intel_pmu_save_and_restart(struct perf_event *event)
{
x86_perf_event_update(event);
return x86_perf_event_set_period(event);
}
static void intel_pmu_reset(void)
{
struct debug_store *ds = __this_cpu_read(cpu_hw_events.ds);
unsigned long flags;
int idx;
if (!x86_pmu.num_counters)
return;
local_irq_save(flags);
pr_info("clearing PMU state on CPU#%d\n", smp_processor_id());
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
wrmsrl_safe(x86_pmu_config_addr(idx), 0ull);
wrmsrl_safe(x86_pmu_event_addr(idx), 0ull);
}
for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++)
wrmsrl_safe(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, 0ull);
if (ds)
ds->bts_index = ds->bts_buffer_base;
local_irq_restore(flags);
}
/*
* This handler is triggered by the local APIC, so the APIC IRQ handling
* rules apply:
*/
static int intel_pmu_handle_irq(struct pt_regs *regs)
{
struct perf_sample_data data;
struct cpu_hw_events *cpuc;
int bit, loops;
u64 status;
int handled;
cpuc = &__get_cpu_var(cpu_hw_events);
/*
* Some chipsets need to unmask the LVTPC in a particular spot
* inside the nmi handler. As a result, the unmasking was pushed
* into all the nmi handlers.
*
* This handler doesn't seem to have any issues with the unmasking
* so it was left at the top.
*/
apic_write(APIC_LVTPC, APIC_DM_NMI);
intel_pmu_disable_all();
handled = intel_pmu_drain_bts_buffer();
status = intel_pmu_get_status();
if (!status) {
intel_pmu_enable_all(0);
return handled;
}
loops = 0;
again:
intel_pmu_ack_status(status);
if (++loops > 100) {
WARN_ONCE(1, "perfevents: irq loop stuck!\n");
perf_event_print_debug();
intel_pmu_reset();
goto done;
}
inc_irq_stat(apic_perf_irqs);
intel_pmu_lbr_read();
/*
* PEBS overflow sets bit 62 in the global status register
*/
if (__test_and_clear_bit(62, (unsigned long *)&status)) {
handled++;
x86_pmu.drain_pebs(regs);
}
for_each_set_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
struct perf_event *event = cpuc->events[bit];
handled++;
if (!test_bit(bit, cpuc->active_mask))
continue;
if (!intel_pmu_save_and_restart(event))
continue;
perf_sample_data_init(&data, 0, event->hw.last_period);
if (has_branch_stack(event))
data.br_stack = &cpuc->lbr_stack;
if (perf_event_overflow(event, &data, regs))
x86_pmu_stop(event, 0);
}
/*
* Repeat if there is more work to be done:
*/
status = intel_pmu_get_status();
if (status)
goto again;
done:
intel_pmu_enable_all(0);
return handled;
}
static struct event_constraint *
intel_bts_constraints(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
unsigned int hw_event, bts_event;
if (event->attr.freq)
return NULL;
hw_event = hwc->config & INTEL_ARCH_EVENT_MASK;
bts_event = x86_pmu.event_map(PERF_COUNT_HW_BRANCH_INSTRUCTIONS);
if (unlikely(hw_event == bts_event && hwc->sample_period == 1))
return &bts_constraint;
return NULL;
}
static int intel_alt_er(int idx)
{
if (!(x86_pmu.er_flags & ERF_HAS_RSP_1))
return idx;
if (idx == EXTRA_REG_RSP_0)
return EXTRA_REG_RSP_1;
if (idx == EXTRA_REG_RSP_1)
return EXTRA_REG_RSP_0;
return idx;
}
static void intel_fixup_er(struct perf_event *event, int idx)
{
event->hw.extra_reg.idx = idx;
if (idx == EXTRA_REG_RSP_0) {
event->hw.config &= ~INTEL_ARCH_EVENT_MASK;
event->hw.config |= 0x01b7;
event->hw.extra_reg.reg = MSR_OFFCORE_RSP_0;
} else if (idx == EXTRA_REG_RSP_1) {
event->hw.config &= ~INTEL_ARCH_EVENT_MASK;
event->hw.config |= 0x01bb;
event->hw.extra_reg.reg = MSR_OFFCORE_RSP_1;
}
}
/*
* manage allocation of shared extra msr for certain events
*
* sharing can be:
* per-cpu: to be shared between the various events on a single PMU
* per-core: per-cpu + shared by HT threads
*/
static struct event_constraint *
__intel_shared_reg_get_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event,
struct hw_perf_event_extra *reg)
{
struct event_constraint *c = &emptyconstraint;
struct er_account *era;
unsigned long flags;
int idx = reg->idx;
/*
* reg->alloc can be set due to existing state, so for fake cpuc we
* need to ignore this, otherwise we might fail to allocate proper fake
* state for this extra reg constraint. Also see the comment below.
*/
if (reg->alloc && !cpuc->is_fake)
return NULL; /* call x86_get_event_constraint() */
again:
era = &cpuc->shared_regs->regs[idx];
/*
* we use spin_lock_irqsave() to avoid lockdep issues when
* passing a fake cpuc
*/
raw_spin_lock_irqsave(&era->lock, flags);
if (!atomic_read(&era->ref) || era->config == reg->config) {
/*
* If its a fake cpuc -- as per validate_{group,event}() we
* shouldn't touch event state and we can avoid doing so
* since both will only call get_event_constraints() once
* on each event, this avoids the need for reg->alloc.
*
* Not doing the ER fixup will only result in era->reg being
* wrong, but since we won't actually try and program hardware
* this isn't a problem either.
*/
if (!cpuc->is_fake) {
if (idx != reg->idx)
intel_fixup_er(event, idx);
/*
* x86_schedule_events() can call get_event_constraints()
* multiple times on events in the case of incremental
* scheduling(). reg->alloc ensures we only do the ER
* allocation once.
*/
reg->alloc = 1;
}
/* lock in msr value */
era->config = reg->config;
era->reg = reg->reg;
/* one more user */
atomic_inc(&era->ref);
/*
* need to call x86_get_event_constraint()
* to check if associated event has constraints
*/
c = NULL;
} else {
idx = intel_alt_er(idx);
if (idx != reg->idx) {
raw_spin_unlock_irqrestore(&era->lock, flags);
goto again;
}
}
raw_spin_unlock_irqrestore(&era->lock, flags);
return c;
}
static void
__intel_shared_reg_put_constraints(struct cpu_hw_events *cpuc,
struct hw_perf_event_extra *reg)
{
struct er_account *era;
/*
* Only put constraint if extra reg was actually allocated. Also takes
* care of event which do not use an extra shared reg.
*
* Also, if this is a fake cpuc we shouldn't touch any event state
* (reg->alloc) and we don't care about leaving inconsistent cpuc state
* either since it'll be thrown out.
*/
if (!reg->alloc || cpuc->is_fake)
return;
era = &cpuc->shared_regs->regs[reg->idx];
/* one fewer user */
atomic_dec(&era->ref);
/* allocate again next time */
reg->alloc = 0;
}
static struct event_constraint *
intel_shared_regs_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
struct event_constraint *c = NULL, *d;
struct hw_perf_event_extra *xreg, *breg;
xreg = &event->hw.extra_reg;
if (xreg->idx != EXTRA_REG_NONE) {
c = __intel_shared_reg_get_constraints(cpuc, event, xreg);
if (c == &emptyconstraint)
return c;
}
breg = &event->hw.branch_reg;
if (breg->idx != EXTRA_REG_NONE) {
d = __intel_shared_reg_get_constraints(cpuc, event, breg);
if (d == &emptyconstraint) {
__intel_shared_reg_put_constraints(cpuc, xreg);
c = d;
}
}
return c;
}
struct event_constraint *
x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
{
struct event_constraint *c;
if (x86_pmu.event_constraints) {
for_each_event_constraint(c, x86_pmu.event_constraints) {
if ((event->hw.config & c->cmask) == c->code)
return c;
}
}
return &unconstrained;
}
static struct event_constraint *
intel_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
{
struct event_constraint *c;
c = intel_bts_constraints(event);
if (c)
return c;
c = intel_pebs_constraints(event);
if (c)
return c;
c = intel_shared_regs_constraints(cpuc, event);
if (c)
return c;
return x86_get_event_constraints(cpuc, event);
}
static void
intel_put_shared_regs_event_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
struct hw_perf_event_extra *reg;
reg = &event->hw.extra_reg;
if (reg->idx != EXTRA_REG_NONE)
__intel_shared_reg_put_constraints(cpuc, reg);
reg = &event->hw.branch_reg;
if (reg->idx != EXTRA_REG_NONE)
__intel_shared_reg_put_constraints(cpuc, reg);
}
static void intel_put_event_constraints(struct cpu_hw_events *cpuc,
struct perf_event *event)
{
intel_put_shared_regs_event_constraints(cpuc, event);
}
static void intel_pebs_aliases_core2(struct perf_event *event)
{
if ((event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) {
/*
* Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P
* (0x003c) so that we can use it with PEBS.
*
* The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't
* PEBS capable. However we can use INST_RETIRED.ANY_P
* (0x00c0), which is a PEBS capable event, to get the same
* count.
*
* INST_RETIRED.ANY_P counts the number of cycles that retires
* CNTMASK instructions. By setting CNTMASK to a value (16)
* larger than the maximum number of instructions that can be
* retired per cycle (4) and then inverting the condition, we
* count all cycles that retire 16 or less instructions, which
* is every cycle.
*
* Thereby we gain a PEBS capable cycle counter.
*/
u64 alt_config = X86_CONFIG(.event=0xc0, .inv=1, .cmask=16);
alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK);
event->hw.config = alt_config;
}
}
static void intel_pebs_aliases_snb(struct perf_event *event)
{
if ((event->hw.config & X86_RAW_EVENT_MASK) == 0x003c) {
/*
* Use an alternative encoding for CPU_CLK_UNHALTED.THREAD_P
* (0x003c) so that we can use it with PEBS.
*
* The regular CPU_CLK_UNHALTED.THREAD_P event (0x003c) isn't
* PEBS capable. However we can use UOPS_RETIRED.ALL
* (0x01c2), which is a PEBS capable event, to get the same
* count.
*
* UOPS_RETIRED.ALL counts the number of cycles that retires
* CNTMASK micro-ops. By setting CNTMASK to a value (16)
* larger than the maximum number of micro-ops that can be
* retired per cycle (4) and then inverting the condition, we
* count all cycles that retire 16 or less micro-ops, which
* is every cycle.
*
* Thereby we gain a PEBS capable cycle counter.
*/
u64 alt_config = X86_CONFIG(.event=0xc2, .umask=0x01, .inv=1, .cmask=16);
alt_config |= (event->hw.config & ~X86_RAW_EVENT_MASK);
event->hw.config = alt_config;
}
}
static int intel_pmu_hw_config(struct perf_event *event)
{
int ret = x86_pmu_hw_config(event);
if (ret)
return ret;
if (event->attr.precise_ip && x86_pmu.pebs_aliases)
x86_pmu.pebs_aliases(event);
if (intel_pmu_needs_lbr_smpl(event)) {
ret = intel_pmu_setup_lbr_filter(event);
if (ret)
return ret;
}
if (event->attr.type != PERF_TYPE_RAW)
return 0;
if (!(event->attr.config & ARCH_PERFMON_EVENTSEL_ANY))
return 0;
if (x86_pmu.version < 3)
return -EINVAL;
if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
return -EACCES;
event->hw.config |= ARCH_PERFMON_EVENTSEL_ANY;
return 0;
}
struct perf_guest_switch_msr *perf_guest_get_msrs(int *nr)
{
if (x86_pmu.guest_get_msrs)
return x86_pmu.guest_get_msrs(nr);
*nr = 0;
return NULL;
}
EXPORT_SYMBOL_GPL(perf_guest_get_msrs);
static struct perf_guest_switch_msr *intel_guest_get_msrs(int *nr)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs;
arr[0].msr = MSR_CORE_PERF_GLOBAL_CTRL;
arr[0].host = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_guest_mask;
arr[0].guest = x86_pmu.intel_ctrl & ~cpuc->intel_ctrl_host_mask;
/*
* If PMU counter has PEBS enabled it is not enough to disable counter
* on a guest entry since PEBS memory write can overshoot guest entry
* and corrupt guest memory. Disabling PEBS solves the problem.
*/
arr[1].msr = MSR_IA32_PEBS_ENABLE;
arr[1].host = cpuc->pebs_enabled;
arr[1].guest = 0;
*nr = 2;
return arr;
}
static struct perf_guest_switch_msr *core_guest_get_msrs(int *nr)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct perf_guest_switch_msr *arr = cpuc->guest_switch_msrs;
int idx;
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
struct perf_event *event = cpuc->events[idx];
arr[idx].msr = x86_pmu_config_addr(idx);
arr[idx].host = arr[idx].guest = 0;
if (!test_bit(idx, cpuc->active_mask))
continue;
arr[idx].host = arr[idx].guest =
event->hw.config | ARCH_PERFMON_EVENTSEL_ENABLE;
if (event->attr.exclude_host)
arr[idx].host &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
else if (event->attr.exclude_guest)
arr[idx].guest &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
}
*nr = x86_pmu.num_counters;
return arr;
}
static void core_pmu_enable_event(struct perf_event *event)
{
if (!event->attr.exclude_host)
x86_pmu_enable_event(event);
}
static void core_pmu_enable_all(int added)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
int idx;
for (idx = 0; idx < x86_pmu.num_counters; idx++) {
struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
if (!test_bit(idx, cpuc->active_mask) ||
cpuc->events[idx]->attr.exclude_host)
continue;
__x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
}
}
PMU_FORMAT_ATTR(event, "config:0-7" );
PMU_FORMAT_ATTR(umask, "config:8-15" );
PMU_FORMAT_ATTR(edge, "config:18" );
PMU_FORMAT_ATTR(pc, "config:19" );
PMU_FORMAT_ATTR(any, "config:21" ); /* v3 + */
PMU_FORMAT_ATTR(inv, "config:23" );
PMU_FORMAT_ATTR(cmask, "config:24-31" );
static struct attribute *intel_arch_formats_attr[] = {
&format_attr_event.attr,
&format_attr_umask.attr,
&format_attr_edge.attr,
&format_attr_pc.attr,
&format_attr_inv.attr,
&format_attr_cmask.attr,
NULL,
};
ssize_t intel_event_sysfs_show(char *page, u64 config)
{
u64 event = (config & ARCH_PERFMON_EVENTSEL_EVENT);
return x86_event_sysfs_show(page, config, event);
}
static __initconst const struct x86_pmu core_pmu = {
.name = "core",
.handle_irq = x86_pmu_handle_irq,
.disable_all = x86_pmu_disable_all,
.enable_all = core_pmu_enable_all,
.enable = core_pmu_enable_event,
.disable = x86_pmu_disable_event,
.hw_config = x86_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_ARCH_PERFMON_EVENTSEL0,
.perfctr = MSR_ARCH_PERFMON_PERFCTR0,
.event_map = intel_pmu_event_map,
.max_events = ARRAY_SIZE(intel_perfmon_event_map),
.apic = 1,
/*
* Intel PMCs cannot be accessed sanely above 32 bit width,
* so we install an artificial 1<<31 period regardless of
* the generic event period:
*/
.max_period = (1ULL << 31) - 1,
.get_event_constraints = intel_get_event_constraints,
.put_event_constraints = intel_put_event_constraints,
.event_constraints = intel_core_event_constraints,
.guest_get_msrs = core_guest_get_msrs,
.format_attrs = intel_arch_formats_attr,
.events_sysfs_show = intel_event_sysfs_show,
};
struct intel_shared_regs *allocate_shared_regs(int cpu)
{
struct intel_shared_regs *regs;
int i;
regs = kzalloc_node(sizeof(struct intel_shared_regs),
GFP_KERNEL, cpu_to_node(cpu));
if (regs) {
/*
* initialize the locks to keep lockdep happy
*/
for (i = 0; i < EXTRA_REG_MAX; i++)
raw_spin_lock_init(®s->regs[i].lock);
regs->core_id = -1;
}
return regs;
}
static int intel_pmu_cpu_prepare(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
if (!(x86_pmu.extra_regs || x86_pmu.lbr_sel_map))
return NOTIFY_OK;
cpuc->shared_regs = allocate_shared_regs(cpu);
if (!cpuc->shared_regs)
return NOTIFY_BAD;
return NOTIFY_OK;
}
static void intel_pmu_cpu_starting(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
int core_id = topology_core_id(cpu);
int i;
init_debug_store_on_cpu(cpu);
/*
* Deal with CPUs that don't clear their LBRs on power-up.
*/
intel_pmu_lbr_reset();
cpuc->lbr_sel = NULL;
if (!cpuc->shared_regs)
return;
if (!(x86_pmu.er_flags & ERF_NO_HT_SHARING)) {
for_each_cpu(i, topology_thread_cpumask(cpu)) {
struct intel_shared_regs *pc;
pc = per_cpu(cpu_hw_events, i).shared_regs;
if (pc && pc->core_id == core_id) {
cpuc->kfree_on_online = cpuc->shared_regs;
cpuc->shared_regs = pc;
break;
}
}
cpuc->shared_regs->core_id = core_id;
cpuc->shared_regs->refcnt++;
}
if (x86_pmu.lbr_sel_map)
cpuc->lbr_sel = &cpuc->shared_regs->regs[EXTRA_REG_LBR];
}
static void intel_pmu_cpu_dying(int cpu)
{
struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
struct intel_shared_regs *pc;
pc = cpuc->shared_regs;
if (pc) {
if (pc->core_id == -1 || --pc->refcnt == 0)
kfree(pc);
cpuc->shared_regs = NULL;
}
fini_debug_store_on_cpu(cpu);
}
static void intel_pmu_flush_branch_stack(void)
{
/*
* Intel LBR does not tag entries with the
* PID of the current task, then we need to
* flush it on ctxsw
* For now, we simply reset it
*/
if (x86_pmu.lbr_nr)
intel_pmu_lbr_reset();
}
PMU_FORMAT_ATTR(offcore_rsp, "config1:0-63");
static struct attribute *intel_arch3_formats_attr[] = {
&format_attr_event.attr,
&format_attr_umask.attr,
&format_attr_edge.attr,
&format_attr_pc.attr,
&format_attr_any.attr,
&format_attr_inv.attr,
&format_attr_cmask.attr,
&format_attr_offcore_rsp.attr, /* XXX do NHM/WSM + SNB breakout */
NULL,
};
static __initconst const struct x86_pmu intel_pmu = {
.name = "Intel",
.handle_irq = intel_pmu_handle_irq,
.disable_all = intel_pmu_disable_all,
.enable_all = intel_pmu_enable_all,
.enable = intel_pmu_enable_event,
.disable = intel_pmu_disable_event,
.hw_config = intel_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_ARCH_PERFMON_EVENTSEL0,
.perfctr = MSR_ARCH_PERFMON_PERFCTR0,
.event_map = intel_pmu_event_map,
.max_events = ARRAY_SIZE(intel_perfmon_event_map),
.apic = 1,
/*
* Intel PMCs cannot be accessed sanely above 32 bit width,
* so we install an artificial 1<<31 period regardless of
* the generic event period:
*/
.max_period = (1ULL << 31) - 1,
.get_event_constraints = intel_get_event_constraints,
.put_event_constraints = intel_put_event_constraints,
.pebs_aliases = intel_pebs_aliases_core2,
.format_attrs = intel_arch3_formats_attr,
.events_sysfs_show = intel_event_sysfs_show,
.cpu_prepare = intel_pmu_cpu_prepare,
.cpu_starting = intel_pmu_cpu_starting,
.cpu_dying = intel_pmu_cpu_dying,
.guest_get_msrs = intel_guest_get_msrs,
.flush_branch_stack = intel_pmu_flush_branch_stack,
};
static __init void intel_clovertown_quirk(void)
{
/*
* PEBS is unreliable due to:
*
* AJ67 - PEBS may experience CPL leaks
* AJ68 - PEBS PMI may be delayed by one event
* AJ69 - GLOBAL_STATUS[62] will only be set when DEBUGCTL[12]
* AJ106 - FREEZE_LBRS_ON_PMI doesn't work in combination with PEBS
*
* AJ67 could be worked around by restricting the OS/USR flags.
* AJ69 could be worked around by setting PMU_FREEZE_ON_PMI.
*
* AJ106 could possibly be worked around by not allowing LBR
* usage from PEBS, including the fixup.
* AJ68 could possibly be worked around by always programming
* a pebs_event_reset[0] value and coping with the lost events.
*
* But taken together it might just make sense to not enable PEBS on
* these chips.
*/
pr_warn("PEBS disabled due to CPU errata\n");
x86_pmu.pebs = 0;
x86_pmu.pebs_constraints = NULL;
}
static int intel_snb_pebs_broken(int cpu)
{
u32 rev = UINT_MAX; /* default to broken for unknown models */
switch (cpu_data(cpu).x86_model) {
case 42: /* SNB */
rev = 0x28;
break;
case 45: /* SNB-EP */
switch (cpu_data(cpu).x86_mask) {
case 6: rev = 0x618; break;
case 7: rev = 0x70c; break;
}
}
return (cpu_data(cpu).microcode < rev);
}
static void intel_snb_check_microcode(void)
{
int pebs_broken = 0;
int cpu;
get_online_cpus();
for_each_online_cpu(cpu) {
if ((pebs_broken = intel_snb_pebs_broken(cpu)))
break;
}
put_online_cpus();
if (pebs_broken == x86_pmu.pebs_broken)
return;
/*
* Serialized by the microcode lock..
*/
if (x86_pmu.pebs_broken) {
pr_info("PEBS enabled due to microcode update\n");
x86_pmu.pebs_broken = 0;
} else {
pr_info("PEBS disabled due to CPU errata, please upgrade microcode\n");
x86_pmu.pebs_broken = 1;
}
}
static __init void intel_sandybridge_quirk(void)
{
x86_pmu.check_microcode = intel_snb_check_microcode;
intel_snb_check_microcode();
}
static const struct { int id; char *name; } intel_arch_events_map[] __initconst = {
{ PERF_COUNT_HW_CPU_CYCLES, "cpu cycles" },
{ PERF_COUNT_HW_INSTRUCTIONS, "instructions" },
{ PERF_COUNT_HW_BUS_CYCLES, "bus cycles" },
{ PERF_COUNT_HW_CACHE_REFERENCES, "cache references" },
{ PERF_COUNT_HW_CACHE_MISSES, "cache misses" },
{ PERF_COUNT_HW_BRANCH_INSTRUCTIONS, "branch instructions" },
{ PERF_COUNT_HW_BRANCH_MISSES, "branch misses" },
};
static __init void intel_arch_events_quirk(void)
{
int bit;
/* disable event that reported as not presend by cpuid */
for_each_set_bit(bit, x86_pmu.events_mask, ARRAY_SIZE(intel_arch_events_map)) {
intel_perfmon_event_map[intel_arch_events_map[bit].id] = 0;
pr_warn("CPUID marked event: \'%s\' unavailable\n",
intel_arch_events_map[bit].name);
}
}
static __init void intel_nehalem_quirk(void)
{
union cpuid10_ebx ebx;
ebx.full = x86_pmu.events_maskl;
if (ebx.split.no_branch_misses_retired) {
/*
* Erratum AAJ80 detected, we work it around by using
* the BR_MISP_EXEC.ANY event. This will over-count
* branch-misses, but it's still much better than the
* architectural event which is often completely bogus:
*/
intel_perfmon_event_map[PERF_COUNT_HW_BRANCH_MISSES] = 0x7f89;
ebx.split.no_branch_misses_retired = 0;
x86_pmu.events_maskl = ebx.full;
pr_info("CPU erratum AAJ80 worked around\n");
}
}
__init int intel_pmu_init(void)
{
union cpuid10_edx edx;
union cpuid10_eax eax;
union cpuid10_ebx ebx;
struct event_constraint *c;
unsigned int unused;
int version;
if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON)) {
switch (boot_cpu_data.x86) {
case 0x6:
return p6_pmu_init();
case 0xb:
return knc_pmu_init();
case 0xf:
return p4_pmu_init();
}
return -ENODEV;
}
/*
* Check whether the Architectural PerfMon supports
* Branch Misses Retired hw_event or not.
*/
cpuid(10, &eax.full, &ebx.full, &unused, &edx.full);
if (eax.split.mask_length < ARCH_PERFMON_EVENTS_COUNT)
return -ENODEV;
version = eax.split.version_id;
if (version < 2)
x86_pmu = core_pmu;
else
x86_pmu = intel_pmu;
x86_pmu.version = version;
x86_pmu.num_counters = eax.split.num_counters;
x86_pmu.cntval_bits = eax.split.bit_width;
x86_pmu.cntval_mask = (1ULL << eax.split.bit_width) - 1;
x86_pmu.events_maskl = ebx.full;
x86_pmu.events_mask_len = eax.split.mask_length;
x86_pmu.max_pebs_events = min_t(unsigned, MAX_PEBS_EVENTS, x86_pmu.num_counters);
/*
* Quirk: v2 perfmon does not report fixed-purpose events, so
* assume at least 3 events:
*/
if (version > 1)
x86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, 3);
/*
* v2 and above have a perf capabilities MSR
*/
if (version > 1) {
u64 capabilities;
rdmsrl(MSR_IA32_PERF_CAPABILITIES, capabilities);
x86_pmu.intel_cap.capabilities = capabilities;
}
intel_ds_init();
x86_add_quirk(intel_arch_events_quirk); /* Install first, so it runs last */
/*
* Install the hw-cache-events table:
*/
switch (boot_cpu_data.x86_model) {
case 14: /* 65 nm core solo/duo, "Yonah" */
pr_cont("Core events, ");
break;
case 15: /* original 65 nm celeron/pentium/core2/xeon, "Merom"/"Conroe" */
x86_add_quirk(intel_clovertown_quirk);
case 22: /* single-core 65 nm celeron/core2solo "Merom-L"/"Conroe-L" */
case 23: /* current 45 nm celeron/core2/xeon "Penryn"/"Wolfdale" */
case 29: /* six-core 45 nm xeon "Dunnington" */
memcpy(hw_cache_event_ids, core2_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_core();
x86_pmu.event_constraints = intel_core2_event_constraints;
x86_pmu.pebs_constraints = intel_core2_pebs_event_constraints;
pr_cont("Core2 events, ");
break;
case 26: /* 45 nm nehalem, "Bloomfield" */
case 30: /* 45 nm nehalem, "Lynnfield" */
case 46: /* 45 nm nehalem-ex, "Beckton" */
memcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_nehalem_event_constraints;
x86_pmu.pebs_constraints = intel_nehalem_pebs_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.extra_regs = intel_nehalem_extra_regs;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
x86_add_quirk(intel_nehalem_quirk);
pr_cont("Nehalem events, ");
break;
case 28: /* Atom */
case 38: /* Lincroft */
case 39: /* Penwell */
case 53: /* Cloverview */
case 54: /* Cedarview */
memcpy(hw_cache_event_ids, atom_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
intel_pmu_lbr_init_atom();
x86_pmu.event_constraints = intel_gen_event_constraints;
x86_pmu.pebs_constraints = intel_atom_pebs_event_constraints;
pr_cont("Atom events, ");
break;
case 37: /* 32 nm nehalem, "Clarkdale" */
case 44: /* 32 nm nehalem, "Gulftown" */
case 47: /* 32 nm Xeon E7 */
memcpy(hw_cache_event_ids, westmere_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, nehalem_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_nhm();
x86_pmu.event_constraints = intel_westmere_event_constraints;
x86_pmu.enable_all = intel_pmu_nhm_enable_all;
x86_pmu.pebs_constraints = intel_westmere_pebs_event_constraints;
x86_pmu.extra_regs = intel_westmere_extra_regs;
x86_pmu.er_flags |= ERF_HAS_RSP_1;
/* UOPS_ISSUED.STALLED_CYCLES */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_EXECUTED.CORE_ACTIVE_CYCLES,c=1,i=1 */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x3f, .inv=1, .cmask=1);
pr_cont("Westmere events, ");
break;
case 42: /* SandyBridge */
case 45: /* SandyBridge, "Romely-EP" */
x86_add_quirk(intel_sandybridge_quirk);
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_snb_event_constraints;
x86_pmu.pebs_constraints = intel_snb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
if (boot_cpu_data.x86_model == 45)
x86_pmu.extra_regs = intel_snbep_extra_regs;
else
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
/* UOPS_DISPATCHED.THREAD,c=1,i=1 to count stall cycles*/
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_BACKEND] =
X86_CONFIG(.event=0xb1, .umask=0x01, .inv=1, .cmask=1);
pr_cont("SandyBridge events, ");
break;
case 58: /* IvyBridge */
case 62: /* IvyBridge EP */
memcpy(hw_cache_event_ids, snb_hw_cache_event_ids,
sizeof(hw_cache_event_ids));
memcpy(hw_cache_extra_regs, snb_hw_cache_extra_regs,
sizeof(hw_cache_extra_regs));
intel_pmu_lbr_init_snb();
x86_pmu.event_constraints = intel_ivb_event_constraints;
x86_pmu.pebs_constraints = intel_ivb_pebs_event_constraints;
x86_pmu.pebs_aliases = intel_pebs_aliases_snb;
if (boot_cpu_data.x86_model == 62)
x86_pmu.extra_regs = intel_snbep_extra_regs;
else
x86_pmu.extra_regs = intel_snb_extra_regs;
/* all extra regs are per-cpu when HT is on */
x86_pmu.er_flags |= ERF_HAS_RSP_1;
x86_pmu.er_flags |= ERF_NO_HT_SHARING;
/* UOPS_ISSUED.ANY,c=1,i=1 to count stall cycles */
intel_perfmon_event_map[PERF_COUNT_HW_STALLED_CYCLES_FRONTEND] =
X86_CONFIG(.event=0x0e, .umask=0x01, .inv=1, .cmask=1);
pr_cont("IvyBridge events, ");
break;
default:
switch (x86_pmu.version) {
case 1:
x86_pmu.event_constraints = intel_v1_event_constraints;
pr_cont("generic architected perfmon v1, ");
break;
default:
/*
* default constraints for v2 and up
*/
x86_pmu.event_constraints = intel_gen_event_constraints;
pr_cont("generic architected perfmon, ");
break;
}
}
if (x86_pmu.num_counters > INTEL_PMC_MAX_GENERIC) {
WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
x86_pmu.num_counters, INTEL_PMC_MAX_GENERIC);
x86_pmu.num_counters = INTEL_PMC_MAX_GENERIC;
}
x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
if (x86_pmu.num_counters_fixed > INTEL_PMC_MAX_FIXED) {
WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
x86_pmu.num_counters_fixed, INTEL_PMC_MAX_FIXED);
x86_pmu.num_counters_fixed = INTEL_PMC_MAX_FIXED;
}
x86_pmu.intel_ctrl |=
((1LL << x86_pmu.num_counters_fixed)-1) << INTEL_PMC_IDX_FIXED;
if (x86_pmu.event_constraints) {
/*
* event on fixed counter2 (REF_CYCLES) only works on this
* counter, so do not extend mask to generic counters
*/
for_each_event_constraint(c, x86_pmu.event_constraints) {
if (c->cmask != X86_RAW_EVENT_MASK
|| c->idxmsk64 == INTEL_PMC_MSK_FIXED_REF_CYCLES) {
continue;
}
c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
c->weight += x86_pmu.num_counters;
}
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5653_0 |
crossvul-cpp_data_bad_2314_0 | /*
* Copyright (c) 2007, 2008, Andrea Bittau <a.bittau@cs.ucl.ac.uk>
*
* OS dependent API for using card via network.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <sys/select.h>
#include <errno.h>
#include "osdep.h"
#include "network.h"
#define QUEUE_MAX 666
struct queue {
unsigned char q_buf[2048];
int q_len;
struct queue *q_next;
struct queue *q_prev;
};
struct priv_net {
int pn_s;
struct queue pn_queue;
struct queue pn_queue_free;
int pn_queue_len;
};
int net_send(int s, int command, void *arg, int len)
{
struct net_hdr *pnh;
char *pktbuf;
size_t pktlen;
pktlen = sizeof(struct net_hdr) + len;
pktbuf = (char*)calloc(sizeof(char), pktlen);
if (pktbuf == NULL) {
perror("calloc");
goto net_send_error;
}
pnh = (struct net_hdr*)pktbuf;
pnh->nh_type = command;
pnh->nh_len = htonl(len);
memcpy(pktbuf + sizeof(struct net_hdr), arg, len);
for (;;) {
ssize_t rc = send(s, pktbuf, pktlen, 0);
if ((size_t)rc == pktlen)
break;
if (rc == EAGAIN || rc == EWOULDBLOCK || rc == EINTR)
continue;
if (rc == ECONNRESET)
printf("Connection reset while sending packet!\n");
goto net_send_error;
}
free(pktbuf);
return 0;
net_send_error:
free(pktbuf);
return -1;
}
int net_read_exact(int s, void *arg, int len)
{
ssize_t rc;
int rlen = 0;
char *buf = (char*)arg;
while (rlen < len) {
rc = recv(s, buf, (len - rlen), 0);
if (rc < 1) {
if (rc == -1 && (errno == EAGAIN || errno == EINTR)) {
usleep(100);
continue;
}
return -1;
}
buf += rc;
rlen += rc;
}
return 0;
}
int net_get(int s, void *arg, int *len)
{
struct net_hdr nh;
int plen;
if (net_read_exact(s, &nh, sizeof(nh)) == -1)
{
return -1;
}
plen = ntohl(nh.nh_len);
if (!(plen <= *len))
printf("PLEN %d type %d len %d\n",
plen, nh.nh_type, *len);
assert(plen <= *len); /* XXX */
*len = plen;
if ((*len) && (net_read_exact(s, arg, *len) == -1))
{
return -1;
}
return nh.nh_type;
}
static void queue_del(struct queue *q)
{
q->q_prev->q_next = q->q_next;
q->q_next->q_prev = q->q_prev;
}
static void queue_add(struct queue *head, struct queue *q)
{
struct queue *pos = head->q_prev;
q->q_prev = pos;
q->q_next = pos->q_next;
q->q_next->q_prev = q;
pos->q_next = q;
}
#if 0
static int queue_len(struct queue *head)
{
struct queue *q = head->q_next;
int i = 0;
while (q != head) {
i++;
q = q->q_next;
}
return i;
}
#endif
static struct queue *queue_get_slot(struct priv_net *pn)
{
struct queue *q = pn->pn_queue_free.q_next;
if (q != &pn->pn_queue_free) {
queue_del(q);
return q;
}
if (pn->pn_queue_len++ > QUEUE_MAX)
return NULL;
return malloc(sizeof(*q));
}
static void net_enque(struct priv_net *pn, void *buf, int len)
{
struct queue *q;
q = queue_get_slot(pn);
if (!q)
return;
q->q_len = len;
assert((int) sizeof(q->q_buf) >= q->q_len);
memcpy(q->q_buf, buf, q->q_len);
queue_add(&pn->pn_queue, q);
}
static int net_get_nopacket(struct priv_net *pn, void *arg, int *len)
{
unsigned char buf[2048];
int l = sizeof(buf);
int c;
while (1) {
l = sizeof(buf);
c = net_get(pn->pn_s, buf, &l);
if (c != NET_PACKET && c > 0)
break;
if(c > 0)
net_enque(pn, buf, l);
}
assert(l <= *len);
memcpy(arg, buf, l);
*len = l;
return c;
}
static int net_cmd(struct priv_net *pn, int command, void *arg, int alen)
{
uint32_t rc;
int len;
int cmd;
if (net_send(pn->pn_s, command, arg, alen) == -1)
{
return -1;
}
len = sizeof(rc);
cmd = net_get_nopacket(pn, &rc, &len);
if (cmd == -1)
{
return -1;
}
assert(cmd == NET_RC);
assert(len == sizeof(rc));
return ntohl(rc);
}
static int queue_get(struct priv_net *pn, void *buf, int len)
{
struct queue *head = &pn->pn_queue;
struct queue *q = head->q_next;
if (q == head)
return 0;
assert(q->q_len <= len);
memcpy(buf, q->q_buf, q->q_len);
queue_del(q);
queue_add(&pn->pn_queue_free, q);
return q->q_len;
}
static int net_read(struct wif *wi, unsigned char *h80211, int len,
struct rx_info *ri)
{
struct priv_net *pn = wi_priv(wi);
uint32_t buf[512]; // 512 * 4 = 2048
unsigned char *bufc = (unsigned char*)buf;
int cmd;
int sz = sizeof(*ri);
int l;
int ret;
/* try queue */
l = queue_get(pn, buf, sizeof(buf));
if (!l) {
/* try reading form net */
l = sizeof(buf);
cmd = net_get(pn->pn_s, buf, &l);
if (cmd == -1)
return -1;
if (cmd == NET_RC)
{
ret = ntohl((buf[0]));
return ret;
}
assert(cmd == NET_PACKET);
}
/* XXX */
if (ri) {
// re-assemble 64-bit integer
ri->ri_mactime = __be64_to_cpu(((uint64_t)buf[0] << 32 || buf[1] ));
ri->ri_power = __be32_to_cpu(buf[2]);
ri->ri_noise = __be32_to_cpu(buf[3]);
ri->ri_channel = __be32_to_cpu(buf[4]);
ri->ri_rate = __be32_to_cpu(buf[5]);
ri->ri_antenna = __be32_to_cpu(buf[6]);
}
l -= sz;
assert(l > 0);
if (l > len)
l = len;
memcpy(h80211, &bufc[sz], l);
return l;
}
static int net_get_mac(struct wif *wi, unsigned char *mac)
{
struct priv_net *pn = wi_priv(wi);
uint32_t buf[2]; // only need 6 bytes, this provides 8
int cmd;
int sz = 6;
if (net_send(pn->pn_s, NET_GET_MAC, NULL, 0) == -1)
return -1;
cmd = net_get_nopacket(pn, buf, &sz);
if (cmd == -1)
return -1;
if (cmd == NET_RC)
return ntohl(buf[0]);
assert(cmd == NET_MAC);
assert(sz == 6);
memcpy(mac, buf, 6);
return 0;
}
static int net_write(struct wif *wi, unsigned char *h80211, int len,
struct tx_info *ti)
{
struct priv_net *pn = wi_priv(wi);
int sz = sizeof(*ti);
unsigned char buf[2048];
unsigned char *ptr = buf;
/* XXX */
if (ti)
memcpy(ptr, ti, sz);
else
memset(ptr, 0, sizeof(*ti));
ptr += sz;
memcpy(ptr, h80211, len);
sz += len;
return net_cmd(pn, NET_WRITE, buf, sz);
}
static int net_set_channel(struct wif *wi, int chan)
{
uint32_t c = htonl(chan);
return net_cmd(wi_priv(wi), NET_SET_CHAN, &c, sizeof(c));
}
static int net_get_channel(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
return net_cmd(pn, NET_GET_CHAN, NULL, 0);
}
static int net_set_rate(struct wif *wi, int rate)
{
uint32_t c = htonl(rate);
return net_cmd(wi_priv(wi), NET_SET_RATE, &c, sizeof(c));
}
static int net_get_rate(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
return net_cmd(pn, NET_GET_RATE, NULL, 0);
}
static int net_get_monitor(struct wif *wi)
{
return net_cmd(wi_priv(wi), NET_GET_MONITOR, NULL, 0);
}
static void do_net_free(struct wif *wi)
{
assert(wi->wi_priv);
free(wi->wi_priv);
wi->wi_priv = 0;
free(wi);
}
static void net_close(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
close(pn->pn_s);
do_net_free(wi);
}
static int get_ip_port(char *iface, char *ip, const int ipsize)
{
char *host;
char *ptr;
int port = -1;
struct in_addr addr;
host = strdup(iface);
if (!host)
return -1;
ptr = strchr(host, ':');
if (!ptr)
goto out;
*ptr++ = 0;
if (!inet_aton(host, &addr))
goto out; /* XXX resolve hostname */
assert(strlen(host) <= 15);
strncpy(ip, host, ipsize);
port = atoi(ptr);
out:
free(host);
return port;
}
static int handshake(int s)
{
if (s) {} /* XXX unused */
/* XXX do a handshake */
return 0;
}
static int do_net_open(char *iface)
{
int s, port;
char ip[16];
struct sockaddr_in s_in;
port = get_ip_port(iface, ip, sizeof(ip)-1);
if (port == -1)
return -1;
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
if (!inet_aton(ip, &s_in.sin_addr))
return -1;
if ((s = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
printf("Connecting to %s port %d...\n", ip, port);
if (connect(s, (struct sockaddr*) &s_in, sizeof(s_in)) == -1) {
close(s);
printf("Failed to connect\n");
return -1;
}
if (handshake(s) == -1) {
close(s);
printf("Failed to connect - handshake failed\n");
return -1;
}
printf("Connection successful\n");
return s;
}
static int net_fd(struct wif *wi)
{
struct priv_net *pn = wi_priv(wi);
return pn->pn_s;
}
struct wif *net_open(char *iface)
{
struct wif *wi;
struct priv_net *pn;
int s;
/* setup wi struct */
wi = wi_alloc(sizeof(*pn));
if (!wi)
return NULL;
wi->wi_read = net_read;
wi->wi_write = net_write;
wi->wi_set_channel = net_set_channel;
wi->wi_get_channel = net_get_channel;
wi->wi_set_rate = net_set_rate;
wi->wi_get_rate = net_get_rate;
wi->wi_close = net_close;
wi->wi_fd = net_fd;
wi->wi_get_mac = net_get_mac;
wi->wi_get_monitor = net_get_monitor;
/* setup iface */
s = do_net_open(iface);
if (s == -1) {
do_net_free(wi);
return NULL;
}
/* setup private state */
pn = wi_priv(wi);
pn->pn_s = s;
pn->pn_queue.q_next = pn->pn_queue.q_prev = &pn->pn_queue;
pn->pn_queue_free.q_next = pn->pn_queue_free.q_prev
= &pn->pn_queue_free;
return wi;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2314_0 |
crossvul-cpp_data_good_5608_0 | /*
* ModSecurity for Apache 2.x, http://www.modsecurity.org/
* Copyright (c) 2004-2011 Trustwave Holdings, Inc. (http://www.trustwave.com/)
*
* You may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* If any of the files related to licensing are missing or if you have any
* other questions related to licensing please contact Trustwave Holdings, Inc.
* directly using the email address security@modsecurity.org.
*/
#include <limits.h>
#include "modsecurity.h"
#include "msc_logging.h"
#include "msc_util.h"
#include "http_log.h"
#include "apr_lib.h"
#include "acmp.h"
#include "msc_crypt.h"
#if defined(WITH_LUA)
#include "msc_lua.h"
#endif
/* -- Directory context creation and initialisation -- */
/**
* Creates a fresh directory configuration.
*/
void *create_directory_config(apr_pool_t *mp, char *path)
{
directory_config *dcfg = (directory_config *)apr_pcalloc(mp, sizeof(directory_config));
if (dcfg == NULL) return NULL;
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Created directory config %pp path %s", dcfg, path);
#endif
dcfg->mp = mp;
dcfg->is_enabled = NOT_SET;
dcfg->reqbody_access = NOT_SET;
dcfg->reqintercept_oe = NOT_SET;
dcfg->reqbody_buffering = NOT_SET;
dcfg->reqbody_inmemory_limit = NOT_SET;
dcfg->reqbody_limit = NOT_SET;
dcfg->reqbody_no_files_limit = NOT_SET;
dcfg->resbody_access = NOT_SET;
dcfg->debuglog_name = NOT_SET_P;
dcfg->debuglog_level = NOT_SET;
dcfg->debuglog_fd = NOT_SET_P;
dcfg->of_limit = NOT_SET;
dcfg->if_limit_action = NOT_SET;
dcfg->of_limit_action = NOT_SET;
dcfg->of_mime_types = NOT_SET_P;
dcfg->of_mime_types_cleared = NOT_SET;
dcfg->cookie_format = NOT_SET;
dcfg->argument_separator = NOT_SET;
dcfg->cookiev0_separator = NOT_SET_P;
dcfg->rule_inheritance = NOT_SET;
dcfg->rule_exceptions = apr_array_make(mp, 16, sizeof(rule_exception *));
dcfg->hash_method = apr_array_make(mp, 16, sizeof(hash_method *));
/* audit log variables */
dcfg->auditlog_flag = NOT_SET;
dcfg->auditlog_type = NOT_SET;
dcfg->max_rule_time = NOT_SET;
dcfg->auditlog_dirperms = NOT_SET;
dcfg->auditlog_fileperms = NOT_SET;
dcfg->auditlog_name = NOT_SET_P;
dcfg->auditlog2_name = NOT_SET_P;
dcfg->auditlog_fd = NOT_SET_P;
dcfg->auditlog2_fd = NOT_SET_P;
dcfg->auditlog_storage_dir = NOT_SET_P;
dcfg->auditlog_parts = NOT_SET_P;
dcfg->auditlog_relevant_regex = NOT_SET_P;
dcfg->ruleset = NULL;
/* Upload */
dcfg->tmp_dir = NOT_SET_P;
dcfg->upload_dir = NOT_SET_P;
dcfg->upload_keep_files = NOT_SET;
dcfg->upload_validates_files = NOT_SET;
dcfg->upload_filemode = NOT_SET;
dcfg->upload_file_limit = NOT_SET;
/* These are only used during the configuration process. */
dcfg->tmp_chain_starter = NULL;
dcfg->tmp_default_actionset = NULL;
dcfg->tmp_rule_placeholders = NULL;
/* Misc */
dcfg->data_dir = NOT_SET_P;
dcfg->webappid = NOT_SET_P;
dcfg->sensor_id = NOT_SET_P;
dcfg->httpBlkey = NOT_SET_P;
/* Content injection. */
dcfg->content_injection_enabled = NOT_SET;
/* Stream inspection */
dcfg->stream_inbody_inspection = NOT_SET;
dcfg->stream_outbody_inspection = NOT_SET;
/* Geo Lookups */
dcfg->geo = NOT_SET_P;
/* Gsb Lookups */
dcfg->gsb = NOT_SET_P;
/* Unicode Map */
dcfg->u_map = NOT_SET_P;
/* Cache */
dcfg->cache_trans = NOT_SET;
dcfg->cache_trans_incremental = NOT_SET;
dcfg->cache_trans_min = NOT_SET;
dcfg->cache_trans_max = NOT_SET;
dcfg->cache_trans_maxitems = NOT_SET;
/* Rule ids */
dcfg->rule_id_htab = apr_hash_make(mp);
dcfg->component_signatures = apr_array_make(mp, 16, sizeof(char *));
dcfg->request_encoding = NOT_SET_P;
dcfg->disable_backend_compression = NOT_SET;
/* Collection timeout */
dcfg->col_timeout = NOT_SET;
dcfg->crypto_key = NOT_SET_P;
dcfg->crypto_key_len = NOT_SET;
dcfg->crypto_key_add = NOT_SET;
dcfg->crypto_param_name = NOT_SET_P;
dcfg->hash_is_enabled = NOT_SET;
dcfg->hash_enforcement = NOT_SET;
dcfg->crypto_hash_href_rx = NOT_SET;
dcfg->crypto_hash_faction_rx = NOT_SET;
dcfg->crypto_hash_location_rx = NOT_SET;
dcfg->crypto_hash_iframesrc_rx = NOT_SET;
dcfg->crypto_hash_framesrc_rx = NOT_SET;
dcfg->crypto_hash_href_pm = NOT_SET;
dcfg->crypto_hash_faction_pm = NOT_SET;
dcfg->crypto_hash_location_pm = NOT_SET;
dcfg->crypto_hash_iframesrc_pm = NOT_SET;
dcfg->crypto_hash_framesrc_pm = NOT_SET;
/* xml external entity */
dcfg->xml_external_entity = NOT_SET;
return dcfg;
}
/**
* Copies rules between one phase of two configuration contexts,
* taking exceptions into account.
*/
static void copy_rules_phase(apr_pool_t *mp,
apr_array_header_t *parent_phase_arr,
apr_array_header_t *child_phase_arr,
apr_array_header_t *exceptions_arr)
{
rule_exception **exceptions;
msre_rule **rules;
int i, j;
int mode = 0;
rules = (msre_rule **)parent_phase_arr->elts;
for(i = 0; i < parent_phase_arr->nelts; i++) {
msre_rule *rule = (msre_rule *)rules[i];
int copy = 1;
if (mode == 0) {
/* First rule in the chain. */
exceptions = (rule_exception **)exceptions_arr->elts;
for(j = 0; j < exceptions_arr->nelts; j++) {
/* Process exceptions. */
switch(exceptions[j]->type) {
case RULE_EXCEPTION_REMOVE_ID :
if ((rule->actionset != NULL)&&(rule->actionset->id != NULL)) {
int ruleid = atoi(rule->actionset->id);
if (rule_id_in_range(ruleid, exceptions[j]->param)) copy--;
}
break;
case RULE_EXCEPTION_REMOVE_MSG :
if ((rule->actionset != NULL)&&(rule->actionset->msg != NULL)) {
char *my_error_msg = NULL;
int rc = msc_regexec(exceptions[j]->param_data,
rule->actionset->msg, strlen(rule->actionset->msg),
&my_error_msg);
if (rc >= 0) copy--;
}
break;
case RULE_EXCEPTION_REMOVE_TAG :
if ((rule->actionset != NULL)&&(apr_is_empty_table(rule->actionset->actions) == 0)) {
char *my_error_msg = NULL;
const apr_array_header_t *tarr = NULL;
const apr_table_entry_t *telts = NULL;
int c;
tarr = apr_table_elts(rule->actionset->actions);
telts = (const apr_table_entry_t*)tarr->elts;
for (c = 0; c < tarr->nelts; c++) {
msre_action *action = (msre_action *)telts[c].val;
if(strcmp("tag", action->metadata->name) == 0) {
int rc = msc_regexec(exceptions[j]->param_data,
action->param, strlen(action->param),
&my_error_msg);
if (rc >= 0) copy--;
}
}
}
break;
}
}
if (copy > 0) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Copy rule %pp [id \"%s\"]", rule, rule->actionset->id);
#endif
/* Copy the rule. */
*(msre_rule **)apr_array_push(child_phase_arr) = rule;
if (rule->actionset->is_chained) mode = 2;
} else {
if (rule->actionset->is_chained) mode = 1;
}
} else {
if (mode == 2) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Copy chain %pp for rule %pp [id \"%s\"]", rule, rule->chain_starter, rule->chain_starter->actionset->id);
#endif
/* Copy the rule (it belongs to the chain we want to include. */
*(msre_rule **)apr_array_push(child_phase_arr) = rule;
}
if ((rule->actionset == NULL)||(rule->actionset->is_chained == 0)) mode = 0;
}
}
}
/**
* Copies rules between two configuration contexts,
* taking exceptions into account.
*/
static int copy_rules(apr_pool_t *mp, msre_ruleset *parent_ruleset,
msre_ruleset *child_ruleset,
apr_array_header_t *exceptions_arr)
{
copy_rules_phase(mp, parent_ruleset->phase_request_headers,
child_ruleset->phase_request_headers, exceptions_arr);
copy_rules_phase(mp, parent_ruleset->phase_request_body,
child_ruleset->phase_request_body, exceptions_arr);
copy_rules_phase(mp, parent_ruleset->phase_response_headers,
child_ruleset->phase_response_headers, exceptions_arr);
copy_rules_phase(mp, parent_ruleset->phase_response_body,
child_ruleset->phase_response_body, exceptions_arr);
copy_rules_phase(mp, parent_ruleset->phase_logging,
child_ruleset->phase_logging, exceptions_arr);
return 1;
}
/**
* Merges two directory configurations.
*/
void *merge_directory_configs(apr_pool_t *mp, void *_parent, void *_child)
{
directory_config *parent = (directory_config *)_parent;
directory_config *child = (directory_config *)_child;
directory_config *merged = create_directory_config(mp, NULL);
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Merge parent %pp child %pp RESULT %pp", _parent, _child, merged);
#endif
if (merged == NULL) return NULL;
/* Use values from the child configuration where possible,
* otherwise use the parent's.
*/
merged->is_enabled = (child->is_enabled == NOT_SET
? parent->is_enabled : child->is_enabled);
/* IO parameters */
merged->reqbody_access = (child->reqbody_access == NOT_SET
? parent->reqbody_access : child->reqbody_access);
merged->reqbody_buffering = (child->reqbody_buffering == NOT_SET
? parent->reqbody_buffering : child->reqbody_buffering);
merged->reqbody_inmemory_limit = (child->reqbody_inmemory_limit == NOT_SET
? parent->reqbody_inmemory_limit : child->reqbody_inmemory_limit);
merged->reqbody_limit = (child->reqbody_limit == NOT_SET
? parent->reqbody_limit : child->reqbody_limit);
merged->reqbody_no_files_limit = (child->reqbody_no_files_limit == NOT_SET
? parent->reqbody_no_files_limit : child->reqbody_no_files_limit);
merged->resbody_access = (child->resbody_access == NOT_SET
? parent->resbody_access : child->resbody_access);
merged->of_limit = (child->of_limit == NOT_SET
? parent->of_limit : child->of_limit);
merged->if_limit_action = (child->if_limit_action == NOT_SET
? parent->if_limit_action : child->if_limit_action);
merged->of_limit_action = (child->of_limit_action == NOT_SET
? parent->of_limit_action : child->of_limit_action);
merged->reqintercept_oe = (child->reqintercept_oe == NOT_SET
? parent->reqintercept_oe : child->reqintercept_oe);
if (child->of_mime_types != NOT_SET_P) {
/* Child added to the table */
if (child->of_mime_types_cleared == 1) {
/* The list of MIME types was cleared in the child,
* which means the parent's MIME types went away and
* we should not take them into consideration here.
*/
merged->of_mime_types = child->of_mime_types;
merged->of_mime_types_cleared = 1;
} else {
/* Add MIME types defined in the child to those
* defined in the parent context.
*/
if (parent->of_mime_types == NOT_SET_P) {
merged->of_mime_types = child->of_mime_types;
merged->of_mime_types_cleared = NOT_SET;
} else {
merged->of_mime_types = apr_table_overlay(mp, parent->of_mime_types,
child->of_mime_types);
if (merged->of_mime_types == NULL) return NULL;
}
}
} else {
/* Child did not add to the table */
if (child->of_mime_types_cleared == 1) {
merged->of_mime_types_cleared = 1;
} else {
merged->of_mime_types = parent->of_mime_types;
merged->of_mime_types_cleared = parent->of_mime_types_cleared;
}
}
/* debug log */
if (child->debuglog_fd == NOT_SET_P) {
merged->debuglog_name = parent->debuglog_name;
merged->debuglog_fd = parent->debuglog_fd;
} else {
merged->debuglog_name = child->debuglog_name;
merged->debuglog_fd = child->debuglog_fd;
}
merged->debuglog_level = (child->debuglog_level == NOT_SET
? parent->debuglog_level : child->debuglog_level);
merged->cookie_format = (child->cookie_format == NOT_SET
? parent->cookie_format : child->cookie_format);
merged->argument_separator = (child->argument_separator == NOT_SET
? parent->argument_separator : child->argument_separator);
merged->cookiev0_separator = (child->cookiev0_separator == NOT_SET_P
? parent->cookiev0_separator : child->cookiev0_separator);
/* rule inheritance */
if ((child->rule_inheritance == NOT_SET)||(child->rule_inheritance == 1)) {
merged->rule_inheritance = parent->rule_inheritance;
if ((child->ruleset == NULL)&&(parent->ruleset == NULL)) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "No rules in this context.");
#endif
/* Do nothing, there are no rules in either context. */
} else
if (child->ruleset == NULL) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Using parent rules in this context.");
#endif
/* Copy the rules from the parent context. */
merged->ruleset = msre_ruleset_create(parent->ruleset->engine, mp);
copy_rules(mp, parent->ruleset, merged->ruleset, child->rule_exceptions);
} else
if (parent->ruleset == NULL) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Using child rules in this context.");
#endif
/* Copy child rules. */
merged->ruleset = msre_ruleset_create(child->ruleset->engine, mp);
merged->ruleset->phase_request_headers = apr_array_copy(mp,
child->ruleset->phase_request_headers);
merged->ruleset->phase_request_body = apr_array_copy(mp,
child->ruleset->phase_request_body);
merged->ruleset->phase_response_headers = apr_array_copy(mp,
child->ruleset->phase_response_headers);
merged->ruleset->phase_response_body = apr_array_copy(mp,
child->ruleset->phase_response_body);
merged->ruleset->phase_logging = apr_array_copy(mp,
child->ruleset->phase_logging);
} else {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, mp, "Using parent then child rules in this context.");
#endif
/* Copy parent rules, then add child rules to it. */
merged->ruleset = msre_ruleset_create(parent->ruleset->engine, mp);
copy_rules(mp, parent->ruleset, merged->ruleset, child->rule_exceptions);
apr_array_cat(merged->ruleset->phase_request_headers,
child->ruleset->phase_request_headers);
apr_array_cat(merged->ruleset->phase_request_body,
child->ruleset->phase_request_body);
apr_array_cat(merged->ruleset->phase_response_headers,
child->ruleset->phase_response_headers);
apr_array_cat(merged->ruleset->phase_response_body,
child->ruleset->phase_response_body);
apr_array_cat(merged->ruleset->phase_logging,
child->ruleset->phase_logging);
}
} else {
merged->rule_inheritance = 0;
if (child->ruleset != NULL) {
/* Copy child rules. */
merged->ruleset = msre_ruleset_create(child->ruleset->engine, mp);
merged->ruleset->phase_request_headers = apr_array_copy(mp,
child->ruleset->phase_request_headers);
merged->ruleset->phase_request_body = apr_array_copy(mp,
child->ruleset->phase_request_body);
merged->ruleset->phase_response_headers = apr_array_copy(mp,
child->ruleset->phase_response_headers);
merged->ruleset->phase_response_body = apr_array_copy(mp,
child->ruleset->phase_response_body);
merged->ruleset->phase_logging = apr_array_copy(mp,
child->ruleset->phase_logging);
}
}
/* Merge rule exceptions. */
merged->rule_exceptions = apr_array_append(mp, parent->rule_exceptions,
child->rule_exceptions);
merged->hash_method = apr_array_append(mp, parent->hash_method,
child->hash_method);
/* audit log variables */
merged->auditlog_flag = (child->auditlog_flag == NOT_SET
? parent->auditlog_flag : child->auditlog_flag);
merged->auditlog_type = (child->auditlog_type == NOT_SET
? parent->auditlog_type : child->auditlog_type);
merged->max_rule_time = (child->max_rule_time == NOT_SET
? parent->max_rule_time : child->max_rule_time);
merged->auditlog_dirperms = (child->auditlog_dirperms == NOT_SET
? parent->auditlog_dirperms : child->auditlog_dirperms);
merged->auditlog_fileperms = (child->auditlog_fileperms == NOT_SET
? parent->auditlog_fileperms : child->auditlog_fileperms);
if (child->auditlog_fd != NOT_SET_P) {
merged->auditlog_fd = child->auditlog_fd;
merged->auditlog_name = child->auditlog_name;
} else {
merged->auditlog_fd = parent->auditlog_fd;
merged->auditlog_name = parent->auditlog_name;
}
if (child->auditlog2_fd != NOT_SET_P) {
merged->auditlog2_fd = child->auditlog2_fd;
merged->auditlog2_name = child->auditlog2_name;
} else {
merged->auditlog2_fd = parent->auditlog2_fd;
merged->auditlog2_name = parent->auditlog2_name;
}
merged->auditlog_storage_dir = (child->auditlog_storage_dir == NOT_SET_P
? parent->auditlog_storage_dir : child->auditlog_storage_dir);
merged->auditlog_parts = (child->auditlog_parts == NOT_SET_P
? parent->auditlog_parts : child->auditlog_parts);
merged->auditlog_relevant_regex = (child->auditlog_relevant_regex == NOT_SET_P
? parent->auditlog_relevant_regex : child->auditlog_relevant_regex);
/* Upload */
merged->tmp_dir = (child->tmp_dir == NOT_SET_P
? parent->tmp_dir : child->tmp_dir);
merged->upload_dir = (child->upload_dir == NOT_SET_P
? parent->upload_dir : child->upload_dir);
merged->upload_keep_files = (child->upload_keep_files == NOT_SET
? parent->upload_keep_files : child->upload_keep_files);
merged->upload_validates_files = (child->upload_validates_files == NOT_SET
? parent->upload_validates_files : child->upload_validates_files);
merged->upload_filemode = (child->upload_filemode == NOT_SET
? parent->upload_filemode : child->upload_filemode);
merged->upload_file_limit = (child->upload_file_limit == NOT_SET
? parent->upload_file_limit : child->upload_file_limit);
/* Misc */
merged->data_dir = (child->data_dir == NOT_SET_P
? parent->data_dir : child->data_dir);
merged->webappid = (child->webappid == NOT_SET_P
? parent->webappid : child->webappid);
merged->sensor_id = (child->sensor_id == NOT_SET_P
? parent->sensor_id : child->sensor_id);
merged->httpBlkey = (child->httpBlkey == NOT_SET_P
? parent->httpBlkey : child->httpBlkey);
/* Content injection. */
merged->content_injection_enabled = (child->content_injection_enabled == NOT_SET
? parent->content_injection_enabled : child->content_injection_enabled);
/* Stream inspection */
merged->stream_inbody_inspection = (child->stream_inbody_inspection == NOT_SET
? parent->stream_inbody_inspection : child->stream_inbody_inspection);
merged->stream_outbody_inspection = (child->stream_outbody_inspection == NOT_SET
? parent->stream_outbody_inspection : child->stream_outbody_inspection);
/* Geo Lookup */
merged->geo = (child->geo == NOT_SET_P
? parent->geo : child->geo);
/* Gsb Lookup */
merged->gsb = (child->gsb == NOT_SET_P
? parent->gsb : child->gsb);
/* Unicode Map */
merged->u_map = (child->u_map == NOT_SET_P
? parent->u_map : child->u_map);
/* Cache */
merged->cache_trans = (child->cache_trans == NOT_SET
? parent->cache_trans : child->cache_trans);
merged->cache_trans_incremental = (child->cache_trans_incremental == NOT_SET
? parent->cache_trans_incremental : child->cache_trans_incremental);
merged->cache_trans_min = (child->cache_trans_min == (apr_size_t)NOT_SET
? parent->cache_trans_min : child->cache_trans_min);
merged->cache_trans_max = (child->cache_trans_max == (apr_size_t)NOT_SET
? parent->cache_trans_max : child->cache_trans_max);
merged->cache_trans_maxitems = (child->cache_trans_maxitems == (apr_size_t)NOT_SET
? parent->cache_trans_maxitems : child->cache_trans_maxitems);
/* Merge component signatures. */
merged->component_signatures = apr_array_append(mp, parent->component_signatures,
child->component_signatures);
merged->request_encoding = (child->request_encoding == NOT_SET_P
? parent->request_encoding : child->request_encoding);
merged->disable_backend_compression = (child->disable_backend_compression == NOT_SET
? parent->disable_backend_compression : child->disable_backend_compression);
merged->col_timeout = (child->col_timeout == NOT_SET
? parent->col_timeout : child->col_timeout);
/* Hash */
merged->crypto_key = (child->crypto_key == NOT_SET_P
? parent->crypto_key : child->crypto_key);
merged->crypto_key_len = (child->crypto_key_len == NOT_SET
? parent->crypto_key_len : child->crypto_key_len);
merged->crypto_key_add = (child->crypto_key_add == NOT_SET
? parent->crypto_key_add : child->crypto_key_add);
merged->crypto_param_name = (child->crypto_param_name == NOT_SET_P
? parent->crypto_param_name : child->crypto_param_name);
merged->hash_is_enabled = (child->hash_is_enabled == NOT_SET
? parent->hash_is_enabled : child->hash_is_enabled);
merged->hash_enforcement = (child->hash_enforcement == NOT_SET
? parent->hash_enforcement : child->hash_enforcement);
merged->crypto_hash_href_rx = (child->crypto_hash_href_rx == NOT_SET
? parent->crypto_hash_href_rx : child->crypto_hash_href_rx);
merged->crypto_hash_faction_rx = (child->crypto_hash_faction_rx == NOT_SET
? parent->crypto_hash_faction_rx : child->crypto_hash_faction_rx);
merged->crypto_hash_location_rx = (child->crypto_hash_location_rx == NOT_SET
? parent->crypto_hash_location_rx : child->crypto_hash_location_rx);
merged->crypto_hash_iframesrc_rx = (child->crypto_hash_iframesrc_rx == NOT_SET
? parent->crypto_hash_iframesrc_rx : child->crypto_hash_iframesrc_rx);
merged->crypto_hash_framesrc_rx = (child->crypto_hash_framesrc_rx == NOT_SET
? parent->crypto_hash_framesrc_rx : child->crypto_hash_framesrc_rx);
merged->crypto_hash_href_pm = (child->crypto_hash_href_pm == NOT_SET
? parent->crypto_hash_href_pm : child->crypto_hash_href_pm);
merged->crypto_hash_faction_pm = (child->crypto_hash_faction_pm == NOT_SET
? parent->crypto_hash_faction_pm : child->crypto_hash_faction_pm);
merged->crypto_hash_location_pm = (child->crypto_hash_location_pm == NOT_SET
? parent->crypto_hash_location_pm : child->crypto_hash_location_pm);
merged->crypto_hash_iframesrc_pm = (child->crypto_hash_iframesrc_pm == NOT_SET
? parent->crypto_hash_iframesrc_pm : child->crypto_hash_iframesrc_pm);
merged->crypto_hash_framesrc_pm = (child->crypto_hash_framesrc_pm == NOT_SET
? parent->crypto_hash_framesrc_pm : child->crypto_hash_framesrc_pm);
/* xml external entity */
merged->xml_external_entity = (child->xml_external_entity == NOT_SET
? parent->xml_external_entity : child->xml_external_entity);
return merged;
}
/**
* Initialise directory configuration. This function is *not* meant
* to be called for directory configuration instances created during
* the configuration phase. It can only be called on copies of those
* (created fresh for every transaction).
*/
void init_directory_config(directory_config *dcfg)
{
if (dcfg == NULL) return;
if (dcfg->is_enabled == NOT_SET) dcfg->is_enabled = 0;
if (dcfg->reqbody_access == NOT_SET) dcfg->reqbody_access = 0;
if (dcfg->reqintercept_oe == NOT_SET) dcfg->reqintercept_oe = 0;
if (dcfg->reqbody_buffering == NOT_SET) dcfg->reqbody_buffering = REQUEST_BODY_FORCEBUF_OFF;
if (dcfg->reqbody_inmemory_limit == NOT_SET)
dcfg->reqbody_inmemory_limit = REQUEST_BODY_DEFAULT_INMEMORY_LIMIT;
if (dcfg->reqbody_limit == NOT_SET) dcfg->reqbody_limit = REQUEST_BODY_DEFAULT_LIMIT;
if (dcfg->reqbody_no_files_limit == NOT_SET) dcfg->reqbody_no_files_limit = REQUEST_BODY_NO_FILES_DEFAULT_LIMIT;
if (dcfg->resbody_access == NOT_SET) dcfg->resbody_access = 0;
if (dcfg->of_limit == NOT_SET) dcfg->of_limit = RESPONSE_BODY_DEFAULT_LIMIT;
if (dcfg->if_limit_action == NOT_SET) dcfg->if_limit_action = REQUEST_BODY_LIMIT_ACTION_REJECT;
if (dcfg->of_limit_action == NOT_SET) dcfg->of_limit_action = RESPONSE_BODY_LIMIT_ACTION_REJECT;
if (dcfg->of_mime_types == NOT_SET_P) {
dcfg->of_mime_types = apr_table_make(dcfg->mp, 3);
if (dcfg->of_mime_types_cleared != 1) {
apr_table_setn(dcfg->of_mime_types, "text/plain", "1");
apr_table_setn(dcfg->of_mime_types, "text/html", "1");
}
}
if (dcfg->debuglog_fd == NOT_SET_P) dcfg->debuglog_fd = NULL;
if (dcfg->debuglog_name == NOT_SET_P) dcfg->debuglog_name = NULL;
if (dcfg->debuglog_level == NOT_SET) dcfg->debuglog_level = 0;
if (dcfg->cookie_format == NOT_SET) dcfg->cookie_format = 0;
if (dcfg->argument_separator == NOT_SET) dcfg->argument_separator = '&';
if (dcfg->cookiev0_separator == NOT_SET_P) dcfg->cookiev0_separator = NULL;
if (dcfg->rule_inheritance == NOT_SET) dcfg->rule_inheritance = 1;
/* audit log variables */
if (dcfg->auditlog_flag == NOT_SET) dcfg->auditlog_flag = 0;
if (dcfg->auditlog_type == NOT_SET) dcfg->auditlog_type = AUDITLOG_SERIAL;
if (dcfg->max_rule_time == NOT_SET) dcfg->max_rule_time = 0;
if (dcfg->auditlog_dirperms == NOT_SET) dcfg->auditlog_dirperms = CREATEMODE_DIR;
if (dcfg->auditlog_fileperms == NOT_SET) dcfg->auditlog_fileperms = CREATEMODE;
if (dcfg->auditlog_fd == NOT_SET_P) dcfg->auditlog_fd = NULL;
if (dcfg->auditlog2_fd == NOT_SET_P) dcfg->auditlog2_fd = NULL;
if (dcfg->auditlog_name == NOT_SET_P) dcfg->auditlog_name = NULL;
if (dcfg->auditlog2_name == NOT_SET_P) dcfg->auditlog2_name = NULL;
if (dcfg->auditlog_storage_dir == NOT_SET_P) dcfg->auditlog_storage_dir = NULL;
if (dcfg->auditlog_parts == NOT_SET_P) dcfg->auditlog_parts = "ABCFHZ";
if (dcfg->auditlog_relevant_regex == NOT_SET_P) dcfg->auditlog_relevant_regex = NULL;
/* Upload */
if (dcfg->tmp_dir == NOT_SET_P) dcfg->tmp_dir = guess_tmp_dir(dcfg->mp);
if (dcfg->upload_dir == NOT_SET_P) dcfg->upload_dir = NULL;
if (dcfg->upload_keep_files == NOT_SET) dcfg->upload_keep_files = KEEP_FILES_OFF;
if (dcfg->upload_validates_files == NOT_SET) dcfg->upload_validates_files = 0;
if (dcfg->upload_filemode == NOT_SET) dcfg->upload_filemode = 0600;
if (dcfg->upload_file_limit == NOT_SET) dcfg->upload_file_limit = 100;
/* Misc */
if (dcfg->data_dir == NOT_SET_P) dcfg->data_dir = NULL;
if (dcfg->webappid == NOT_SET_P) dcfg->webappid = "default";
if (dcfg->sensor_id == NOT_SET_P) dcfg->sensor_id = "default";
if (dcfg->httpBlkey == NOT_SET_P) dcfg->httpBlkey = NULL;
/* Content injection. */
if (dcfg->content_injection_enabled == NOT_SET) dcfg->content_injection_enabled = 0;
/* Stream inspection */
if (dcfg->stream_inbody_inspection == NOT_SET) dcfg->stream_inbody_inspection = 0;
if (dcfg->stream_outbody_inspection == NOT_SET) dcfg->stream_outbody_inspection = 0;
/* Geo Lookup */
if (dcfg->geo == NOT_SET_P) dcfg->geo = NULL;
/* Gsb Lookup */
if (dcfg->gsb == NOT_SET_P) dcfg->gsb = NULL;
/* Unicode Map */
if (dcfg->u_map == NOT_SET_P) dcfg->u_map = NULL;
/* Cache */
if (dcfg->cache_trans == NOT_SET) dcfg->cache_trans = MODSEC_CACHE_DISABLED;
if (dcfg->cache_trans_incremental == NOT_SET) dcfg->cache_trans_incremental = 0;
if (dcfg->cache_trans_min == (apr_size_t)NOT_SET) dcfg->cache_trans_min = 32;
if (dcfg->cache_trans_max == (apr_size_t)NOT_SET) dcfg->cache_trans_max = 1024;
if (dcfg->cache_trans_maxitems == (apr_size_t)NOT_SET) dcfg->cache_trans_maxitems = 512;
if (dcfg->request_encoding == NOT_SET_P) dcfg->request_encoding = NULL;
if (dcfg->disable_backend_compression == NOT_SET) dcfg->disable_backend_compression = 0;
if (dcfg->col_timeout == NOT_SET) dcfg->col_timeout = 3600;
/* Hash */
if (dcfg->crypto_key == NOT_SET_P) dcfg->crypto_key = getkey(dcfg->mp);
if (dcfg->crypto_key_len == NOT_SET) dcfg->crypto_key_len = strlen(dcfg->crypto_key);
if (dcfg->crypto_key_add == NOT_SET) dcfg->crypto_key_add = HASH_KEYONLY;
if (dcfg->crypto_param_name == NOT_SET_P) dcfg->crypto_param_name = "crypt";
if (dcfg->hash_is_enabled == NOT_SET) dcfg->hash_is_enabled = HASH_DISABLED;
if (dcfg->hash_enforcement == NOT_SET) dcfg->hash_enforcement = HASH_DISABLED;
if (dcfg->crypto_hash_href_rx == NOT_SET) dcfg->crypto_hash_href_rx = 0;
if (dcfg->crypto_hash_faction_rx == NOT_SET) dcfg->crypto_hash_faction_rx = 0;
if (dcfg->crypto_hash_location_rx == NOT_SET) dcfg->crypto_hash_location_rx = 0;
if (dcfg->crypto_hash_iframesrc_rx == NOT_SET) dcfg->crypto_hash_iframesrc_rx = 0;
if (dcfg->crypto_hash_framesrc_rx == NOT_SET) dcfg->crypto_hash_framesrc_rx = 0;
if (dcfg->crypto_hash_href_pm == NOT_SET) dcfg->crypto_hash_href_pm = 0;
if (dcfg->crypto_hash_faction_pm == NOT_SET) dcfg->crypto_hash_faction_pm = 0;
if (dcfg->crypto_hash_location_pm == NOT_SET) dcfg->crypto_hash_location_pm = 0;
if (dcfg->crypto_hash_iframesrc_pm == NOT_SET) dcfg->crypto_hash_iframesrc_pm = 0;
if (dcfg->crypto_hash_framesrc_pm == NOT_SET) dcfg->crypto_hash_framesrc_pm = 0;
/* xml external entity */
if (dcfg->xml_external_entity == NOT_SET) dcfg->xml_external_entity = 0;
}
/**
*
*/
static const char *add_rule(cmd_parms *cmd, directory_config *dcfg, int type,
const char *p1, const char *p2, const char *p3)
{
char *my_error_msg = NULL;
//msre_rule *rule = NULL, *tmp_rule = NULL;
char *rid = NULL;
msre_rule *rule = NULL;
extern msc_engine *modsecurity;
int offset = 0;
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Rule: type=%d p1='%s' p2='%s' p3='%s'", type, p1, p2, p3);
#endif
/* Create a ruleset if one does not exist. */
if ((dcfg->ruleset == NULL)||(dcfg->ruleset == NOT_SET_P)) {
dcfg->ruleset = msre_ruleset_create(modsecurity->msre, cmd->pool);
if (dcfg->ruleset == NULL) return FATAL_ERROR;
}
/* Create the rule now. */
switch(type) {
#if defined(WITH_LUA)
case RULE_TYPE_LUA :
rule = msre_rule_lua_create(dcfg->ruleset, cmd->directive->filename,
cmd->directive->line_num, p1, p2, &my_error_msg);
break;
#endif
default :
rule = msre_rule_create(dcfg->ruleset, type, cmd->directive->filename,
cmd->directive->line_num, p1, p2, p3, &my_error_msg);
break;
}
if (rule == NULL) {
return my_error_msg;
}
/* Rules must have uniq ID */
if (
#if defined(WITH_LUA)
type != RULE_TYPE_LUA &&
#endif
(dcfg->tmp_chain_starter == NULL))
if(rule->actionset == NULL)
return "ModSecurity: Rules must have at least id action";
if(rule->actionset != NULL && (dcfg->tmp_chain_starter == NULL)) {
if(rule->actionset->id == NOT_SET_P
#if defined(WITH_LUA)
&& (type != RULE_TYPE_LUA)
#endif
)
return "ModSecurity: No action id present within the rule";
#if defined(WITH_LUA)
if(type != RULE_TYPE_LUA)
#endif
{
rid = apr_hash_get(dcfg->rule_id_htab, rule->actionset->id, APR_HASH_KEY_STRING);
if(rid != NULL) {
return "ModSecurity: Found another rule with the same id";
} else {
apr_hash_set(dcfg->rule_id_htab, apr_pstrdup(dcfg->mp, rule->actionset->id), APR_HASH_KEY_STRING, apr_pstrdup(dcfg->mp, "1"));
}
//tmp_rule = msre_ruleset_fetch_rule(dcfg->ruleset, rule->actionset->id, offset);
//if(tmp_rule != NULL)
// return "ModSecurity: Found another rule with the same id";
}
}
/* Create default actionset if one does not already exist. */
if (dcfg->tmp_default_actionset == NULL) {
dcfg->tmp_default_actionset = msre_actionset_create_default(modsecurity->msre);
if (dcfg->tmp_default_actionset == NULL) return FATAL_ERROR;
}
/* Check some cases prior to merging so we know where it came from */
/* Check syntax for chained rules */
if ((rule->actionset != NULL) && (dcfg->tmp_chain_starter != NULL)) {
/* Must NOT specify a disruptive action. */
if (rule->actionset->intercept_action != NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: Disruptive actions can only "
"be specified by chain starter rules.");
}
/* Must NOT specify a skipafter action. */
if (rule->actionset->skip_after != NOT_SET_P) {
return apr_psprintf(cmd->pool, "ModSecurity: SkipAfter actions can only "
"be specified by chain starter rules.");
}
/* Must NOT specify a phase. */
if (rule->actionset->phase != NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: Execution phases can only be "
"specified by chain starter rules.");
}
/* Must NOT use metadata actions. */
/* ENH: loop through to check for tags */
if ((rule->actionset->id != NOT_SET_P)
||(rule->actionset->rev != NOT_SET_P)
||(rule->actionset->msg != NOT_SET_P)
||(rule->actionset->severity != NOT_SET)
||(rule->actionset->version != NOT_SET_P)
||(rule->actionset->accuracy != NOT_SET)
||(rule->actionset->maturity != NOT_SET)
||(rule->actionset->logdata != NOT_SET_P))
{
return apr_psprintf(cmd->pool, "ModSecurity: Metadata actions (id, rev, msg, tag, severity, ver, accuracy, maturity, logdata) "
" can only be specified by chain starter rules.");
}
/* Must NOT use skip. */
if (rule->actionset->skip_count != NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: The skip action can only be used "
" by chain starter rules. ");
}
}
/* Merge actions with the parent.
*
* ENH Probably do not want this done fully for chained rules.
*/
rule->actionset = msre_actionset_merge(modsecurity->msre, dcfg->tmp_default_actionset,
rule->actionset, 1);
/* Keep track of the parent action for "block" */
rule->actionset->parent_intercept_action_rec = dcfg->tmp_default_actionset->intercept_action_rec;
rule->actionset->parent_intercept_action = dcfg->tmp_default_actionset->intercept_action;
/* Must NOT specify a disruptive action in logging phase. */
if ((rule->actionset != NULL)
&& (rule->actionset->phase == PHASE_LOGGING)
&& (rule->actionset->intercept_action != ACTION_ALLOW)
&& (rule->actionset->intercept_action != ACTION_ALLOW_REQUEST)
&& (rule->actionset->intercept_action != ACTION_NONE)
) {
return apr_psprintf(cmd->pool, "ModSecurity: Disruptive actions "
"cannot be specified in the logging phase.");
}
if (dcfg->tmp_chain_starter != NULL) {
rule->chain_starter = dcfg->tmp_chain_starter;
rule->actionset->phase = rule->chain_starter->actionset->phase;
}
if (rule->actionset->is_chained != 1) {
/* If this rule is part of the chain but does
* not want more rules to follow in the chain
* then cut it (the chain).
*/
dcfg->tmp_chain_starter = NULL;
} else {
/* On the other hand, if this rule wants other
* rules to follow it, then start a new chain
* if there isn't one already.
*/
if (dcfg->tmp_chain_starter == NULL) {
dcfg->tmp_chain_starter = rule;
}
}
/* Optimisation */
if ((rule->op_name != NULL)&&(strcasecmp(rule->op_name, "inspectFile") == 0)) {
dcfg->upload_validates_files = 1;
}
/* Create skip table if one does not already exist. */
if (dcfg->tmp_rule_placeholders == NULL) {
dcfg->tmp_rule_placeholders = apr_table_make(cmd->pool, 10);
if (dcfg->tmp_rule_placeholders == NULL) return FATAL_ERROR;
}
/* Keep track of any rule IDs we need to skip after */
if (rule->actionset->skip_after != NOT_SET_P) {
char *tmp_id = apr_pstrdup(cmd->pool, rule->actionset->skip_after);
apr_table_setn(dcfg->tmp_rule_placeholders, tmp_id, tmp_id);
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Watching for skipafter target rule id=\"%s\".", tmp_id);
#endif
}
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Adding rule %pp phase=%d id=\"%s\".", rule, rule->actionset->phase, (rule->actionset->id == NOT_SET_P
? "(none)" : rule->actionset->id));
#endif
/* Add rule to the recipe. */
if (msre_ruleset_rule_add(dcfg->ruleset, rule, rule->actionset->phase) < 0) {
return "Internal Error: Failed to add rule to the ruleset.";
}
/* Add an additional placeholder if this rule ID is on the list */
if ((rule->actionset->id != NULL) && apr_table_get(dcfg->tmp_rule_placeholders, rule->actionset->id)) {
msre_rule *phrule = apr_palloc(rule->ruleset->mp, sizeof(msre_rule));
if (phrule == NULL) {
return FATAL_ERROR;
}
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Adding placeholder %pp for rule %pp id=\"%s\".", phrule, rule, rule->actionset->id);
#endif
/* shallow copy of original rule with placeholder marked as target */
memcpy(phrule, rule, sizeof(msre_rule));
phrule->placeholder = RULE_PH_SKIPAFTER;
/* Add placeholder. */
if (msre_ruleset_rule_add(dcfg->ruleset, phrule, phrule->actionset->phase) < 0) {
return "Internal Error: Failed to add placeholder to the ruleset.";
}
/* No longer need to search for the ID */
apr_table_unset(dcfg->tmp_rule_placeholders, rule->actionset->id);
}
/* Update the unparsed rule */
rule->unparsed = msre_rule_generate_unparsed(dcfg->ruleset->mp, rule, NULL, NULL, NULL);
return NULL;
}
/**
*
*/
static const char *add_marker(cmd_parms *cmd, directory_config *dcfg,
const char *p1, const char *p2, const char *p3)
{
char *my_error_msg = NULL;
msre_rule *rule = NULL;
extern msc_engine *modsecurity;
int p;
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Rule: type=%d p1='%s' p2='%s' p3='%s'", RULE_TYPE_MARKER, p1, p2, p3);
#endif
/* Create a ruleset if one does not exist. */
if ((dcfg->ruleset == NULL)||(dcfg->ruleset == NOT_SET_P)) {
dcfg->ruleset = msre_ruleset_create(modsecurity->msre, cmd->pool);
if (dcfg->ruleset == NULL) return FATAL_ERROR;
}
/* Create the rule now. */
rule = msre_rule_create(dcfg->ruleset, RULE_TYPE_MARKER, cmd->directive->filename, cmd->directive->line_num, p1, p2, p3, &my_error_msg);
if (rule == NULL) {
return my_error_msg;
}
/* This is a marker */
rule->placeholder = RULE_PH_MARKER;
/* Add placeholder to each phase */
for (p = PHASE_FIRST; p <= PHASE_LAST; p++) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Adding marker %pp phase=%d id=\"%s\".", rule, p, (rule->actionset->id == NOT_SET_P
? "(none)" : rule->actionset->id));
#endif
if (msre_ruleset_rule_add(dcfg->ruleset, rule, p) < 0) {
return "Internal Error: Failed to add marker to the ruleset.";
}
}
/* No longer need to search for the ID */
if (dcfg->tmp_rule_placeholders != NULL) {
apr_table_unset(dcfg->tmp_rule_placeholders, rule->actionset->id);
}
return NULL;
}
/**
*
*/
static const char *update_rule_action(cmd_parms *cmd, directory_config *dcfg,
const char *p1, const char *p2, int offset)
{
char *my_error_msg = NULL;
msre_rule *rule = NULL;
msre_actionset *new_actionset = NULL;
msre_ruleset *ruleset = dcfg->ruleset;
extern msc_engine *modsecurity;
/* Get the ruleset if one exists */
if ((ruleset == NULL)||(ruleset == NOT_SET_P)) {
return NULL;
}
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Update rule id=\"%s\" with action \"%s\".", p1, p2);
#endif
/* Fetch the rule */
rule = msre_ruleset_fetch_rule(ruleset, p1, offset);
if (rule == NULL) {
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Update rule id=\"%s\" with action \"%s\" failed: Rule not found.", p1, p2);
#endif
return NULL;
}
/* Check the rule actionset */
/* ENH: Can this happen? */
if (rule->actionset == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Attempt to update action for rule \"%s\" failed: Rule does not have an actionset.", p1);
}
/* Create a new actionset */
new_actionset = msre_actionset_create(modsecurity->msre, p2, &my_error_msg);
if (new_actionset == NULL) return FATAL_ERROR;
if (my_error_msg != NULL) return my_error_msg;
/* Must NOT change an id */
if ((new_actionset->id != NOT_SET_P) && (rule->actionset->id != NULL) && (strcmp(rule->actionset->id, new_actionset->id) != 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Rule IDs cannot be updated via SecRuleUpdateActionById.");
}
/* Must NOT alter the phase */
if ((new_actionset->phase != NOT_SET) && (rule->actionset->phase != new_actionset->phase)) {
return apr_psprintf(cmd->pool, "ModSecurity: Rule phases cannot be updated via SecRuleUpdateActionById.");
}
#ifdef DEBUG_CONF
{
char *actions = msre_actionset_generate_action_string(ruleset->mp, rule->actionset);
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Update rule %pp id=\"%s\" old action: \"%s\"",
rule,
(rule->actionset->id == NOT_SET_P ? "(none)" : rule->actionset->id),
actions);
}
#endif
/* Merge new actions with the rule */
/* ENH: Will this leak the old actionset? */
rule->actionset = msre_actionset_merge(modsecurity->msre, rule->actionset,
new_actionset, 1);
msre_actionset_set_defaults(rule->actionset);
/* Update the unparsed rule */
rule->unparsed = msre_rule_generate_unparsed(ruleset->mp, rule, NULL, NULL, NULL);
#ifdef DEBUG_CONF
{
char *actions = msre_actionset_generate_action_string(ruleset->mp, rule->actionset);
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool,
"Update rule %pp id=\"%s\" new action: \"%s\"",
rule,
(rule->actionset->id == NOT_SET_P ? "(none)" : rule->actionset->id),
actions);
}
#endif
return NULL;
}
/* -- Configuration directives -- */
static const char *cmd_action(cmd_parms *cmd, void *_dcfg, const char *p1)
{
return add_rule(cmd, (directory_config *)_dcfg, RULE_TYPE_ACTION, SECACTION_TARGETS, SECACTION_ARGS, p1);
}
static const char *cmd_marker(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
const char *action = apr_pstrcat(dcfg->mp, SECMARKER_BASE_ACTIONS, p1, NULL);
return add_marker(cmd, (directory_config *)_dcfg, SECMARKER_TARGETS, SECMARKER_ARGS, action);
}
static const char *cmd_cookiev0_separator(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (strlen(p1) != 1) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid cookie v0 separator: %s", p1);
}
dcfg->cookiev0_separator = p1;
return NULL;
}
static const char *cmd_argument_separator(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (strlen(p1) != 1) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid argument separator: %s", p1);
}
dcfg->argument_separator = p1[0];
return NULL;
}
static const char *cmd_audit_engine(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = _dcfg;
if (strcasecmp(p1, "On") == 0) dcfg->auditlog_flag = AUDITLOG_ON;
else
if (strcasecmp(p1, "Off") == 0) dcfg->auditlog_flag = AUDITLOG_OFF;
else
if (strcasecmp(p1, "RelevantOnly") == 0) dcfg->auditlog_flag = AUDITLOG_RELEVANT;
else
return (const char *)apr_psprintf(cmd->pool,
"ModSecurity: Unrecognised parameter value for SecAuditEngine: %s", p1);
return NULL;
}
static const char *cmd_audit_log(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = _dcfg;
dcfg->auditlog_name = (char *)p1;
if (dcfg->auditlog_name[0] == '|') {
const char *pipe_name = dcfg->auditlog_name + 1;
piped_log *pipe_log;
pipe_log = ap_open_piped_log(cmd->pool, pipe_name);
if (pipe_log == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to open the audit log pipe: %s",
pipe_name);
}
dcfg->auditlog_fd = ap_piped_log_write_fd(pipe_log);
}
else {
const char *file_name = ap_server_root_relative(cmd->pool, dcfg->auditlog_name);
apr_status_t rc;
rc = apr_file_open(&dcfg->auditlog_fd, file_name,
APR_WRITE | APR_APPEND | APR_CREATE | APR_BINARY,
CREATEMODE, cmd->pool);
if (rc != APR_SUCCESS) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to open the audit log file: %s",
file_name);
}
}
return NULL;
}
static const char *cmd_audit_log2(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = _dcfg;
if (dcfg->auditlog_name == NOT_SET_P) {
return apr_psprintf(cmd->pool, "ModSecurity: Cannot configure a secondary audit log without a primary defined: %s", p1);
}
dcfg->auditlog2_name = (char *)p1;
if (dcfg->auditlog2_name[0] == '|') {
const char *pipe_name = ap_server_root_relative(cmd->pool, dcfg->auditlog2_name + 1);
piped_log *pipe_log;
pipe_log = ap_open_piped_log(cmd->pool, pipe_name);
if (pipe_log == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to open the secondary audit log pipe: %s",
pipe_name);
}
dcfg->auditlog2_fd = ap_piped_log_write_fd(pipe_log);
}
else {
const char *file_name = ap_server_root_relative(cmd->pool, dcfg->auditlog2_name);
apr_status_t rc;
rc = apr_file_open(&dcfg->auditlog2_fd, file_name,
APR_WRITE | APR_APPEND | APR_CREATE | APR_BINARY,
CREATEMODE, cmd->pool);
if (rc != APR_SUCCESS) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to open the secondary audit log file: %s",
file_name);
}
}
return NULL;
}
static const char *cmd_audit_log_parts(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = _dcfg;
if (is_valid_parts_specification((char *)p1) != 1) {
return apr_psprintf(cmd->pool, "Invalid parts specification for SecAuditLogParts: %s", p1);
}
dcfg->auditlog_parts = (char *)p1;
return NULL;
}
static const char *cmd_audit_log_relevant_status(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = _dcfg;
dcfg->auditlog_relevant_regex = msc_pregcomp(cmd->pool, p1, PCRE_DOTALL, NULL, NULL);
if (dcfg->auditlog_relevant_regex == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p1);
}
return NULL;
}
static const char *cmd_audit_log_type(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = _dcfg;
if (strcasecmp(p1, "Serial") == 0) dcfg->auditlog_type = AUDITLOG_SERIAL;
else
if (strcasecmp(p1, "Concurrent") == 0) dcfg->auditlog_type = AUDITLOG_CONCURRENT;
else
return (const char *)apr_psprintf(cmd->pool,
"ModSecurity: Unrecognised parameter value for SecAuditLogType: %s", p1);
return NULL;
}
static const char *cmd_audit_log_dirmode(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "default") == 0) {
dcfg->auditlog_dirperms = NOT_SET;
}
else {
long int mode = strtol(p1, NULL, 8); /* expects octal mode */
if ((mode == LONG_MAX)||(mode == LONG_MIN)||(mode <= 0)||(mode > 07777)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecAuditLogDirMode: %s", p1);
}
dcfg->auditlog_dirperms = mode2fileperms(mode);
}
return NULL;
}
static const char *cmd_audit_log_filemode(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "default") == 0) {
dcfg->auditlog_fileperms = NOT_SET;
}
else {
long int mode = strtol(p1, NULL, 8); /* expects octal mode */
if ((mode == LONG_MAX)||(mode == LONG_MIN)||(mode <= 0)||(mode > 07777)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecAuditLogFileMode: %s", p1);
}
dcfg->auditlog_fileperms = mode2fileperms(mode);
}
return NULL;
}
static const char *cmd_audit_log_storage_dir(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = _dcfg;
dcfg->auditlog_storage_dir = ap_server_root_relative(cmd->pool, p1);
return NULL;
}
static const char *cmd_cookie_format(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (strcmp(p1, "0") == 0) dcfg->cookie_format = COOKIES_V0;
else
if (strcmp(p1, "1") == 0) dcfg->cookie_format = COOKIES_V1;
else {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid cookie format: %s", p1);
}
return NULL;
}
static const char *cmd_chroot_dir(cmd_parms *cmd, void *_dcfg, const char *p1)
{
char cwd[1025] = "";
if (cmd->server->is_virtual) {
return "ModSecurity: SecChrootDir not allowed in VirtualHost";
}
chroot_dir = (char *)p1;
if (getcwd(cwd, 1024) == NULL) {
return "ModSecurity: Failed to get the current working directory";
}
if (chdir(chroot_dir) < 0) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to chdir to %s, errno=%d (%s)",
chroot_dir, errno, strerror(errno));
}
if (chdir(cwd) < 0) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to chdir to %s, errno=%d (%s)",
cwd, errno, strerror(errno));
}
return NULL;
}
/**
* Adds component signature to the list of signatures kept in configuration.
*/
static const char *cmd_component_signature(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
/* ENH Enforce "Name/VersionX.Y.Z (comment)" format. */
*(char **)apr_array_push(dcfg->component_signatures) = (char *)p1;
return NULL;
}
static const char *cmd_content_injection(cmd_parms *cmd, void *_dcfg, int flag)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
dcfg->content_injection_enabled = flag;
return NULL;
}
static const char *cmd_data_dir(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (cmd->server->is_virtual) {
return "ModSecurity: SecDataDir not allowed in VirtualHost.";
}
dcfg->data_dir = ap_server_root_relative(cmd->pool, p1);
return NULL;
}
static const char *cmd_debug_log(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
apr_status_t rc;
dcfg->debuglog_name = ap_server_root_relative(cmd->pool, p1);
rc = apr_file_open(&dcfg->debuglog_fd, dcfg->debuglog_name,
APR_WRITE | APR_APPEND | APR_CREATE | APR_BINARY,
CREATEMODE, cmd->pool);
if (rc != APR_SUCCESS) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to open debug log file: %s",
dcfg->debuglog_name);
}
return NULL;
}
/**
* \brief Add SecCollectionTimeout configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_collection_timeout(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
dcfg->col_timeout = atoi(p1);
/* max 30 days */
if ((dcfg->col_timeout >= 0)&&(dcfg->col_timeout <= 2592000)) return NULL;
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecCollectionTimeout: %s", p1);
}
static const char *cmd_debug_log_level(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
dcfg->debuglog_level = atoi(p1);
if ((dcfg->debuglog_level >= 0)&&(dcfg->debuglog_level <= 9)) return NULL;
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecDebugLogLevel: %s", p1);
}
static const char *cmd_default_action(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
extern msc_engine *modsecurity;
char *my_error_msg = NULL;
dcfg->tmp_default_actionset = msre_actionset_create(modsecurity->msre, p1, &my_error_msg);
if (dcfg->tmp_default_actionset == NULL) {
if (my_error_msg != NULL) return my_error_msg;
else return FATAL_ERROR;
}
/* Must specify a disruptive action. */
/* ENH: Remove this requirement? */
if (dcfg->tmp_default_actionset->intercept_action == NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: SecDefaultAction must specify a disruptive action.");
}
/* Must specify a phase. */
/* ENH: Remove this requirement? */
if (dcfg->tmp_default_actionset->phase == NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: SecDefaultAction must specify a phase.");
}
/* Must not use metadata actions. */
/* ENH: loop through to check for tags */
if ((dcfg->tmp_default_actionset->id != NOT_SET_P)
||(dcfg->tmp_default_actionset->rev != NOT_SET_P)
||(dcfg->tmp_default_actionset->version != NOT_SET_P)
||(dcfg->tmp_default_actionset->maturity != NOT_SET)
||(dcfg->tmp_default_actionset->accuracy != NOT_SET)
||(dcfg->tmp_default_actionset->msg != NOT_SET_P))
{
return apr_psprintf(cmd->pool, "ModSecurity: SecDefaultAction must not "
"contain any metadata actions (id, rev, msg, tag, severity, ver, accuracy, maturity, logdata).");
}
/* These are just a warning for now. */
if ((dcfg->tmp_default_actionset->severity != NOT_SET)
||(dcfg->tmp_default_actionset->logdata != NOT_SET_P))
{
ap_log_perror(APLOG_MARK,
APLOG_STARTUP|APLOG_WARNING|APLOG_NOERRNO, 0, cmd->pool,
"ModSecurity: WARNING Using \"severity\" or \"logdata\" in "
"SecDefaultAction is deprecated (%s:%d).",
cmd->directive->filename, cmd->directive->line_num);
}
if (apr_table_get(dcfg->tmp_default_actionset->actions, "t")) {
ap_log_perror(APLOG_MARK,
APLOG_STARTUP|APLOG_WARNING|APLOG_NOERRNO, 0, cmd->pool,
"ModSecurity: WARNING Using transformations in "
"SecDefaultAction is deprecated (%s:%d).",
cmd->directive->filename, cmd->directive->line_num);
}
/* Must not use chain. */
if (dcfg->tmp_default_actionset->is_chained != NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: SecDefaultAction must not "
"contain a chain action.");
}
/* Must not use skip. */
if (dcfg->tmp_default_actionset->skip_count != NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: SecDefaultAction must not "
"contain a skip action.");
}
/* Must not use skipAfter. */
if (dcfg->tmp_default_actionset->skip_after != NOT_SET_P) {
return apr_psprintf(cmd->pool, "ModSecurity: SecDefaultAction must not "
"contain a skipAfter action.");
}
return NULL;
}
static const char *cmd_disable_backend_compression(cmd_parms *cmd, void *_dcfg, int flag)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
dcfg->disable_backend_compression = flag;
return NULL;
}
static const char *cmd_guardian_log(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2)
{
extern char *guardianlog_name;
extern apr_file_t *guardianlog_fd;
extern char *guardianlog_condition;
if (cmd->server->is_virtual) {
return "ModSecurity: SecGuardianLog not allowed in VirtualHost";
}
if (p2 != NULL) {
if (strncmp(p2, "env=", 4) != 0) {
return "ModSecurity: Error in condition clause";
}
if ( (p2[4] == '\0') || ((p2[4] == '!')&&(p2[5] == '\0')) ) {
return "ModSecurity: Missing variable name";
}
guardianlog_condition = apr_pstrdup(cmd->pool, p2 + 4);
}
guardianlog_name = (char *)p1;
if (guardianlog_name[0] == '|') {
const char *pipe_name = ap_server_root_relative(cmd->pool, guardianlog_name + 1);
piped_log *pipe_log;
pipe_log = ap_open_piped_log(cmd->pool, pipe_name);
if (pipe_log == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to open the guardian log pipe: %s",
pipe_name);
}
guardianlog_fd = ap_piped_log_write_fd(pipe_log);
}
else {
const char *file_name = ap_server_root_relative(cmd->pool, guardianlog_name);
apr_status_t rc;
rc = apr_file_open(&guardianlog_fd, file_name,
APR_WRITE | APR_APPEND | APR_CREATE | APR_BINARY,
CREATEMODE, cmd->pool);
if (rc != APR_SUCCESS) {
return apr_psprintf(cmd->pool, "ModSecurity: Failed to open the guardian log file: %s",
file_name);
}
}
return NULL;
}
/**
* \brief Add SecStreamInBodyInspection configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_stream_inbody_inspection(cmd_parms *cmd, void *_dcfg, int flag)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
dcfg->stream_inbody_inspection = flag;
return NULL;
}
/**
* \brief Add SecStreamOutBodyInspection configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_stream_outbody_inspection(cmd_parms *cmd, void *_dcfg, int flag)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
dcfg->stream_outbody_inspection = flag;
return NULL;
}
/**
* \brief Add SecRulePerfTime configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_rule_perf_time(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
long int limit;
if (dcfg == NULL) return NULL;
limit = strtol(p1, NULL, 10);
if ((limit == LONG_MAX)||(limit == LONG_MIN)||(limit <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecRulePerfTime: %s", p1);
}
dcfg->max_rule_time = limit;
return NULL;
}
/**
* \brief Add SecReadStateLimit configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_conn_read_state_limit(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
long int limit;
if (dcfg == NULL) return NULL;
limit = strtol(p1, NULL, 10);
if ((limit == LONG_MAX)||(limit == LONG_MIN)||(limit <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecReadStateLimit: %s", p1);
}
conn_read_state_limit = limit;
return NULL;
}
/**
* \brief Add SecWriteStateLimit configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_conn_write_state_limit(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
long int limit;
if (dcfg == NULL) return NULL;
limit = strtol(p1, NULL, 10);
if ((limit == LONG_MAX)||(limit == LONG_MIN)||(limit <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecWriteStateLimit: %s", p1);
}
conn_write_state_limit = limit;
return NULL;
}
static const char *cmd_request_body_inmemory_limit(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
long int limit;
if (dcfg == NULL) return NULL;
limit = strtol(p1, NULL, 10);
if ((limit == LONG_MAX)||(limit == LONG_MIN)||(limit <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecRequestBodyInMemoryLimit: %s", p1);
}
dcfg->reqbody_inmemory_limit = limit;
return NULL;
}
static const char *cmd_request_body_limit(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
long int limit;
if (dcfg == NULL) return NULL;
limit = strtol(p1, NULL, 10);
if ((limit == LONG_MAX)||(limit == LONG_MIN)||(limit <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecRequestBodyLimit: %s", p1);
}
dcfg->reqbody_limit = limit;
return NULL;
}
static const char *cmd_request_body_no_files_limit(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
long int limit;
if (dcfg == NULL) return NULL;
limit = strtol(p1, NULL, 10);
if ((limit == LONG_MAX)||(limit == LONG_MIN)||(limit <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecRequestBodyNoFilesLimit: %s", p1);
}
dcfg->reqbody_no_files_limit = limit;
return NULL;
}
static const char *cmd_request_body_access(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0) dcfg->reqbody_access = 1;
else
if (strcasecmp(p1, "off") == 0) dcfg->reqbody_access = 0;
else
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecRequestBodyAccess: %s", p1);
return NULL;
}
/**
* \brief Add SecInterceptOnError configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On success
*/
static const char *cmd_request_intercept_on_error(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0) dcfg->reqintercept_oe = 1;
else
if (strcasecmp(p1, "off") == 0) dcfg->reqintercept_oe = 0;
else
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecInterceptOnError: %s", p1);
return NULL;
}
static const char *cmd_request_encoding(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
/* ENH Validate encoding */
dcfg->request_encoding = p1;
return NULL;
}
static const char *cmd_response_body_access(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0) dcfg->resbody_access = 1;
else
if (strcasecmp(p1, "off") == 0) dcfg->resbody_access = 0;
else
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecResponseBodyAccess: %s", p1);
return NULL;
}
static const char *cmd_response_body_limit(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
long int limit;
limit = strtol(p1, NULL, 10);
if ((limit == LONG_MAX)||(limit == LONG_MIN)||(limit <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecResponseBodyLimit: %s", p1);
}
if (limit > RESPONSE_BODY_HARD_LIMIT) {
return apr_psprintf(cmd->pool, "ModSecurity: Response size limit can not exceed the hard limit: %li", RESPONSE_BODY_HARD_LIMIT);
}
dcfg->of_limit = limit;
return NULL;
}
static const char *cmd_response_body_limit_action(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (dcfg->is_enabled == MODSEC_DETECTION_ONLY) {
dcfg->of_limit_action = RESPONSE_BODY_LIMIT_ACTION_PARTIAL;
return NULL;
}
if (strcasecmp(p1, "ProcessPartial") == 0) dcfg->of_limit_action = RESPONSE_BODY_LIMIT_ACTION_PARTIAL;
else
if (strcasecmp(p1, "Reject") == 0) dcfg->of_limit_action = RESPONSE_BODY_LIMIT_ACTION_REJECT;
else
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecResponseBodyLimitAction: %s", p1);
return NULL;
}
/**
* \brief Add SecRequestBodyLimitAction configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On success
*/
static const char *cmd_resquest_body_limit_action(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (dcfg->is_enabled == MODSEC_DETECTION_ONLY) {
dcfg->if_limit_action = REQUEST_BODY_LIMIT_ACTION_PARTIAL;
return NULL;
}
if (strcasecmp(p1, "ProcessPartial") == 0) dcfg->if_limit_action = REQUEST_BODY_LIMIT_ACTION_PARTIAL;
else
if (strcasecmp(p1, "Reject") == 0) dcfg->if_limit_action = REQUEST_BODY_LIMIT_ACTION_REJECT;
else
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecRequestBodyLimitAction: %s", p1);
return NULL;
}
static const char *cmd_response_body_mime_type(cmd_parms *cmd, void *_dcfg,
const char *_p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
char *p1 = apr_pstrdup(cmd->pool, _p1);
/* TODO check whether the parameter is a valid MIME type of "???" */
if ((dcfg->of_mime_types == NULL)||(dcfg->of_mime_types == NOT_SET_P)) {
dcfg->of_mime_types = apr_table_make(cmd->pool, 10);
}
strtolower_inplace((unsigned char *)p1);
apr_table_setn(dcfg->of_mime_types, p1, "1");
return NULL;
}
static const char *cmd_response_body_mime_types_clear(cmd_parms *cmd,
void *_dcfg)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
dcfg->of_mime_types_cleared = 1;
if ((dcfg->of_mime_types != NULL)&&(dcfg->of_mime_types != NOT_SET_P)) {
apr_table_clear(dcfg->of_mime_types);
}
return NULL;
}
/**
* \brief Add SecRuleUpdateTargetById
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
* \param p2 Pointer to configuration option
* \param p3 Pointer to configuration option
*
* \retval NULL On failure|Success
*/
static const char *cmd_rule_update_target_by_id(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2, const char *p3)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(rule_exception));
if (dcfg == NULL) return NULL;
if(p1 == NULL) {
return apr_psprintf(cmd->pool, "Updating target by ID with no ID");
}
re->type = RULE_EXCEPTION_REMOVE_ID;
/* TODO: Validate the range here, while we can still tell the user if it's invalid */
re->param = p1;
return msre_ruleset_rule_update_target_matching_exception(NULL, dcfg->ruleset, re, p2, p3);
}
/**
* \brief Add SecRuleUpdateTargetByTag configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option RULETAG
* \param p2 Pointer to configuration option TARGET
* \param p3 Pointer to configuration option REPLACED_TARGET
* \todo Finish documenting
*
* \retval NULL On success
* \retval apr_psprintf On failure
*
* \todo Figure out error checking
*/
static const char *cmd_rule_update_target_by_tag(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2, const char *p3)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(rule_exception));
if (dcfg == NULL) return NULL;
if(p1 == NULL) {
return apr_psprintf(cmd->pool, "Updating target by tag with no tag");
}
re->type = RULE_EXCEPTION_REMOVE_TAG;
re->param = p1;
re->param_data = msc_pregcomp(cmd->pool, p1, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p1);
}
return msre_ruleset_rule_update_target_matching_exception(NULL, dcfg->ruleset, re, p2, p3);
}
/**
* \brief Add SecRuleUpdateTargetByMsg configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option RULEMSG
* \param p2 Pointer to configuration option TARGET
* \param p3 Pointer to configuration option REPLACED_TARGET
* \todo Finish documenting
*
* \retval NULL On success
* \retval apr_psprintf On failure
*
* \todo Figure out error checking
*/
static const char *cmd_rule_update_target_by_msg(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2, const char *p3)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(rule_exception));
if (dcfg == NULL) return NULL;
if(p1 == NULL) {
return apr_psprintf(cmd->pool, "Updating target by message with no message");
}
re->type = RULE_EXCEPTION_REMOVE_MSG;
re->param = p1;
re->param_data = msc_pregcomp(cmd->pool, p1, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p1);
}
return msre_ruleset_rule_update_target_matching_exception(NULL, dcfg->ruleset, re, p2, p3);
}
static const char *cmd_rule(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2, const char *p3)
{
return add_rule(cmd, (directory_config *)_dcfg, RULE_TYPE_NORMAL, p1, p2, p3);
}
static const char *cmd_rule_engine(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0) dcfg->is_enabled = MODSEC_ENABLED;
else
if (strcasecmp(p1, "off") == 0) dcfg->is_enabled = MODSEC_DISABLED;
else
if (strcasecmp(p1, "detectiononly") == 0) {
dcfg->is_enabled = MODSEC_DETECTION_ONLY;
dcfg->of_limit_action = RESPONSE_BODY_LIMIT_ACTION_PARTIAL;
dcfg->if_limit_action = REQUEST_BODY_LIMIT_ACTION_PARTIAL;
} else
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecRuleEngine: %s", p1);
return NULL;
}
static const char *cmd_rule_inheritance(cmd_parms *cmd, void *_dcfg, int flag)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
dcfg->rule_inheritance = flag;
return NULL;
}
static const char *cmd_rule_script(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2)
{
#if defined(WITH_LUA)
const char *filename = resolve_relative_path(cmd->pool, cmd->directive->filename, p1);
return add_rule(cmd, (directory_config *)_dcfg, RULE_TYPE_LUA, filename, p2, NULL);
#else
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool, "Ignoring SecRuleScript \"%s\" directive (%s:%d): No Lua scripting support.", p1, cmd->directive->filename, cmd->directive->line_num);
return NULL;
#endif
}
static const char *cmd_rule_remove_by_id(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(rule_exception));
if (dcfg == NULL) return NULL;
re->type = RULE_EXCEPTION_REMOVE_ID;
re->param = p1;
*(rule_exception **)apr_array_push(dcfg->rule_exceptions) = re;
/* Remove the corresponding rules from the context straight away. */
msre_ruleset_rule_remove_with_exception(dcfg->ruleset, re);
return NULL;
}
/**
* \brief Add SecRuleRemoveByTag configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On success
*/
static const char *cmd_rule_remove_by_tag(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(rule_exception));
if (dcfg == NULL) return NULL;
re->type = RULE_EXCEPTION_REMOVE_TAG;
re->param = p1;
re->param_data = msc_pregcomp(cmd->pool, p1, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p1);
}
*(rule_exception **)apr_array_push(dcfg->rule_exceptions) = re;
/* Remove the corresponding rules from the context straight away. */
msre_ruleset_rule_remove_with_exception(dcfg->ruleset, re);
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool, "Added exception %pp (%d %s) to dcfg %pp.", re, re->type, re->param, dcfg);
#endif
return NULL;
}
static const char *cmd_rule_remove_by_msg(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(rule_exception));
if (dcfg == NULL) return NULL;
re->type = RULE_EXCEPTION_REMOVE_MSG;
re->param = p1;
re->param_data = msc_pregcomp(cmd->pool, p1, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p1);
}
*(rule_exception **)apr_array_push(dcfg->rule_exceptions) = re;
/* Remove the corresponding rules from the context straight away. */
msre_ruleset_rule_remove_with_exception(dcfg->ruleset, re);
#ifdef DEBUG_CONF
ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_NOERRNO, 0, cmd->pool, "Added exception %pp (%d %s) to dcfg %pp.", re, re->type, re->param, dcfg);
#endif
return NULL;
}
static const char *cmd_rule_update_action_by_id(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2)
{
int offset = 0, rule_id = atoi(p1);
char *opt = strchr(p1,':');
char *savedptr = NULL;
char *param = apr_pstrdup(cmd->pool, p1);
if ((rule_id == LONG_MAX)||(rule_id == LONG_MIN)||(rule_id <= 0)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for ID for update action: %s", p1);
}
if(opt != NULL) {
opt++;
offset = atoi(opt);
opt = apr_strtok(param,":", &savedptr);
return update_rule_action(cmd, (directory_config *)_dcfg, (const char *)opt, p2, offset);
}
return update_rule_action(cmd, (directory_config *)_dcfg, p1, p2, offset);
}
static const char *cmd_server_signature(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
if (cmd->server->is_virtual) {
return "ModSecurity: SecServerSignature not allowed in VirtualHost";
}
new_server_signature = (char *)p1;
return NULL;
}
static const char *cmd_tmp_dir(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "none") == 0) dcfg->tmp_dir = NULL;
else dcfg->tmp_dir = ap_server_root_relative(cmd->pool, p1);
return NULL;
}
static const char *cmd_upload_dir(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "none") == 0) dcfg->upload_dir = NULL;
else dcfg->upload_dir = ap_server_root_relative(cmd->pool, p1);
return NULL;
}
static const char *cmd_upload_file_limit(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "default") == 0) {
dcfg->upload_file_limit = NOT_SET;
}
else {
dcfg->upload_file_limit = atoi(p1);
}
return NULL;
}
static const char *cmd_upload_filemode(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "default") == 0) {
dcfg->upload_filemode = NOT_SET;
}
else {
long int mode = strtol(p1, NULL, 8); /* expects octal mode */
if ((mode == LONG_MAX)||(mode == LONG_MIN)||(mode <= 0)||(mode > 07777)) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecUploadFileMode: %s", p1);
}
dcfg->upload_filemode = (int)mode;
}
return NULL;
}
static const char *cmd_upload_keep_files(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0) {
dcfg->upload_keep_files = KEEP_FILES_ON;
} else
if (strcasecmp(p1, "off") == 0) {
dcfg->upload_keep_files = KEEP_FILES_OFF;
} else
if (strcasecmp(p1, "relevantonly") == 0) {
dcfg->upload_keep_files = KEEP_FILES_RELEVANT_ONLY;
} else {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid setting for SecUploadKeepFiles: %s",
p1);
}
return NULL;
}
static const char *cmd_web_app_id(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
/* ENH enforce format (letters, digits, ., _, -) */
dcfg->webappid = p1;
return NULL;
}
static const char *cmd_sensor_id(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
/* ENH enforce format (letters, digits, ., _, -) */
dcfg->sensor_id = p1;
return NULL;
}
/**
* \brief Add SecXmlExternalEntity configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_xml_external_entity(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0) {
dcfg->xml_external_entity = 1;
}
else if (strcasecmp(p1, "off") == 0) {
dcfg->xml_external_entity = 0;
}
else return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecXmlExternalEntity: %s", p1);
return NULL;
}
/**
* \brief Add SecHashEngine configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_hash_engine(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0) {
dcfg->hash_is_enabled = HASH_ENABLED;
dcfg->hash_enforcement = HASH_ENABLED;
}
else if (strcasecmp(p1, "off") == 0) {
dcfg->hash_is_enabled = HASH_DISABLED;
dcfg->hash_enforcement = HASH_DISABLED;
}
else return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SexHashEngine: %s", p1);
return NULL;
}
/**
* \brief Add SecHashPram configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On success
*/
static const char *cmd_hash_param(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (p1 == NULL) return NULL;
dcfg->crypto_param_name = p1;
return NULL;
}
/**
* \brief Add SecHashKey configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param _p1 Pointer to configuration option
* \param _p2 Pointer to configuration option
*
* \retval NULL On success
*/
static const char *cmd_hash_key(cmd_parms *cmd, void *_dcfg, const char *_p1, const char *_p2)
{
directory_config *dcfg = (directory_config *)_dcfg;
char *p1 = NULL;
if (dcfg == NULL) return NULL;
if (_p1 == NULL) return NULL;
if (strcasecmp(_p1, "Rand") == 0) {
p1 = apr_pstrdup(cmd->pool, getkey(cmd->pool));
dcfg->crypto_key = p1;
dcfg->crypto_key_len = strlen(dcfg->crypto_key);
} else {
p1 = apr_pstrdup(cmd->pool, _p1);
dcfg->crypto_key = p1;
dcfg->crypto_key_len = strlen(p1);
}
if(_p2 == NULL) {
return NULL;
} else {
if (strcasecmp(_p2, "KeyOnly") == 0)
dcfg->crypto_key_add = HASH_KEYONLY;
else if (strcasecmp(_p2, "SessionID") == 0)
dcfg->crypto_key_add = HASH_SESSIONID;
else if (strcasecmp(_p2, "RemoteIP") == 0)
dcfg->crypto_key_add = HASH_REMOTEIP;
}
return NULL;
}
/**
* \brief Add SecHashMethodPm configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
* \param p2 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_hash_method_pm(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(hash_method));
const char *_p2 = apr_pstrdup(cmd->pool, p2);
ACMP *p = NULL;
const char *phrase = NULL;
const char *next = NULL;
if (dcfg == NULL) return NULL;
p = acmp_create(0, cmd->pool);
if (p == NULL) return NULL;
if(phrase == NULL)
phrase = apr_pstrdup(cmd->pool, _p2);
for (;;) {
while((apr_isspace(*phrase) != 0) && (*phrase != '\0')) phrase++;
if (*phrase == '\0') break;
next = phrase;
while((apr_isspace(*next) == 0) && (*next != 0)) next++;
acmp_add_pattern(p, phrase, NULL, NULL, next - phrase);
phrase = next;
}
acmp_prepare(p);
if (strcasecmp(p1, "HashHref") == 0) {
re->type = HASH_URL_HREF_HASH_PM;
re->param = _p2;
re->param_data = (void *)p;
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid pattern: %s", p2);
}
dcfg->crypto_hash_href_pm = 1;
}
else if (strcasecmp(p1, "HashFormAction") == 0) {
re->type = HASH_URL_FACTION_HASH_PM;
re->param = _p2;
re->param_data = (void *)p;
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid pattern: %s", p2);
}
dcfg->crypto_hash_faction_pm = 1;
}
else if (strcasecmp(p1, "HashLocation") == 0) {
re->type = HASH_URL_LOCATION_HASH_PM;
re->param = _p2;
re->param_data = (void *)p;
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid pattern: %s", p2);
}
dcfg->crypto_hash_location_pm = 1;
}
else if (strcasecmp(p1, "HashIframeSrc") == 0) {
re->type = HASH_URL_IFRAMESRC_HASH_PM;
re->param = _p2;
re->param_data = (void *)p;
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid pattern: %s", p2);
}
dcfg->crypto_hash_iframesrc_pm = 1;
}
else if (strcasecmp(p1, "HashFrameSrc") == 0) {
re->type = HASH_URL_FRAMESRC_HASH_PM;
re->param = _p2;
re->param_data = (void *)p;
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid pattern: %s", p2);
}
dcfg->crypto_hash_framesrc_pm = 1;
}
*(hash_method **)apr_array_push(dcfg->hash_method) = re;
return NULL;
}
/**
* \brief Add SecHashMethodRx configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
* \param p2 Pointer to configuration option
*
* \retval NULL On failure
* \retval apr_psprintf On Success
*/
static const char *cmd_hash_method_rx(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2)
{
directory_config *dcfg = (directory_config *)_dcfg;
rule_exception *re = apr_pcalloc(cmd->pool, sizeof(hash_method));
const char *_p2 = apr_pstrdup(cmd->pool, p2);
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "HashHref") == 0) {
re->type = HASH_URL_HREF_HASH_RX;
re->param = _p2;
re->param_data = msc_pregcomp(cmd->pool, p2, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p2);
}
dcfg->crypto_hash_href_rx = 1;
}
else if (strcasecmp(p1, "HashFormAction") == 0) {
re->type = HASH_URL_FACTION_HASH_RX;
re->param = _p2;
re->param_data = msc_pregcomp(cmd->pool, p2, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p2);
}
dcfg->crypto_hash_faction_rx = 1;
}
else if (strcasecmp(p1, "HashLocation") == 0) {
re->type = HASH_URL_LOCATION_HASH_RX;
re->param = _p2;
re->param_data = msc_pregcomp(cmd->pool, p2, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p2);
}
dcfg->crypto_hash_location_rx = 1;
}
else if (strcasecmp(p1, "HashIframeSrc") == 0) {
re->type = HASH_URL_IFRAMESRC_HASH_RX;
re->param = _p2;
re->param_data = msc_pregcomp(cmd->pool, p2, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p2);
}
dcfg->crypto_hash_iframesrc_rx = 1;
}
else if (strcasecmp(p1, "HashFrameSrc") == 0) {
re->type = HASH_URL_FRAMESRC_HASH_RX;
re->param = _p2;
re->param_data = msc_pregcomp(cmd->pool, p2, 0, NULL, NULL);
if (re->param_data == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid regular expression: %s", p2);
}
dcfg->crypto_hash_framesrc_rx = 1;
}
*(hash_method **)apr_array_push(dcfg->hash_method) = re;
return NULL;
}
/**
* \brief Add SecHttpBlKey configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On success
*/
static const char *cmd_httpBl_key(cmd_parms *cmd, void *_dcfg, const char *p1)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (p1 == NULL) return NULL;
dcfg->httpBlkey = p1;
return NULL;
}
/* PCRE Limits */
static const char *cmd_pcre_match_limit(cmd_parms *cmd,
void *_dcfg, const char *p1)
{
long val;
if (cmd->server->is_virtual) {
return "ModSecurity: SecPcreMatchLimit not allowed in VirtualHost";
}
val = atol(p1);
if (val <= 0) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid setting for "
"SecPcreMatchLimit: %s", p1);
}
msc_pcre_match_limit = (unsigned long int)val;
return NULL;
}
static const char *cmd_pcre_match_limit_recursion(cmd_parms *cmd,
void *_dcfg, const char *p1)
{
long val;
if (cmd->server->is_virtual) {
return "ModSecurity: SecPcreMatchLimitRecursion not allowed in VirtualHost";
}
val = atol(p1);
if (val <= 0) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid setting for "
"SecPcreMatchLimitRecursion: %s", p1);
}
msc_pcre_match_limit_recursion = (unsigned long int)val;
return NULL;
}
/* -- Geo Lookup configuration -- */
static const char *cmd_geo_lookup_db(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
const char *filename = resolve_relative_path(cmd->pool, cmd->directive->filename, p1);
char *error_msg;
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (geo_init(dcfg, filename, &error_msg) <= 0) {
return error_msg;
}
return NULL;
}
/**
* \brief Add SecUnicodeCodePage configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On success
*/
static const char *cmd_unicode_codepage(cmd_parms *cmd,
void *_dcfg, const char *p1)
{
long val;
val = atol(p1);
if (val <= 0) {
return apr_psprintf(cmd->pool, "ModSecurity: Invalid setting for "
"SecUnicodeCodePage: %s", p1);
}
unicode_codepage = (unsigned long int)val;
return NULL;
}
/**
* \brief Add SecUnicodeMapFile configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On success
*/
static const char *cmd_unicode_map(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
const char *filename = resolve_relative_path(cmd->pool, cmd->directive->filename, p1);
char *error_msg;
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (unicode_map_init(dcfg, filename, &error_msg) <= 0) {
return error_msg;
}
return NULL;
}
/**
* \brief Add SecGsbLookupDb configuration option
*
* \param cmd Pointer to configuration data
* \param _dcfg Pointer to directory configuration
* \param p1 Pointer to configuration option
*
* \retval NULL On success
*/
static const char *cmd_gsb_lookup_db(cmd_parms *cmd, void *_dcfg,
const char *p1)
{
const char *filename = resolve_relative_path(cmd->pool, cmd->directive->filename, p1);
char *error_msg;
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (gsb_db_init(dcfg, filename, &error_msg) <= 0) {
return error_msg;
}
return NULL;
}
/* -- Cache -- */
static const char *cmd_cache_transformations(cmd_parms *cmd, void *_dcfg,
const char *p1, const char *p2)
{
directory_config *dcfg = (directory_config *)_dcfg;
if (dcfg == NULL) return NULL;
if (strcasecmp(p1, "on") == 0)
dcfg->cache_trans = MODSEC_CACHE_ENABLED;
else if (strcasecmp(p1, "off") == 0)
dcfg->cache_trans = MODSEC_CACHE_DISABLED;
else
return apr_psprintf(cmd->pool, "ModSecurity: Invalid value for SecCacheTransformations: %s", p1);
/* Process options */
if (p2 != NULL) {
apr_table_t *vartable = apr_table_make(cmd->pool, 4);
apr_status_t rc;
char *error_msg = NULL;
const char *charval = NULL;
apr_int64_t intval = 0;
if (vartable == NULL) {
return apr_psprintf(cmd->pool, "ModSecurity: Unable to process options for SecCacheTransformations");
}
rc = msre_parse_generic(cmd->pool, p2, vartable, &error_msg);
if (rc < 0) {
return apr_psprintf(cmd->pool, "ModSecurity: Unable to parse options for SecCacheTransformations: %s", error_msg);
}
/* incremental */
charval = apr_table_get(vartable, "incremental");
if (charval != NULL) {
if (strcasecmp(charval, "on") == 0)
dcfg->cache_trans_incremental = 1;
else if (strcasecmp(charval, "off") == 0)
dcfg->cache_trans_incremental = 0;
else
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations invalid incremental value: %s", charval);
}
/* minlen */
charval = apr_table_get(vartable, "minlen");
if (charval != NULL) {
intval = apr_atoi64(charval);
if (errno == ERANGE) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations minlen out of range: %s", charval);
}
if (intval < 0) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations minlen must be positive: %s", charval);
}
/* The NOT_SET indicator is -1, a signed long, and therfore
* we cannot be >= the unsigned value of NOT_SET.
*/
if ((unsigned long)intval >= (unsigned long)NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations minlen must be less than: %lu", (unsigned long)NOT_SET);
}
dcfg->cache_trans_min = (apr_size_t)intval;
}
/* maxlen */
charval = apr_table_get(vartable, "maxlen");
if (charval != NULL) {
intval = apr_atoi64(charval);
if (errno == ERANGE) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations maxlen out of range: %s", charval);
}
if (intval < 0) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations maxlen must be positive: %s", charval);
}
/* The NOT_SET indicator is -1, a signed long, and therfore
* we cannot be >= the unsigned value of NOT_SET.
*/
if ((unsigned long)intval >= (unsigned long)NOT_SET) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations maxlen must be less than: %lu", (unsigned long)NOT_SET);
}
if ((intval != 0) && ((apr_size_t)intval < dcfg->cache_trans_min)) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations maxlen must not be less than minlen: %lu < %" APR_SIZE_T_FMT, (unsigned long)intval, dcfg->cache_trans_min);
}
dcfg->cache_trans_max = (apr_size_t)intval;
}
/* maxitems */
charval = apr_table_get(vartable, "maxitems");
if (charval != NULL) {
intval = apr_atoi64(charval);
if (errno == ERANGE) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations maxitems out of range: %s", charval);
}
if (intval < 0) {
return apr_psprintf(cmd->pool, "ModSecurity: SecCacheTransformations maxitems must be positive: %s", charval);
}
dcfg->cache_trans_maxitems = (apr_size_t)intval;
}
}
return NULL;
}
/* -- Configuration directives definitions -- */
#define CMD_SCOPE_MAIN (RSRC_CONF)
#define CMD_SCOPE_ANY (RSRC_CONF | ACCESS_CONF)
#if defined(HTACCESS_CONFIG)
#define CMD_SCOPE_HTACCESS (OR_OPTIONS)
#endif
const command_rec module_directives[] = {
#ifdef HTACCESS_CONFIG
AP_INIT_TAKE1 (
"SecAction",
cmd_action,
NULL,
CMD_SCOPE_HTACCESS,
"an action list"
),
#else
AP_INIT_TAKE1 (
"SecAction",
cmd_action,
NULL,
CMD_SCOPE_ANY,
"an action list"
),
#endif
AP_INIT_TAKE1 (
"SecArgumentSeparator",
cmd_argument_separator,
NULL,
CMD_SCOPE_ANY,
"character that will be used as separator when parsing application/x-www-form-urlencoded content."
),
AP_INIT_TAKE1 (
"SecCookiev0Separator",
cmd_cookiev0_separator,
NULL,
CMD_SCOPE_ANY,
"character that will be used as separator when parsing cookie v0 content."
),
AP_INIT_TAKE1 (
"SecAuditEngine",
cmd_audit_engine,
NULL,
CMD_SCOPE_ANY,
"On, Off or RelevantOnly to determine the level of audit logging"
),
AP_INIT_TAKE1 (
"SecAuditLog",
cmd_audit_log,
NULL,
CMD_SCOPE_ANY,
"filename of the primary audit log file"
),
AP_INIT_TAKE1 (
"SecAuditLog2",
cmd_audit_log2,
NULL,
CMD_SCOPE_ANY,
"filename of the secondary audit log file"
),
AP_INIT_TAKE1 (
"SecAuditLogParts",
cmd_audit_log_parts,
NULL,
CMD_SCOPE_ANY,
"list of audit log parts that go into the log."
),
AP_INIT_TAKE1 (
"SecAuditLogRelevantStatus",
cmd_audit_log_relevant_status,
NULL,
CMD_SCOPE_ANY,
"regular expression that will be used to determine if the response status is relevant for audit logging"
),
AP_INIT_TAKE1 (
"SecAuditLogType",
cmd_audit_log_type,
NULL,
CMD_SCOPE_ANY,
"whether to use the old audit log format (Serial) or new (Concurrent)"
),
AP_INIT_TAKE1 (
"SecAuditLogStorageDir",
cmd_audit_log_storage_dir,
NULL,
CMD_SCOPE_ANY,
"path to the audit log storage area; absolute, or relative to the root of the server"
),
AP_INIT_TAKE1 (
"SecAuditLogDirMode",
cmd_audit_log_dirmode,
NULL,
CMD_SCOPE_ANY,
"octal permissions mode for concurrent audit log directories"
),
AP_INIT_TAKE1 (
"SecAuditLogFileMode",
cmd_audit_log_filemode,
NULL,
CMD_SCOPE_ANY,
"octal permissions mode for concurrent audit log files"
),
AP_INIT_TAKE12 (
"SecCacheTransformations",
cmd_cache_transformations,
NULL,
CMD_SCOPE_ANY,
"whether or not to cache transformations. Defaults to true."
),
AP_INIT_TAKE1 (
"SecChrootDir",
cmd_chroot_dir,
NULL,
CMD_SCOPE_MAIN,
"path of the directory to which server will be chrooted"
),
AP_INIT_TAKE1 (
"SecComponentSignature",
cmd_component_signature,
NULL,
CMD_SCOPE_MAIN,
"component signature to add to ModSecurity signature."
),
AP_INIT_FLAG (
"SecContentInjection",
cmd_content_injection,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_FLAG (
"SecStreamOutBodyInspection",
cmd_stream_outbody_inspection,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_FLAG (
"SecStreamInBodyInspection",
cmd_stream_inbody_inspection,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE1 (
"SecCookieFormat",
cmd_cookie_format,
NULL,
CMD_SCOPE_ANY,
"version of the Cookie specification to use for parsing. Possible values are 0 and 1."
),
AP_INIT_TAKE1 (
"SecDataDir",
cmd_data_dir,
NULL,
CMD_SCOPE_MAIN,
"path to the persistent data storage area" // TODO
),
AP_INIT_TAKE1 (
"SecDebugLog",
cmd_debug_log,
NULL,
CMD_SCOPE_ANY,
"path to the debug log file"
),
AP_INIT_TAKE1 (
"SecDebugLogLevel",
cmd_debug_log_level,
NULL,
CMD_SCOPE_ANY,
"debug log level, which controls the verbosity of logging."
" Use values from 0 (no logging) to 9 (a *lot* of logging)."
),
AP_INIT_TAKE1 (
"SecCollectionTimeout",
cmd_collection_timeout,
NULL,
CMD_SCOPE_ANY,
"set default collections timeout. default it 3600"
),
AP_INIT_TAKE1 (
"SecDefaultAction",
cmd_default_action,
NULL,
CMD_SCOPE_ANY,
"default action list"
),
AP_INIT_FLAG (
"SecDisableBackendCompression",
cmd_disable_backend_compression,
NULL,
CMD_SCOPE_ANY,
"When set to On, removes the compression headers from the backend requests."
),
AP_INIT_TAKE1 (
"SecGsbLookupDB",
cmd_gsb_lookup_db,
NULL,
RSRC_CONF,
"database google safe browsing"
),
AP_INIT_TAKE1 (
"SecUnicodeCodePage",
cmd_unicode_codepage,
NULL,
CMD_SCOPE_MAIN,
"Unicode CodePage"
),
AP_INIT_TAKE1 (
"SecUnicodeMapFile",
cmd_unicode_map,
NULL,
CMD_SCOPE_MAIN,
"Unicode Map file"
),
AP_INIT_TAKE1 (
"SecGeoLookupDB",
cmd_geo_lookup_db,
NULL,
RSRC_CONF,
"database for geographical lookups module."
),
AP_INIT_TAKE12 (
"SecGuardianLog",
cmd_guardian_log,
NULL,
CMD_SCOPE_MAIN,
"The filename of the filter debugging log file"
),
AP_INIT_TAKE1 (
"SecMarker",
cmd_marker,
NULL,
CMD_SCOPE_ANY,
"marker for a skipAfter target"
),
AP_INIT_TAKE1 (
"SecPcreMatchLimit",
cmd_pcre_match_limit,
NULL,
CMD_SCOPE_MAIN,
"PCRE match limit"
),
AP_INIT_TAKE1 (
"SecPcreMatchLimitRecursion",
cmd_pcre_match_limit_recursion,
NULL,
CMD_SCOPE_MAIN,
"PCRE match limit recursion"
),
AP_INIT_TAKE1 (
"SecRequestBodyAccess",
cmd_request_body_access,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE1 (
"SecInterceptOnError",
cmd_request_intercept_on_error,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE1 (
"SecRulePerfTime",
cmd_rule_perf_time,
NULL,
CMD_SCOPE_ANY,
"Threshold to log slow rules in usecs."
),
AP_INIT_TAKE1 (
"SecReadStateLimit",
cmd_conn_read_state_limit,
NULL,
CMD_SCOPE_ANY,
"maximum number of threads in READ_BUSY state per ip address"
),
AP_INIT_TAKE1 (
"SecWriteStateLimit",
cmd_conn_write_state_limit,
NULL,
CMD_SCOPE_ANY,
"maximum number of threads in WRITE_BUSY state per ip address"
),
AP_INIT_TAKE1 (
"SecRequestBodyInMemoryLimit",
cmd_request_body_inmemory_limit,
NULL,
CMD_SCOPE_ANY,
"maximum request body size that will be placed in memory (except for POST urlencoded requests)."
),
AP_INIT_TAKE1 (
"SecRequestBodyLimit",
cmd_request_body_limit,
NULL,
CMD_SCOPE_ANY,
"maximum request body size ModSecurity will accept."
),
AP_INIT_TAKE1 (
"SecRequestBodyNoFilesLimit",
cmd_request_body_no_files_limit,
NULL,
CMD_SCOPE_ANY,
"maximum request body size ModSecurity will accept, but excluding the size of uploaded files."
),
AP_INIT_TAKE1 (
"SecRequestEncoding",
cmd_request_encoding,
NULL,
CMD_SCOPE_ANY,
"character encoding used in request."
),
AP_INIT_TAKE1 (
"SecResponseBodyAccess",
cmd_response_body_access,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE1 (
"SecResponseBodyLimit",
cmd_response_body_limit,
NULL,
CMD_SCOPE_ANY,
"byte limit for response body"
),
AP_INIT_TAKE1 (
"SecResponseBodyLimitAction",
cmd_response_body_limit_action,
NULL,
CMD_SCOPE_ANY,
"what happens when the response body limit is reached"
),
AP_INIT_TAKE1 (
"SecRequestBodyLimitAction",
cmd_resquest_body_limit_action,
NULL,
CMD_SCOPE_ANY,
"what happens when the request body limit is reached"
),
AP_INIT_ITERATE (
"SecResponseBodyMimeType",
cmd_response_body_mime_type,
NULL,
CMD_SCOPE_ANY,
"adds given MIME types to the list of types that will be buffered on output"
),
AP_INIT_NO_ARGS (
"SecResponseBodyMimeTypesClear",
cmd_response_body_mime_types_clear,
NULL,
CMD_SCOPE_ANY,
"clears the list of MIME types that will be buffered on output"
),
#ifdef HTACCESS_CONFIG
AP_INIT_TAKE23 (
"SecRule",
cmd_rule,
NULL,
CMD_SCOPE_HTACCESS,
"rule target, operator and optional action list"
),
#else
AP_INIT_TAKE23 (
"SecRule",
cmd_rule,
NULL,
CMD_SCOPE_ANY,
"rule target, operator and optional action list"
),
#endif
AP_INIT_TAKE1 (
"SecRuleEngine",
cmd_rule_engine,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE1 (
"SecXmlExternalEntity",
cmd_xml_external_entity,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_FLAG (
"SecRuleInheritance",
cmd_rule_inheritance,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE12 (
"SecRuleScript",
cmd_rule_script,
NULL,
CMD_SCOPE_ANY,
"rule script and optional actionlist"
),
#ifdef HTACCESS_CONFIG
AP_INIT_ITERATE (
"SecRuleRemoveById",
cmd_rule_remove_by_id,
NULL,
CMD_SCOPE_HTACCESS,
"rule ID for removal"
),
AP_INIT_ITERATE (
"SecRuleRemoveByTag",
cmd_rule_remove_by_tag,
NULL,
CMD_SCOPE_HTACCESS,
"rule tag for removal"
),
AP_INIT_ITERATE (
"SecRuleRemoveByMsg",
cmd_rule_remove_by_msg,
NULL,
CMD_SCOPE_HTACCESS,
"rule message for removal"
),
#else
AP_INIT_ITERATE (
"SecRuleRemoveById",
cmd_rule_remove_by_id,
NULL,
CMD_SCOPE_ANY,
"rule ID for removal"
),
AP_INIT_ITERATE (
"SecRuleRemoveByTag",
cmd_rule_remove_by_tag,
NULL,
CMD_SCOPE_ANY,
"rule tag for removal"
),
AP_INIT_ITERATE (
"SecRuleRemoveByMsg",
cmd_rule_remove_by_msg,
NULL,
CMD_SCOPE_ANY,
"rule message for removal"
),
#endif
AP_INIT_TAKE2 (
"SecHashMethodPm",
cmd_hash_method_pm,
NULL,
CMD_SCOPE_ANY,
"Hash method and pattern"
),
AP_INIT_TAKE2 (
"SecHashMethodRx",
cmd_hash_method_rx,
NULL,
CMD_SCOPE_ANY,
"Hash method and regex"
),
#ifdef HTACCESS_CONFIG
AP_INIT_TAKE2 (
"SecRuleUpdateActionById",
cmd_rule_update_action_by_id,
NULL,
CMD_SCOPE_HTACCESS,
"updated action list"
),
AP_INIT_TAKE23 (
"SecRuleUpdateTargetById",
cmd_rule_update_target_by_id,
NULL,
CMD_SCOPE_HTACCESS,
"updated target list"
),
AP_INIT_TAKE23 (
"SecRuleUpdateTargetByTag",
cmd_rule_update_target_by_tag,
NULL,
CMD_SCOPE_HTACCESS,
"rule tag pattern and updated target list"
),
AP_INIT_TAKE23 (
"SecRuleUpdateTargetByMsg",
cmd_rule_update_target_by_msg,
NULL,
CMD_SCOPE_HTACCESS,
"rule message pattern and updated target list"
),
#else
AP_INIT_TAKE2 (
"SecRuleUpdateActionById",
cmd_rule_update_action_by_id,
NULL,
CMD_SCOPE_ANY,
"updated action list"
),
AP_INIT_TAKE23 (
"SecRuleUpdateTargetById",
cmd_rule_update_target_by_id,
NULL,
CMD_SCOPE_ANY,
"updated target list"
),
AP_INIT_TAKE23 (
"SecRuleUpdateTargetByTag",
cmd_rule_update_target_by_tag,
NULL,
CMD_SCOPE_ANY,
"rule tag pattern and updated target list"
),
AP_INIT_TAKE23 (
"SecRuleUpdateTargetByMsg",
cmd_rule_update_target_by_msg,
NULL,
CMD_SCOPE_ANY,
"rule message pattern and updated target list"
),
#endif
AP_INIT_TAKE1 (
"SecServerSignature",
cmd_server_signature,
NULL,
CMD_SCOPE_MAIN,
"the new signature of the server"
),
AP_INIT_TAKE1 (
"SecTmpDir",
cmd_tmp_dir,
NULL,
CMD_SCOPE_ANY,
"path to the temporary storage area"
),
AP_INIT_TAKE1 (
"SecUploadDir",
cmd_upload_dir,
NULL,
CMD_SCOPE_ANY,
"path to the file upload area"
),
AP_INIT_TAKE1 (
"SecUploadFileLimit",
cmd_upload_file_limit,
NULL,
CMD_SCOPE_ANY,
"limit the number of uploaded files processed"
),
AP_INIT_TAKE1 (
"SecUploadFileMode",
cmd_upload_filemode,
NULL,
CMD_SCOPE_ANY,
"octal permissions mode for uploaded files"
),
AP_INIT_TAKE1 (
"SecUploadKeepFiles",
cmd_upload_keep_files,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE1 (
"SecWebAppId",
cmd_web_app_id,
NULL,
CMD_SCOPE_ANY,
"id"
),
AP_INIT_TAKE1 (
"SecSensorId",
cmd_sensor_id,
NULL,
CMD_SCOPE_MAIN,
"sensor id"
),
AP_INIT_TAKE1 (
"SecHttpBlKey",
cmd_httpBl_key,
NULL,
CMD_SCOPE_ANY,
"httpBl access key"
),
AP_INIT_TAKE1 (
"SecHashEngine",
cmd_hash_engine,
NULL,
CMD_SCOPE_ANY,
"On or Off"
),
AP_INIT_TAKE2 (
"SecHashKey",
cmd_hash_key,
NULL,
CMD_SCOPE_ANY,
"Set Hash key"
),
AP_INIT_TAKE1 (
"SecHashParam",
cmd_hash_param,
NULL,
CMD_SCOPE_ANY,
"Set Hash parameter"
),
{ NULL }
};
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5608_0 |
crossvul-cpp_data_good_5411_6 | /**
* Regression test for <https://github.com/libgd/libgd/issues/340>
*
* We're testing that trying to create an oversized image fails early,
* triggering an appropriate warning.
*/
#include <string.h>
#include "gd.h"
#include "gd_errors.h"
#include "gdtest.h"
#define MSG "product of memory allocation multiplication would exceed INT_MAX, failing operation gracefully\n"
void error_handler(int priority, const char *format, ...)
{
gdTestAssert(priority == GD_WARNING);
gdTestAssert(!strcmp(format, MSG));
}
int main()
{
gdImagePtr im;
im = gdImageCreate(64970, 65111);
gdTestAssert(im == NULL);
return gdNumFailures();
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5411_6 |
crossvul-cpp_data_bad_3070_2 | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "../ssl_locl.h"
#include "internal/constant_time_locl.h"
#include <openssl/rand.h>
#include "record_locl.h"
static const unsigned char ssl3_pad_1[48] = {
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
};
static const unsigned char ssl3_pad_2[48] = {
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
};
/*
* Clear the contents of an SSL3_RECORD but retain any memory allocated
*/
void SSL3_RECORD_clear(SSL3_RECORD *r, unsigned int num_recs)
{
unsigned char *comp;
unsigned int i;
for (i = 0; i < num_recs; i++) {
comp = r[i].comp;
memset(&r[i], 0, sizeof(*r));
r[i].comp = comp;
}
}
void SSL3_RECORD_release(SSL3_RECORD *r, unsigned int num_recs)
{
unsigned int i;
for (i = 0; i < num_recs; i++) {
OPENSSL_free(r[i].comp);
r[i].comp = NULL;
}
}
void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
{
memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
}
/*
* Peeks ahead into "read_ahead" data to see if we have a whole record waiting
* for us in the buffer.
*/
static int ssl3_record_app_data_waiting(SSL *s)
{
SSL3_BUFFER *rbuf;
int left, len;
unsigned char *p;
rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
p = SSL3_BUFFER_get_buf(rbuf);
if (p == NULL)
return 0;
left = SSL3_BUFFER_get_left(rbuf);
if (left < SSL3_RT_HEADER_LENGTH)
return 0;
p += SSL3_BUFFER_get_offset(rbuf);
/*
* We only check the type and record length, we will sanity check version
* etc later
*/
if (*p != SSL3_RT_APPLICATION_DATA)
return 0;
p += 3;
n2s(p, len);
if (left < SSL3_RT_HEADER_LENGTH + len)
return 0;
return 1;
}
/*
* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
* will be processed per call to ssl3_get_record. Without this limit an
* attacker could send empty records at a faster rate than we can process and
* cause ssl3_get_record to loop forever.
*/
#define MAX_EMPTY_RECORDS 32
#define SSL2_RT_HEADER_LENGTH 2
/*-
* Call this to get new input records.
* It will return <= 0 if more data is needed, normally due to an error
* or non-blocking IO.
* When it finishes, |numrpipes| records have been decoded. For each record 'i':
* rr[i].type - is the type of record
* rr[i].data, - data
* rr[i].length, - number of bytes
* Multiple records will only be returned if the record types are all
* SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
* |max_pipelines|
*/
/* used only by ssl3_read_bytes */
int ssl3_get_record(SSL *s)
{
int ssl_major, ssl_minor, al;
int enc_err, n, i, ret = -1;
SSL3_RECORD *rr;
SSL3_BUFFER *rbuf;
SSL_SESSION *sess;
unsigned char *p;
unsigned char md[EVP_MAX_MD_SIZE];
short version;
unsigned mac_size;
unsigned int num_recs = 0;
unsigned int max_recs;
unsigned int j;
rr = RECORD_LAYER_get_rrec(&s->rlayer);
rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
max_recs = s->max_pipelines;
if (max_recs == 0)
max_recs = 1;
sess = s->session;
do {
/* check if we have the header */
if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
(RECORD_LAYER_get_packet_length(&s->rlayer)
< SSL3_RT_HEADER_LENGTH)) {
n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
SSL3_BUFFER_get_len(rbuf), 0,
num_recs == 0 ? 1 : 0);
if (n <= 0)
return (n); /* error or non-blocking */
RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
p = RECORD_LAYER_get_packet(&s->rlayer);
/*
* The first record received by the server may be a V2ClientHello.
*/
if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
&& (p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) {
/*
* SSLv2 style record
*
* |num_recs| here will actually always be 0 because
* |num_recs > 0| only ever occurs when we are processing
* multiple app data records - which we know isn't the case here
* because it is an SSLv2ClientHello. We keep it using
* |num_recs| for the sake of consistency
*/
rr[num_recs].type = SSL3_RT_HANDSHAKE;
rr[num_recs].rec_version = SSL2_VERSION;
rr[num_recs].length = ((p[0] & 0x7f) << 8) | p[1];
if (rr[num_recs].length > SSL3_BUFFER_get_len(rbuf)
- SSL2_RT_HEADER_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
goto f_err;
}
if (rr[num_recs].length < MIN_SSL2_RECORD_LEN) {
al = SSL_AD_HANDSHAKE_FAILURE;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
} else {
/* SSLv3+ style record */
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
s->msg_callback_arg);
/* Pull apart the header into the SSL3_RECORD */
rr[num_recs].type = *(p++);
ssl_major = *(p++);
ssl_minor = *(p++);
version = (ssl_major << 8) | ssl_minor;
rr[num_recs].rec_version = version;
n2s(p, rr[num_recs].length);
/* Lets check version */
if (!s->first_packet && version != s->version) {
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
if ((s->version & 0xFF00) == (version & 0xFF00)
&& !s->enc_write_ctx && !s->write_hash) {
if (rr->type == SSL3_RT_ALERT) {
/*
* The record is using an incorrect version number,
* but what we've got appears to be an alert. We
* haven't read the body yet to check whether its a
* fatal or not - but chances are it is. We probably
* shouldn't send a fatal alert back. We'll just
* end.
*/
goto err;
}
/*
* Send back error using their minor version number :-)
*/
s->version = (unsigned short)version;
}
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
if ((version >> 8) != SSL3_VERSION_MAJOR) {
if (RECORD_LAYER_is_first_record(&s->rlayer)) {
/* Go back to start of packet, look at the five bytes
* that we have. */
p = RECORD_LAYER_get_packet(&s->rlayer);
if (strncmp((char *)p, "GET ", 4) == 0 ||
strncmp((char *)p, "POST ", 5) == 0 ||
strncmp((char *)p, "HEAD ", 5) == 0 ||
strncmp((char *)p, "PUT ", 4) == 0) {
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_HTTP_REQUEST);
goto err;
} else if (strncmp((char *)p, "CONNE", 5) == 0) {
SSLerr(SSL_F_SSL3_GET_RECORD,
SSL_R_HTTPS_PROXY_REQUEST);
goto err;
}
/* Doesn't look like TLS - don't send an alert */
SSLerr(SSL_F_SSL3_GET_RECORD,
SSL_R_WRONG_VERSION_NUMBER);
goto err;
} else {
SSLerr(SSL_F_SSL3_GET_RECORD,
SSL_R_WRONG_VERSION_NUMBER);
al = SSL_AD_PROTOCOL_VERSION;
goto f_err;
}
}
if (rr[num_recs].length >
SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
goto f_err;
}
}
/* now s->rlayer.rstate == SSL_ST_READ_BODY */
}
/*
* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
* Calculate how much more data we need to read for the rest of the
* record
*/
if (rr[num_recs].rec_version == SSL2_VERSION) {
i = rr[num_recs].length + SSL2_RT_HEADER_LENGTH
- SSL3_RT_HEADER_LENGTH;
} else {
i = rr[num_recs].length;
}
if (i > 0) {
/* now s->packet_length == SSL3_RT_HEADER_LENGTH */
n = ssl3_read_n(s, i, i, 1, 0);
if (n <= 0)
return (n); /* error or non-blocking io */
}
/* set state for later operations */
RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
/*
* At this point, s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length,
* or s->packet_length == SSL2_RT_HEADER_LENGTH + rr->length
* and we have that many bytes in s->packet
*/
if (rr[num_recs].rec_version == SSL2_VERSION) {
rr[num_recs].input =
&(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
} else {
rr[num_recs].input =
&(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
}
/*
* ok, we can now read from 's->packet' data into 'rr' rr->input points
* at rr->length bytes, which need to be copied into rr->data by either
* the decryption or by the decompression When the data is 'copied' into
* the rr->data buffer, rr->input will be pointed at the new buffer
*/
/*
* We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
* bytes of encrypted compressed stuff.
*/
/* check is not needed I believe */
if (rr[num_recs].length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
goto f_err;
}
/* decrypt in place in 'rr->input' */
rr[num_recs].data = rr[num_recs].input;
rr[num_recs].orig_len = rr[num_recs].length;
/* Mark this record as not read by upper layers yet */
rr[num_recs].read = 0;
num_recs++;
/* we have pulled in a full packet so zero things */
RECORD_LAYER_reset_packet_length(&s->rlayer);
RECORD_LAYER_clear_first_record(&s->rlayer);
} while (num_recs < max_recs
&& rr[num_recs - 1].type == SSL3_RT_APPLICATION_DATA
&& SSL_USE_EXPLICIT_IV(s)
&& s->enc_read_ctx != NULL
&& (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
& EVP_CIPH_FLAG_PIPELINE)
&& ssl3_record_app_data_waiting(s));
/*
* If in encrypt-then-mac mode calculate mac from encrypted record. All
* the details below are public so no timing details can leak.
*/
if (SSL_USE_ETM(s) && s->read_hash) {
unsigned char *mac;
mac_size = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
for (j = 0; j < num_recs; j++) {
if (rr[j].length < mac_size) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
rr[j].length -= mac_size;
mac = rr[j].data + rr[j].length;
i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
if (i < 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
al = SSL_AD_BAD_RECORD_MAC;
SSLerr(SSL_F_SSL3_GET_RECORD,
SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
goto f_err;
}
}
}
enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0);
/*-
* enc_err is:
* 0: (in non-constant time) if the record is publically invalid.
* 1: if the padding is valid
* -1: if the padding is invalid
*/
if (enc_err == 0) {
al = SSL_AD_DECRYPTION_FAILED;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
goto f_err;
}
#ifdef SSL_DEBUG
printf("dec %d\n", rr->length);
{
unsigned int z;
for (z = 0; z < rr->length; z++)
printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\n");
#endif
/* r->length is now the compressed data plus mac */
if ((sess != NULL) &&
(s->enc_read_ctx != NULL) &&
(EVP_MD_CTX_md(s->read_hash) != NULL) && !SSL_USE_ETM(s)) {
/* s->read_hash != NULL => mac_size != -1 */
unsigned char *mac = NULL;
unsigned char mac_tmp[EVP_MAX_MD_SIZE];
mac_size = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
for (j = 0; j < num_recs; j++) {
/*
* orig_len is the length of the record before any padding was
* removed. This is public information, as is the MAC in use,
* therefore we can safely process the record in a different amount
* of time if it's too short to possibly contain a MAC.
*/
if (rr[j].orig_len < mac_size ||
/* CBC records must have a padding length byte too. */
(EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
rr[j].orig_len < mac_size + 1)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
/*
* We update the length so that the TLS header bytes can be
* constructed correctly but we need to extract the MAC in
* constant time from within the record, without leaking the
* contents of the padding bytes.
*/
mac = mac_tmp;
ssl3_cbc_copy_mac(mac_tmp, &rr[j], mac_size);
rr[j].length -= mac_size;
} else {
/*
* In this case there's no padding, so |rec->orig_len| equals
* |rec->length| and we checked that there's enough bytes for
* |mac_size| above.
*/
rr[j].length -= mac_size;
mac = &rr[j].data[rr[j].length];
}
i = s->method->ssl3_enc->mac(s, &rr[j], md, 0 /* not send */ );
if (i < 0 || mac == NULL
|| CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
enc_err = -1;
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
enc_err = -1;
}
}
if (enc_err < 0) {
/*
* A separate 'decryption_failed' alert was introduced with TLS 1.0,
* SSL 3.0 only has 'bad_record_mac'. But unless a decryption
* failure is directly visible from the ciphertext anyway, we should
* not reveal which kind of error occurred -- this might become
* visible to an attacker (e.g. via a logfile)
*/
al = SSL_AD_BAD_RECORD_MAC;
SSLerr(SSL_F_SSL3_GET_RECORD,
SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
goto f_err;
}
for (j = 0; j < num_recs; j++) {
/* rr[j].length is now just compressed */
if (s->expand != NULL) {
if (rr[j].length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
goto f_err;
}
if (!ssl3_do_uncompress(s, &rr[j])) {
al = SSL_AD_DECOMPRESSION_FAILURE;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
goto f_err;
}
}
if (rr[j].length > SSL3_RT_MAX_PLAIN_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
rr[j].off = 0;
/*-
* So at this point the following is true
* rr[j].type is the type of record
* rr[j].length == number of bytes in record
* rr[j].off == offset to first valid byte
* rr[j].data == where to take bytes from, increment after use :-).
*/
/* just read a 0 length packet */
if (rr[j].length == 0) {
RECORD_LAYER_inc_empty_record_count(&s->rlayer);
if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
> MAX_EMPTY_RECORDS) {
al = SSL_AD_UNEXPECTED_MESSAGE;
SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
goto f_err;
}
} else {
RECORD_LAYER_reset_empty_record_count(&s->rlayer);
}
}
RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
return 1;
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
return ret;
}
int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
{
#ifndef OPENSSL_NO_COMP
int i;
if (rr->comp == NULL) {
rr->comp = (unsigned char *)
OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
}
if (rr->comp == NULL)
return 0;
i = COMP_expand_block(ssl->expand, rr->comp,
SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
if (i < 0)
return 0;
else
rr->length = i;
rr->data = rr->comp;
#endif
return 1;
}
int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
{
#ifndef OPENSSL_NO_COMP
int i;
i = COMP_compress_block(ssl->compress, wr->data,
SSL3_RT_MAX_COMPRESSED_LENGTH,
wr->input, (int)wr->length);
if (i < 0)
return (0);
else
wr->length = i;
wr->input = wr->data;
#endif
return (1);
}
/*-
* ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|
*
* Returns:
* 0: (in non-constant time) if the record is publically invalid (i.e. too
* short etc).
* 1: if the record's padding is valid / the encryption was successful.
* -1: if the record's padding is invalid or, if sending, an internal error
* occurred.
*/
int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, unsigned int n_recs, int send)
{
SSL3_RECORD *rec;
EVP_CIPHER_CTX *ds;
unsigned long l;
int bs, i, mac_size = 0;
const EVP_CIPHER *enc;
rec = inrecs;
/*
* We shouldn't ever be called with more than one record in the SSLv3 case
*/
if (n_recs != 1)
return 0;
if (send) {
ds = s->enc_write_ctx;
if (s->enc_write_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
} else {
ds = s->enc_read_ctx;
if (s->enc_read_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
}
if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
memmove(rec->data, rec->input, rec->length);
rec->input = rec->data;
} else {
l = rec->length;
bs = EVP_CIPHER_CTX_block_size(ds);
/* COMPRESS */
if ((bs != 1) && send) {
i = bs - ((int)l % bs);
/* we need to add 'i-1' padding bytes */
l += i;
/*
* the last of these zero bytes will be overwritten with the
* padding length.
*/
memset(&rec->input[rec->length], 0, i);
rec->length += i;
rec->input[l - 1] = (i - 1);
}
if (!send) {
if (l == 0 || l % bs != 0)
return 0;
/* otherwise, rec->length >= bs */
}
if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
return -1;
if (EVP_MD_CTX_md(s->read_hash) != NULL)
mac_size = EVP_MD_CTX_size(s->read_hash);
if ((bs != 1) && !send)
return ssl3_cbc_remove_padding(rec, bs, mac_size);
}
return (1);
}
/*-
* tls1_enc encrypts/decrypts |n_recs| in |recs|.
*
* Returns:
* 0: (in non-constant time) if the record is publically invalid (i.e. too
* short etc).
* 1: if the record's padding is valid / the encryption was successful.
* -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
* an internal error occurred.
*/
int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
{
EVP_CIPHER_CTX *ds;
size_t reclen[SSL_MAX_PIPELINES];
unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
int bs, i, j, k, pad = 0, ret, mac_size = 0;
const EVP_CIPHER *enc;
unsigned int ctr;
if (send) {
if (EVP_MD_CTX_md(s->write_hash)) {
int n = EVP_MD_CTX_size(s->write_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_write_ctx;
if (s->enc_write_ctx == NULL)
enc = NULL;
else {
int ivlen;
enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
/* For TLSv1.1 and later explicit IV */
if (SSL_USE_EXPLICIT_IV(s)
&& EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
ivlen = EVP_CIPHER_iv_length(enc);
else
ivlen = 0;
if (ivlen > 1) {
for (ctr = 0; ctr < n_recs; ctr++) {
if (recs[ctr].data != recs[ctr].input) {
/*
* we can't write into the input stream: Can this ever
* happen?? (steve)
*/
SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
return -1;
} else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
return -1;
}
}
}
}
} else {
if (EVP_MD_CTX_md(s->read_hash)) {
int n = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(n >= 0);
}
ds = s->enc_read_ctx;
if (s->enc_read_ctx == NULL)
enc = NULL;
else
enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
}
if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
for (ctr = 0; ctr < n_recs; ctr++) {
memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
recs[ctr].input = recs[ctr].data;
}
ret = 1;
} else {
bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
if (n_recs > 1) {
if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_PIPELINE)) {
/*
* We shouldn't have been called with pipeline data if the
* cipher doesn't support pipelining
*/
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
return -1;
}
}
for (ctr = 0; ctr < n_recs; ctr++) {
reclen[ctr] = recs[ctr].length;
if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_AEAD_CIPHER) {
unsigned char *seq;
seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
: RECORD_LAYER_get_read_sequence(&s->rlayer);
if (SSL_IS_DTLS(s)) {
/* DTLS does not support pipelining */
unsigned char dtlsseq[9], *p = dtlsseq;
s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
memcpy(p, &seq[2], 6);
memcpy(buf[ctr], dtlsseq, 8);
} else {
memcpy(buf[ctr], seq, 8);
for (i = 7; i >= 0; i--) { /* increment */
++seq[i];
if (seq[i] != 0)
break;
}
}
buf[ctr][8] = recs[ctr].type;
buf[ctr][9] = (unsigned char)(s->version >> 8);
buf[ctr][10] = (unsigned char)(s->version);
buf[ctr][11] = recs[ctr].length >> 8;
buf[ctr][12] = recs[ctr].length & 0xff;
pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
if (pad <= 0)
return -1;
if (send) {
reclen[ctr] += pad;
recs[ctr].length += pad;
}
} else if ((bs != 1) && send) {
i = bs - ((int)reclen[ctr] % bs);
/* Add weird padding of upto 256 bytes */
/* we need to add 'i' padding bytes of value j */
j = i - 1;
for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
recs[ctr].input[k] = j;
reclen[ctr] += i;
recs[ctr].length += i;
}
if (!send) {
if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
return 0;
}
}
if (n_recs > 1) {
unsigned char *data[SSL_MAX_PIPELINES];
/* Set the output buffers */
for (ctr = 0; ctr < n_recs; ctr++) {
data[ctr] = recs[ctr].data;
}
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
n_recs, data) <= 0) {
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
}
/* Set the input buffers */
for (ctr = 0; ctr < n_recs; ctr++) {
data[ctr] = recs[ctr].input;
}
if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
n_recs, data) <= 0
|| EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
n_recs, reclen) <= 0) {
SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
return -1;
}
}
i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
& EVP_CIPH_FLAG_CUSTOM_CIPHER)
? (i < 0)
: (i == 0))
return -1; /* AEAD can fail to verify MAC */
if (send == 0) {
if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
}
} else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
}
}
}
ret = 1;
if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
mac_size = EVP_MD_CTX_size(s->read_hash);
if ((bs != 1) && !send) {
int tmpret;
for (ctr = 0; ctr < n_recs; ctr++) {
tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
/*
* If tmpret == 0 then this means publicly invalid so we can
* short circuit things here. Otherwise we must respect constant
* time behaviour.
*/
if (tmpret == 0)
return 0;
ret = constant_time_select_int(constant_time_eq_int(tmpret, 1),
ret, -1);
}
}
if (pad && !send) {
for (ctr = 0; ctr < n_recs; ctr++) {
recs[ctr].length -= pad;
}
}
}
return ret;
}
int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
{
unsigned char *mac_sec, *seq;
const EVP_MD_CTX *hash;
unsigned char *p, rec_char;
size_t md_size;
int npad;
int t;
if (send) {
mac_sec = &(ssl->s3->write_mac_secret[0]);
seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
hash = ssl->write_hash;
} else {
mac_sec = &(ssl->s3->read_mac_secret[0]);
seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
hash = ssl->read_hash;
}
t = EVP_MD_CTX_size(hash);
if (t < 0)
return -1;
md_size = t;
npad = (48 / md_size) * md_size;
if (!send &&
EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
ssl3_cbc_record_digest_supported(hash)) {
/*
* This is a CBC-encrypted record. We must avoid leaking any
* timing-side channel information about how many blocks of data we
* are hashing because that gives an attacker a timing-oracle.
*/
/*-
* npad is, at most, 48 bytes and that's with MD5:
* 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
*
* With SHA-1 (the largest hash speced for SSLv3) the hash size
* goes up 4, but npad goes down by 8, resulting in a smaller
* total size.
*/
unsigned char header[75];
unsigned j = 0;
memcpy(header + j, mac_sec, md_size);
j += md_size;
memcpy(header + j, ssl3_pad_1, npad);
j += npad;
memcpy(header + j, seq, 8);
j += 8;
header[j++] = rec->type;
header[j++] = rec->length >> 8;
header[j++] = rec->length & 0xff;
/* Final param == is SSLv3 */
if (ssl3_cbc_digest_record(hash,
md, &md_size,
header, rec->input,
rec->length + md_size, rec->orig_len,
mac_sec, md_size, 1) <= 0)
return -1;
} else {
unsigned int md_size_u;
/* Chop the digest off the end :-) */
EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
if (md_ctx == NULL)
return -1;
rec_char = rec->type;
p = md;
s2n(rec->length, p);
if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
|| EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
|| EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
|| EVP_DigestUpdate(md_ctx, seq, 8) <= 0
|| EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
|| EVP_DigestUpdate(md_ctx, md, 2) <= 0
|| EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
|| EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
|| EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
|| EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
|| EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
|| EVP_DigestUpdate(md_ctx, md, md_size) <= 0
|| EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
EVP_MD_CTX_reset(md_ctx);
return -1;
}
md_size = md_size_u;
EVP_MD_CTX_free(md_ctx);
}
ssl3_record_sequence_update(seq);
return (md_size);
}
int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
{
unsigned char *seq;
EVP_MD_CTX *hash;
size_t md_size;
int i;
EVP_MD_CTX *hmac = NULL, *mac_ctx;
unsigned char header[13];
int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
: (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
int t;
if (send) {
seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
hash = ssl->write_hash;
} else {
seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
hash = ssl->read_hash;
}
t = EVP_MD_CTX_size(hash);
OPENSSL_assert(t >= 0);
md_size = t;
/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
if (stream_mac) {
mac_ctx = hash;
} else {
hmac = EVP_MD_CTX_new();
if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash))
return -1;
mac_ctx = hmac;
}
if (SSL_IS_DTLS(ssl)) {
unsigned char dtlsseq[8], *p = dtlsseq;
s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
memcpy(p, &seq[2], 6);
memcpy(header, dtlsseq, 8);
} else
memcpy(header, seq, 8);
header[8] = rec->type;
header[9] = (unsigned char)(ssl->version >> 8);
header[10] = (unsigned char)(ssl->version);
header[11] = (rec->length) >> 8;
header[12] = (rec->length) & 0xff;
if (!send && !SSL_USE_ETM(ssl) &&
EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
ssl3_cbc_record_digest_supported(mac_ctx)) {
/*
* This is a CBC-encrypted record. We must avoid leaking any
* timing-side channel information about how many blocks of data we
* are hashing because that gives an attacker a timing-oracle.
*/
/* Final param == not SSLv3 */
if (ssl3_cbc_digest_record(mac_ctx,
md, &md_size,
header, rec->input,
rec->length + md_size, rec->orig_len,
ssl->s3->read_mac_secret,
ssl->s3->read_mac_secret_size, 0) <= 0) {
EVP_MD_CTX_free(hmac);
return -1;
}
} else {
if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
|| EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
|| EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
EVP_MD_CTX_free(hmac);
return -1;
}
if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
if (!tls_fips_digest_extra(ssl->enc_read_ctx,
mac_ctx, rec->input,
rec->length, rec->orig_len)) {
EVP_MD_CTX_free(hmac);
return -1;
}
}
EVP_MD_CTX_free(hmac);
#ifdef SSL_DEBUG
fprintf(stderr, "seq=");
{
int z;
for (z = 0; z < 8; z++)
fprintf(stderr, "%02X ", seq[z]);
fprintf(stderr, "\n");
}
fprintf(stderr, "rec=");
{
unsigned int z;
for (z = 0; z < rec->length; z++)
fprintf(stderr, "%02X ", rec->data[z]);
fprintf(stderr, "\n");
}
#endif
if (!SSL_IS_DTLS(ssl)) {
for (i = 7; i >= 0; i--) {
++seq[i];
if (seq[i] != 0)
break;
}
}
#ifdef SSL_DEBUG
{
unsigned int z;
for (z = 0; z < md_size; z++)
fprintf(stderr, "%02X ", md[z]);
fprintf(stderr, "\n");
}
#endif
return (md_size);
}
/*-
* ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
* record in |rec| by updating |rec->length| in constant time.
*
* block_size: the block size of the cipher used to encrypt the record.
* returns:
* 0: (in non-constant time) if the record is publicly invalid.
* 1: if the padding was valid
* -1: otherwise.
*/
int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
unsigned block_size, unsigned mac_size)
{
unsigned padding_length, good;
const unsigned overhead = 1 /* padding length byte */ + mac_size;
/*
* These lengths are all public so we can test them in non-constant time.
*/
if (overhead > rec->length)
return 0;
padding_length = rec->data[rec->length - 1];
good = constant_time_ge(rec->length, padding_length + overhead);
/* SSLv3 requires that the padding is minimal. */
good &= constant_time_ge(block_size, padding_length + 1);
rec->length -= good & (padding_length + 1);
return constant_time_select_int(good, 1, -1);
}
/*-
* tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
* record in |rec| in constant time and returns 1 if the padding is valid and
* -1 otherwise. It also removes any explicit IV from the start of the record
* without leaking any timing about whether there was enough space after the
* padding was removed.
*
* block_size: the block size of the cipher used to encrypt the record.
* returns:
* 0: (in non-constant time) if the record is publicly invalid.
* 1: if the padding was valid
* -1: otherwise.
*/
int tls1_cbc_remove_padding(const SSL *s,
SSL3_RECORD *rec,
unsigned block_size, unsigned mac_size)
{
unsigned padding_length, good, to_check, i;
const unsigned overhead = 1 /* padding length byte */ + mac_size;
/* Check if version requires explicit IV */
if (SSL_USE_EXPLICIT_IV(s)) {
/*
* These lengths are all public so we can test them in non-constant
* time.
*/
if (overhead + block_size > rec->length)
return 0;
/* We can now safely skip explicit IV */
rec->data += block_size;
rec->input += block_size;
rec->length -= block_size;
rec->orig_len -= block_size;
} else if (overhead > rec->length)
return 0;
padding_length = rec->data[rec->length - 1];
if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) &
EVP_CIPH_FLAG_AEAD_CIPHER) {
/* padding is already verified */
rec->length -= padding_length + 1;
return 1;
}
good = constant_time_ge(rec->length, overhead + padding_length);
/*
* The padding consists of a length byte at the end of the record and
* then that many bytes of padding, all with the same value as the length
* byte. Thus, with the length byte included, there are i+1 bytes of
* padding. We can't check just |padding_length+1| bytes because that
* leaks decrypted information. Therefore we always have to check the
* maximum amount of padding possible. (Again, the length of the record
* is public information so we can use it.)
*/
to_check = 256; /* maximum amount of padding, inc length byte. */
if (to_check > rec->length)
to_check = rec->length;
for (i = 0; i < to_check; i++) {
unsigned char mask = constant_time_ge_8(padding_length, i);
unsigned char b = rec->data[rec->length - 1 - i];
/*
* The final |padding_length+1| bytes should all have the value
* |padding_length|. Therefore the XOR should be zero.
*/
good &= ~(mask & (padding_length ^ b));
}
/*
* If any of the final |padding_length+1| bytes had the wrong value, one
* or more of the lower eight bits of |good| will be cleared.
*/
good = constant_time_eq(0xff, good & 0xff);
rec->length -= good & (padding_length + 1);
return constant_time_select_int(good, 1, -1);
}
/*-
* ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
* constant time (independent of the concrete value of rec->length, which may
* vary within a 256-byte window).
*
* ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
* this function.
*
* On entry:
* rec->orig_len >= md_size
* md_size <= EVP_MAX_MD_SIZE
*
* If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
* variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
* a single or pair of cache-lines, then the variable memory accesses don't
* actually affect the timing. CPUs with smaller cache-lines [if any] are
* not multi-core and are not considered vulnerable to cache-timing attacks.
*/
#define CBC_MAC_ROTATE_IN_PLACE
void ssl3_cbc_copy_mac(unsigned char *out,
const SSL3_RECORD *rec, unsigned md_size)
{
#if defined(CBC_MAC_ROTATE_IN_PLACE)
unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
unsigned char *rotated_mac;
#else
unsigned char rotated_mac[EVP_MAX_MD_SIZE];
#endif
/*
* mac_end is the index of |rec->data| just after the end of the MAC.
*/
unsigned mac_end = rec->length;
unsigned mac_start = mac_end - md_size;
unsigned in_mac;
/*
* scan_start contains the number of bytes that we can ignore because the
* MAC's position can only vary by 255 bytes.
*/
unsigned scan_start = 0;
unsigned i, j;
unsigned rotate_offset;
OPENSSL_assert(rec->orig_len >= md_size);
OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
#if defined(CBC_MAC_ROTATE_IN_PLACE)
rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
#endif
/* This information is public so it's safe to branch based on it. */
if (rec->orig_len > md_size + 255 + 1)
scan_start = rec->orig_len - (md_size + 255 + 1);
in_mac = 0;
rotate_offset = 0;
memset(rotated_mac, 0, md_size);
for (i = scan_start, j = 0; i < rec->orig_len; i++) {
unsigned mac_started = constant_time_eq(i, mac_start);
unsigned mac_ended = constant_time_lt(i, mac_end);
unsigned char b = rec->data[i];
in_mac |= mac_started;
in_mac &= mac_ended;
rotate_offset |= j & mac_started;
rotated_mac[j++] |= b & in_mac;
j &= constant_time_lt(j, md_size);
}
/* Now rotate the MAC */
#if defined(CBC_MAC_ROTATE_IN_PLACE)
j = 0;
for (i = 0; i < md_size; i++) {
/* in case cache-line is 32 bytes, touch second line */
((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
out[j++] = rotated_mac[rotate_offset++];
rotate_offset &= constant_time_lt(rotate_offset, md_size);
}
#else
memset(out, 0, md_size);
rotate_offset = md_size - rotate_offset;
rotate_offset &= constant_time_lt(rotate_offset, md_size);
for (i = 0; i < md_size; i++) {
for (j = 0; j < md_size; j++)
out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
rotate_offset++;
rotate_offset &= constant_time_lt(rotate_offset, md_size);
}
#endif
}
int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
{
int i, al;
int enc_err;
SSL_SESSION *sess;
SSL3_RECORD *rr;
unsigned int mac_size;
unsigned char md[EVP_MAX_MD_SIZE];
rr = RECORD_LAYER_get_rrec(&s->rlayer);
sess = s->session;
/*
* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
* and we have that many bytes in s->packet
*/
rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
/*
* ok, we can now read from 's->packet' data into 'rr' rr->input points
* at rr->length bytes, which need to be copied into rr->data by either
* the decryption or by the decompression When the data is 'copied' into
* the rr->data buffer, rr->input will be pointed at the new buffer
*/
/*
* We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
* bytes of encrypted compressed stuff.
*/
/* check is not needed I believe */
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
goto f_err;
}
/* decrypt in place in 'rr->input' */
rr->data = rr->input;
rr->orig_len = rr->length;
enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
/*-
* enc_err is:
* 0: (in non-constant time) if the record is publically invalid.
* 1: if the padding is valid
* -1: if the padding is invalid
*/
if (enc_err == 0) {
/* For DTLS we simply ignore bad packets. */
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto err;
}
#ifdef SSL_DEBUG
printf("dec %d\n", rr->length);
{
unsigned int z;
for (z = 0; z < rr->length; z++)
printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\n");
#endif
/* r->length is now the compressed data plus mac */
if ((sess != NULL) &&
(s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
/* s->read_hash != NULL => mac_size != -1 */
unsigned char *mac = NULL;
unsigned char mac_tmp[EVP_MAX_MD_SIZE];
mac_size = EVP_MD_CTX_size(s->read_hash);
OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
/*
* orig_len is the length of the record before any padding was
* removed. This is public information, as is the MAC in use,
* therefore we can safely process the record in a different amount
* of time if it's too short to possibly contain a MAC.
*/
if (rr->orig_len < mac_size ||
/* CBC records must have a padding length byte too. */
(EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
rr->orig_len < mac_size + 1)) {
al = SSL_AD_DECODE_ERROR;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
goto f_err;
}
if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
/*
* We update the length so that the TLS header bytes can be
* constructed correctly but we need to extract the MAC in
* constant time from within the record, without leaking the
* contents of the padding bytes.
*/
mac = mac_tmp;
ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
rr->length -= mac_size;
} else {
/*
* In this case there's no padding, so |rec->orig_len| equals
* |rec->length| and we checked that there's enough bytes for
* |mac_size| above.
*/
rr->length -= mac_size;
mac = &rr->data[rr->length];
}
i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
if (i < 0 || mac == NULL
|| CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
enc_err = -1;
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
enc_err = -1;
}
if (enc_err < 0) {
/* decryption failed, silently discard message */
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto err;
}
/* r->length is now just compressed */
if (s->expand != NULL) {
if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
SSL_R_COMPRESSED_LENGTH_TOO_LONG);
goto f_err;
}
if (!ssl3_do_uncompress(s, rr)) {
al = SSL_AD_DECOMPRESSION_FAILURE;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
goto f_err;
}
}
if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
al = SSL_AD_RECORD_OVERFLOW;
SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
goto f_err;
}
rr->off = 0;
/*-
* So at this point the following is true
* ssl->s3->rrec.type is the type of record
* ssl->s3->rrec.length == number of bytes in record
* ssl->s3->rrec.off == offset to first valid byte
* ssl->s3->rrec.data == where to take bytes from, increment
* after use :-).
*/
/* we have pulled in a full packet so zero things */
RECORD_LAYER_reset_packet_length(&s->rlayer);
/* Mark receipt of record. */
dtls1_record_bitmap_update(s, bitmap);
return (1);
f_err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
err:
return (0);
}
/*
* retrieve a buffered record that belongs to the current epoch, ie,
* processed
*/
#define dtls1_get_processed_record(s) \
dtls1_retrieve_buffered_record((s), \
&(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
/*-
* Call this to get a new input record.
* It will return <= 0 if more data is needed, normally due to an error
* or non-blocking IO.
* When it finishes, one packet has been decoded and can be found in
* ssl->s3->rrec.type - is the type of record
* ssl->s3->rrec.data, - data
* ssl->s3->rrec.length, - number of bytes
*/
/* used only by dtls1_read_bytes */
int dtls1_get_record(SSL *s)
{
int ssl_major, ssl_minor;
int i, n;
SSL3_RECORD *rr;
unsigned char *p = NULL;
unsigned short version;
DTLS1_BITMAP *bitmap;
unsigned int is_next_epoch;
rr = RECORD_LAYER_get_rrec(&s->rlayer);
again:
/*
* The epoch may have changed. If so, process all the pending records.
* This is a non-blocking operation.
*/
if (!dtls1_process_buffered_records(s))
return -1;
/* if we're renegotiating, then there may be buffered records */
if (dtls1_get_processed_record(s))
return 1;
/* get something from the wire */
/* check if we have the header */
if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
(RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
/* read timeout is handled by dtls1_read_bytes */
if (n <= 0)
return (n); /* error or non-blocking */
/* this packet contained a partial record, dump it */
if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
DTLS1_RT_HEADER_LENGTH) {
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto again;
}
RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
p = RECORD_LAYER_get_packet(&s->rlayer);
if (s->msg_callback)
s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
s, s->msg_callback_arg);
/* Pull apart the header into the DTLS1_RECORD */
rr->type = *(p++);
ssl_major = *(p++);
ssl_minor = *(p++);
version = (ssl_major << 8) | ssl_minor;
/* sequence number is 64 bits, with top 2 bytes = epoch */
n2s(p, rr->epoch);
memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
p += 6;
n2s(p, rr->length);
/* Lets check version */
if (!s->first_packet) {
if (version != s->version) {
/* unexpected version, silently discard */
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto again;
}
}
if ((version & 0xff00) != (s->version & 0xff00)) {
/* wrong version, silently discard record */
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto again;
}
if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
/* record too long, silently discard it */
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto again;
}
/* now s->rlayer.rstate == SSL_ST_READ_BODY */
}
/* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
if (rr->length >
RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
/* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
i = rr->length;
n = ssl3_read_n(s, i, i, 1, 1);
/* this packet contained a partial record, dump it */
if (n != i) {
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto again;
}
/*
* now n == rr->length, and s->packet_length ==
* DTLS1_RT_HEADER_LENGTH + rr->length
*/
}
/* set state for later operations */
RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
/* match epochs. NULL means the packet is dropped on the floor */
bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
if (bitmap == NULL) {
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
/* Only do replay check if no SCTP bio */
if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
#endif
/* Check whether this is a repeat, or aged record. */
/*
* TODO: Does it make sense to have replay protection in epoch 0 where
* we have no integrity negotiated yet?
*/
if (!dtls1_record_replay_check(s, bitmap)) {
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
goto again; /* get another record */
}
#ifndef OPENSSL_NO_SCTP
}
#endif
/* just read a 0 length packet */
if (rr->length == 0)
goto again;
/*
* If this record is from the next epoch (either HM or ALERT), and a
* handshake is currently in progress, buffer it since it cannot be
* processed at this time.
*/
if (is_next_epoch) {
if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
if (dtls1_buffer_record
(s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
rr->seq_num) < 0)
return -1;
}
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer);
goto again;
}
if (!dtls1_process_record(s, bitmap)) {
rr->length = 0;
RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
goto again; /* get another record */
}
return (1);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3070_2 |
crossvul-cpp_data_bad_5765_0 | /*
* Kernel-based Virtual Machine driver for Linux
*
* This module enables machines with Intel VT-x extensions to run virtual
* machines without emulation or binary translation.
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include "iodev.h"
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/percpu.h>
#include <linux/mm.h>
#include <linux/miscdevice.h>
#include <linux/vmalloc.h>
#include <linux/reboot.h>
#include <linux/debugfs.h>
#include <linux/highmem.h>
#include <linux/file.h>
#include <linux/syscore_ops.h>
#include <linux/cpu.h>
#include <linux/sched.h>
#include <linux/cpumask.h>
#include <linux/smp.h>
#include <linux/anon_inodes.h>
#include <linux/profile.h>
#include <linux/kvm_para.h>
#include <linux/pagemap.h>
#include <linux/mman.h>
#include <linux/swap.h>
#include <linux/bitops.h>
#include <linux/spinlock.h>
#include <linux/compat.h>
#include <linux/srcu.h>
#include <linux/hugetlb.h>
#include <linux/slab.h>
#include <linux/sort.h>
#include <linux/bsearch.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include "coalesced_mmio.h"
#include "async_pf.h"
#define CREATE_TRACE_POINTS
#include <trace/events/kvm.h>
MODULE_AUTHOR("Qumranet");
MODULE_LICENSE("GPL");
/*
* Ordering of locks:
*
* kvm->lock --> kvm->slots_lock --> kvm->irq_lock
*/
DEFINE_SPINLOCK(kvm_lock);
static DEFINE_RAW_SPINLOCK(kvm_count_lock);
LIST_HEAD(vm_list);
static cpumask_var_t cpus_hardware_enabled;
static int kvm_usage_count = 0;
static atomic_t hardware_enable_failed;
struct kmem_cache *kvm_vcpu_cache;
EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
static __read_mostly struct preempt_ops kvm_preempt_ops;
struct dentry *kvm_debugfs_dir;
static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg);
#ifdef CONFIG_COMPAT
static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
unsigned long arg);
#endif
static int hardware_enable_all(void);
static void hardware_disable_all(void);
static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
bool kvm_rebooting;
EXPORT_SYMBOL_GPL(kvm_rebooting);
static bool largepages_enabled = true;
bool kvm_is_mmio_pfn(pfn_t pfn)
{
if (pfn_valid(pfn))
return PageReserved(pfn_to_page(pfn));
return true;
}
/*
* Switches to specified vcpu, until a matching vcpu_put()
*/
int vcpu_load(struct kvm_vcpu *vcpu)
{
int cpu;
if (mutex_lock_killable(&vcpu->mutex))
return -EINTR;
if (unlikely(vcpu->pid != current->pids[PIDTYPE_PID].pid)) {
/* The thread running this VCPU changed. */
struct pid *oldpid = vcpu->pid;
struct pid *newpid = get_task_pid(current, PIDTYPE_PID);
rcu_assign_pointer(vcpu->pid, newpid);
synchronize_rcu();
put_pid(oldpid);
}
cpu = get_cpu();
preempt_notifier_register(&vcpu->preempt_notifier);
kvm_arch_vcpu_load(vcpu, cpu);
put_cpu();
return 0;
}
void vcpu_put(struct kvm_vcpu *vcpu)
{
preempt_disable();
kvm_arch_vcpu_put(vcpu);
preempt_notifier_unregister(&vcpu->preempt_notifier);
preempt_enable();
mutex_unlock(&vcpu->mutex);
}
static void ack_flush(void *_completed)
{
}
static bool make_all_cpus_request(struct kvm *kvm, unsigned int req)
{
int i, cpu, me;
cpumask_var_t cpus;
bool called = true;
struct kvm_vcpu *vcpu;
zalloc_cpumask_var(&cpus, GFP_ATOMIC);
me = get_cpu();
kvm_for_each_vcpu(i, vcpu, kvm) {
kvm_make_request(req, vcpu);
cpu = vcpu->cpu;
/* Set ->requests bit before we read ->mode */
smp_mb();
if (cpus != NULL && cpu != -1 && cpu != me &&
kvm_vcpu_exiting_guest_mode(vcpu) != OUTSIDE_GUEST_MODE)
cpumask_set_cpu(cpu, cpus);
}
if (unlikely(cpus == NULL))
smp_call_function_many(cpu_online_mask, ack_flush, NULL, 1);
else if (!cpumask_empty(cpus))
smp_call_function_many(cpus, ack_flush, NULL, 1);
else
called = false;
put_cpu();
free_cpumask_var(cpus);
return called;
}
void kvm_flush_remote_tlbs(struct kvm *kvm)
{
long dirty_count = kvm->tlbs_dirty;
smp_mb();
if (make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
++kvm->stat.remote_tlb_flush;
cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
}
EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
void kvm_reload_remote_mmus(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
}
void kvm_make_mclock_inprogress_request(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_MCLOCK_INPROGRESS);
}
void kvm_make_scan_ioapic_request(struct kvm *kvm)
{
make_all_cpus_request(kvm, KVM_REQ_SCAN_IOAPIC);
}
int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
{
struct page *page;
int r;
mutex_init(&vcpu->mutex);
vcpu->cpu = -1;
vcpu->kvm = kvm;
vcpu->vcpu_id = id;
vcpu->pid = NULL;
init_waitqueue_head(&vcpu->wq);
kvm_async_pf_vcpu_init(vcpu);
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->run = page_address(page);
kvm_vcpu_set_in_spin_loop(vcpu, false);
kvm_vcpu_set_dy_eligible(vcpu, false);
vcpu->preempted = false;
r = kvm_arch_vcpu_init(vcpu);
if (r < 0)
goto fail_free_run;
return 0;
fail_free_run:
free_page((unsigned long)vcpu->run);
fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_vcpu_init);
void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
{
put_pid(vcpu->pid);
kvm_arch_vcpu_uninit(vcpu);
free_page((unsigned long)vcpu->run);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
{
return container_of(mn, struct kvm, mmu_notifier);
}
static void kvm_mmu_notifier_invalidate_page(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush, idx;
/*
* When ->invalidate_page runs, the linux pte has been zapped
* already but the page is still allocated until
* ->invalidate_page returns. So if we increase the sequence
* here the kvm page fault will notice if the spte can't be
* established because the page is going to be freed. If
* instead the kvm page fault establishes the spte before
* ->invalidate_page runs, kvm_unmap_hva will release it
* before returning.
*
* The sequence increase only need to be seen at spin_unlock
* time, and not at spin_lock time.
*
* Increasing the sequence after the spin_unlock would be
* unsafe because the kvm page fault could then establish the
* pte after kvm_unmap_hva returned, without noticing the page
* is going to be freed.
*/
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
need_tlb_flush = kvm_unmap_hva(kvm, address) | kvm->tlbs_dirty;
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address,
pte_t pte)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
kvm->mmu_notifier_seq++;
kvm_set_spte_hva(kvm, address, pte);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int need_tlb_flush = 0, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
/*
* The count increase must become visible at unlock time as no
* spte can be established without taking the mmu_lock and
* count is also read inside the mmu_lock critical section.
*/
kvm->mmu_notifier_count++;
need_tlb_flush = kvm_unmap_hva_range(kvm, start, end);
need_tlb_flush |= kvm->tlbs_dirty;
/* we've to flush the tlb before the pages can be freed */
if (need_tlb_flush)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
}
static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
spin_lock(&kvm->mmu_lock);
/*
* This sequence increase will notify the kvm page fault that
* the page that is going to be mapped in the spte could have
* been freed.
*/
kvm->mmu_notifier_seq++;
smp_wmb();
/*
* The above sequence increase must be visible before the
* below count decrease, which is ensured by the smp_wmb above
* in conjunction with the smp_rmb in mmu_notifier_retry().
*/
kvm->mmu_notifier_count--;
spin_unlock(&kvm->mmu_lock);
BUG_ON(kvm->mmu_notifier_count < 0);
}
static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_age_hva(kvm, address);
if (young)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
return young;
}
static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
struct mm_struct *mm,
unsigned long address)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int young, idx;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
young = kvm_test_age_hva(kvm, address);
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
return young;
}
static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
struct mm_struct *mm)
{
struct kvm *kvm = mmu_notifier_to_kvm(mn);
int idx;
idx = srcu_read_lock(&kvm->srcu);
kvm_arch_flush_shadow_all(kvm);
srcu_read_unlock(&kvm->srcu, idx);
}
static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
.invalidate_page = kvm_mmu_notifier_invalidate_page,
.invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
.invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
.clear_flush_young = kvm_mmu_notifier_clear_flush_young,
.test_young = kvm_mmu_notifier_test_young,
.change_pte = kvm_mmu_notifier_change_pte,
.release = kvm_mmu_notifier_release,
};
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
}
#else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
static int kvm_init_mmu_notifier(struct kvm *kvm)
{
return 0;
}
#endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
static void kvm_init_memslots_id(struct kvm *kvm)
{
int i;
struct kvm_memslots *slots = kvm->memslots;
for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
slots->id_to_index[i] = slots->memslots[i].id = i;
}
static struct kvm *kvm_create_vm(unsigned long type)
{
int r, i;
struct kvm *kvm = kvm_arch_alloc_vm();
if (!kvm)
return ERR_PTR(-ENOMEM);
r = kvm_arch_init_vm(kvm, type);
if (r)
goto out_err_nodisable;
r = hardware_enable_all();
if (r)
goto out_err_nodisable;
#ifdef CONFIG_HAVE_KVM_IRQCHIP
INIT_HLIST_HEAD(&kvm->mask_notifier_list);
INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
#endif
BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
r = -ENOMEM;
kvm->memslots = kzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
if (!kvm->memslots)
goto out_err_nosrcu;
kvm_init_memslots_id(kvm);
if (init_srcu_struct(&kvm->srcu))
goto out_err_nosrcu;
for (i = 0; i < KVM_NR_BUSES; i++) {
kvm->buses[i] = kzalloc(sizeof(struct kvm_io_bus),
GFP_KERNEL);
if (!kvm->buses[i])
goto out_err;
}
spin_lock_init(&kvm->mmu_lock);
kvm->mm = current->mm;
atomic_inc(&kvm->mm->mm_count);
kvm_eventfd_init(kvm);
mutex_init(&kvm->lock);
mutex_init(&kvm->irq_lock);
mutex_init(&kvm->slots_lock);
atomic_set(&kvm->users_count, 1);
INIT_LIST_HEAD(&kvm->devices);
r = kvm_init_mmu_notifier(kvm);
if (r)
goto out_err;
spin_lock(&kvm_lock);
list_add(&kvm->vm_list, &vm_list);
spin_unlock(&kvm_lock);
return kvm;
out_err:
cleanup_srcu_struct(&kvm->srcu);
out_err_nosrcu:
hardware_disable_all();
out_err_nodisable:
for (i = 0; i < KVM_NR_BUSES; i++)
kfree(kvm->buses[i]);
kfree(kvm->memslots);
kvm_arch_free_vm(kvm);
return ERR_PTR(r);
}
/*
* Avoid using vmalloc for a small buffer.
* Should not be used when the size is statically known.
*/
void *kvm_kvzalloc(unsigned long size)
{
if (size > PAGE_SIZE)
return vzalloc(size);
else
return kzalloc(size, GFP_KERNEL);
}
void kvm_kvfree(const void *addr)
{
if (is_vmalloc_addr(addr))
vfree(addr);
else
kfree(addr);
}
static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
{
if (!memslot->dirty_bitmap)
return;
kvm_kvfree(memslot->dirty_bitmap);
memslot->dirty_bitmap = NULL;
}
/*
* Free any memory in @free but not in @dont.
*/
static void kvm_free_physmem_slot(struct kvm *kvm, struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
kvm_destroy_dirty_bitmap(free);
kvm_arch_free_memslot(kvm, free, dont);
free->npages = 0;
}
void kvm_free_physmem(struct kvm *kvm)
{
struct kvm_memslots *slots = kvm->memslots;
struct kvm_memory_slot *memslot;
kvm_for_each_memslot(memslot, slots)
kvm_free_physmem_slot(kvm, memslot, NULL);
kfree(kvm->memslots);
}
static void kvm_destroy_devices(struct kvm *kvm)
{
struct list_head *node, *tmp;
list_for_each_safe(node, tmp, &kvm->devices) {
struct kvm_device *dev =
list_entry(node, struct kvm_device, vm_node);
list_del(node);
dev->ops->destroy(dev);
}
}
static void kvm_destroy_vm(struct kvm *kvm)
{
int i;
struct mm_struct *mm = kvm->mm;
kvm_arch_sync_events(kvm);
spin_lock(&kvm_lock);
list_del(&kvm->vm_list);
spin_unlock(&kvm_lock);
kvm_free_irq_routing(kvm);
for (i = 0; i < KVM_NR_BUSES; i++)
kvm_io_bus_destroy(kvm->buses[i]);
kvm_coalesced_mmio_free(kvm);
#if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
#else
kvm_arch_flush_shadow_all(kvm);
#endif
kvm_arch_destroy_vm(kvm);
kvm_destroy_devices(kvm);
kvm_free_physmem(kvm);
cleanup_srcu_struct(&kvm->srcu);
kvm_arch_free_vm(kvm);
hardware_disable_all();
mmdrop(mm);
}
void kvm_get_kvm(struct kvm *kvm)
{
atomic_inc(&kvm->users_count);
}
EXPORT_SYMBOL_GPL(kvm_get_kvm);
void kvm_put_kvm(struct kvm *kvm)
{
if (atomic_dec_and_test(&kvm->users_count))
kvm_destroy_vm(kvm);
}
EXPORT_SYMBOL_GPL(kvm_put_kvm);
static int kvm_vm_release(struct inode *inode, struct file *filp)
{
struct kvm *kvm = filp->private_data;
kvm_irqfd_release(kvm);
kvm_put_kvm(kvm);
return 0;
}
/*
* Allocation size is twice as large as the actual dirty bitmap size.
* See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
*/
static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
{
#ifndef CONFIG_S390
unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
memslot->dirty_bitmap = kvm_kvzalloc(dirty_bytes);
if (!memslot->dirty_bitmap)
return -ENOMEM;
#endif /* !CONFIG_S390 */
return 0;
}
static int cmp_memslot(const void *slot1, const void *slot2)
{
struct kvm_memory_slot *s1, *s2;
s1 = (struct kvm_memory_slot *)slot1;
s2 = (struct kvm_memory_slot *)slot2;
if (s1->npages < s2->npages)
return 1;
if (s1->npages > s2->npages)
return -1;
return 0;
}
/*
* Sort the memslots base on its size, so the larger slots
* will get better fit.
*/
static void sort_memslots(struct kvm_memslots *slots)
{
int i;
sort(slots->memslots, KVM_MEM_SLOTS_NUM,
sizeof(struct kvm_memory_slot), cmp_memslot, NULL);
for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
slots->id_to_index[slots->memslots[i].id] = i;
}
void update_memslots(struct kvm_memslots *slots, struct kvm_memory_slot *new,
u64 last_generation)
{
if (new) {
int id = new->id;
struct kvm_memory_slot *old = id_to_memslot(slots, id);
unsigned long npages = old->npages;
*old = *new;
if (new->npages != npages)
sort_memslots(slots);
}
slots->generation = last_generation + 1;
}
static int check_memory_region_flags(struct kvm_userspace_memory_region *mem)
{
u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
#ifdef KVM_CAP_READONLY_MEM
valid_flags |= KVM_MEM_READONLY;
#endif
if (mem->flags & ~valid_flags)
return -EINVAL;
return 0;
}
static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
struct kvm_memslots *slots, struct kvm_memory_slot *new)
{
struct kvm_memslots *old_memslots = kvm->memslots;
update_memslots(slots, new, kvm->memslots->generation);
rcu_assign_pointer(kvm->memslots, slots);
synchronize_srcu_expedited(&kvm->srcu);
kvm_arch_memslots_updated(kvm);
return old_memslots;
}
/*
* Allocate some memory and give it an address in the guest physical address
* space.
*
* Discontiguous memory is allowed, mostly for framebuffers.
*
* Must be called holding mmap_sem for write.
*/
int __kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem)
{
int r;
gfn_t base_gfn;
unsigned long npages;
struct kvm_memory_slot *slot;
struct kvm_memory_slot old, new;
struct kvm_memslots *slots = NULL, *old_memslots;
enum kvm_mr_change change;
r = check_memory_region_flags(mem);
if (r)
goto out;
r = -EINVAL;
/* General sanity checks */
if (mem->memory_size & (PAGE_SIZE - 1))
goto out;
if (mem->guest_phys_addr & (PAGE_SIZE - 1))
goto out;
/* We can read the guest memory with __xxx_user() later on. */
if ((mem->slot < KVM_USER_MEM_SLOTS) &&
((mem->userspace_addr & (PAGE_SIZE - 1)) ||
!access_ok(VERIFY_WRITE,
(void __user *)(unsigned long)mem->userspace_addr,
mem->memory_size)))
goto out;
if (mem->slot >= KVM_MEM_SLOTS_NUM)
goto out;
if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
goto out;
slot = id_to_memslot(kvm->memslots, mem->slot);
base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
npages = mem->memory_size >> PAGE_SHIFT;
r = -EINVAL;
if (npages > KVM_MEM_MAX_NR_PAGES)
goto out;
if (!npages)
mem->flags &= ~KVM_MEM_LOG_DIRTY_PAGES;
new = old = *slot;
new.id = mem->slot;
new.base_gfn = base_gfn;
new.npages = npages;
new.flags = mem->flags;
r = -EINVAL;
if (npages) {
if (!old.npages)
change = KVM_MR_CREATE;
else { /* Modify an existing slot. */
if ((mem->userspace_addr != old.userspace_addr) ||
(npages != old.npages) ||
((new.flags ^ old.flags) & KVM_MEM_READONLY))
goto out;
if (base_gfn != old.base_gfn)
change = KVM_MR_MOVE;
else if (new.flags != old.flags)
change = KVM_MR_FLAGS_ONLY;
else { /* Nothing to change. */
r = 0;
goto out;
}
}
} else if (old.npages) {
change = KVM_MR_DELETE;
} else /* Modify a non-existent slot: disallowed. */
goto out;
if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
/* Check for overlaps */
r = -EEXIST;
kvm_for_each_memslot(slot, kvm->memslots) {
if ((slot->id >= KVM_USER_MEM_SLOTS) ||
(slot->id == mem->slot))
continue;
if (!((base_gfn + npages <= slot->base_gfn) ||
(base_gfn >= slot->base_gfn + slot->npages)))
goto out;
}
}
/* Free page dirty bitmap if unneeded */
if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
new.dirty_bitmap = NULL;
r = -ENOMEM;
if (change == KVM_MR_CREATE) {
new.userspace_addr = mem->userspace_addr;
if (kvm_arch_create_memslot(kvm, &new, npages))
goto out_free;
}
/* Allocate page dirty bitmap if needed */
if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
if (kvm_create_dirty_bitmap(&new) < 0)
goto out_free;
}
if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
r = -ENOMEM;
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
slot = id_to_memslot(slots, mem->slot);
slot->flags |= KVM_MEMSLOT_INVALID;
old_memslots = install_new_memslots(kvm, slots, NULL);
/* slot was deleted or moved, clear iommu mapping */
kvm_iommu_unmap_pages(kvm, &old);
/* From this point no new shadow pages pointing to a deleted,
* or moved, memslot will be created.
*
* validation of sp->gfn happens in:
* - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
* - kvm_is_visible_gfn (mmu_check_roots)
*/
kvm_arch_flush_shadow_memslot(kvm, slot);
slots = old_memslots;
}
r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
if (r)
goto out_slots;
r = -ENOMEM;
/*
* We can re-use the old_memslots from above, the only difference
* from the currently installed memslots is the invalid flag. This
* will get overwritten by update_memslots anyway.
*/
if (!slots) {
slots = kmemdup(kvm->memslots, sizeof(struct kvm_memslots),
GFP_KERNEL);
if (!slots)
goto out_free;
}
/* actual memory is freed via old in kvm_free_physmem_slot below */
if (change == KVM_MR_DELETE) {
new.dirty_bitmap = NULL;
memset(&new.arch, 0, sizeof(new.arch));
}
old_memslots = install_new_memslots(kvm, slots, &new);
kvm_arch_commit_memory_region(kvm, mem, &old, change);
kvm_free_physmem_slot(kvm, &old, &new);
kfree(old_memslots);
/*
* IOMMU mapping: New slots need to be mapped. Old slots need to be
* un-mapped and re-mapped if their base changes. Since base change
* unmapping is handled above with slot deletion, mapping alone is
* needed here. Anything else the iommu might care about for existing
* slots (size changes, userspace addr changes and read-only flag
* changes) is disallowed above, so any other attribute changes getting
* here can be skipped.
*/
if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
r = kvm_iommu_map_pages(kvm, &new);
return r;
}
return 0;
out_slots:
kfree(slots);
out_free:
kvm_free_physmem_slot(kvm, &new, &old);
out:
return r;
}
EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
int kvm_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem)
{
int r;
mutex_lock(&kvm->slots_lock);
r = __kvm_set_memory_region(kvm, mem);
mutex_unlock(&kvm->slots_lock);
return r;
}
EXPORT_SYMBOL_GPL(kvm_set_memory_region);
int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem)
{
if (mem->slot >= KVM_USER_MEM_SLOTS)
return -EINVAL;
return kvm_set_memory_region(kvm, mem);
}
int kvm_get_dirty_log(struct kvm *kvm,
struct kvm_dirty_log *log, int *is_dirty)
{
struct kvm_memory_slot *memslot;
int r, i;
unsigned long n;
unsigned long any = 0;
r = -EINVAL;
if (log->slot >= KVM_USER_MEM_SLOTS)
goto out;
memslot = id_to_memslot(kvm->memslots, log->slot);
r = -ENOENT;
if (!memslot->dirty_bitmap)
goto out;
n = kvm_dirty_bitmap_bytes(memslot);
for (i = 0; !any && i < n/sizeof(long); ++i)
any = memslot->dirty_bitmap[i];
r = -EFAULT;
if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
goto out;
if (any)
*is_dirty = 1;
r = 0;
out:
return r;
}
EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
bool kvm_largepages_enabled(void)
{
return largepages_enabled;
}
void kvm_disable_largepages(void)
{
largepages_enabled = false;
}
EXPORT_SYMBOL_GPL(kvm_disable_largepages);
struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_memslot(kvm_memslots(kvm), gfn);
}
EXPORT_SYMBOL_GPL(gfn_to_memslot);
int kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
memslot->flags & KVM_MEMSLOT_INVALID)
return 0;
return 1;
}
EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
unsigned long kvm_host_page_size(struct kvm *kvm, gfn_t gfn)
{
struct vm_area_struct *vma;
unsigned long addr, size;
size = PAGE_SIZE;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return PAGE_SIZE;
down_read(¤t->mm->mmap_sem);
vma = find_vma(current->mm, addr);
if (!vma)
goto out;
size = vma_kernel_pagesize(vma);
out:
up_read(¤t->mm->mmap_sem);
return size;
}
static bool memslot_is_readonly(struct kvm_memory_slot *slot)
{
return slot->flags & KVM_MEM_READONLY;
}
static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
gfn_t *nr_pages, bool write)
{
if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
return KVM_HVA_ERR_BAD;
if (memslot_is_readonly(slot) && write)
return KVM_HVA_ERR_RO_BAD;
if (nr_pages)
*nr_pages = slot->npages - (gfn - slot->base_gfn);
return __gfn_to_hva_memslot(slot, gfn);
}
static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
gfn_t *nr_pages)
{
return __gfn_to_hva_many(slot, gfn, nr_pages, true);
}
unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
gfn_t gfn)
{
return gfn_to_hva_many(slot, gfn, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
{
return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_hva);
/*
* If writable is set to false, the hva returned by this function is only
* allowed to be read.
*/
unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
{
struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
if (!kvm_is_error_hva(hva) && writable)
*writable = !memslot_is_readonly(slot);
return hva;
}
static int kvm_read_hva(void *data, void __user *hva, int len)
{
return __copy_from_user(data, hva, len);
}
static int kvm_read_hva_atomic(void *data, void __user *hva, int len)
{
return __copy_from_user_inatomic(data, hva, len);
}
static int get_user_page_nowait(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, int write, struct page **page)
{
int flags = FOLL_TOUCH | FOLL_NOWAIT | FOLL_HWPOISON | FOLL_GET;
if (write)
flags |= FOLL_WRITE;
return __get_user_pages(tsk, mm, start, 1, flags, page, NULL, NULL);
}
static inline int check_user_page_hwpoison(unsigned long addr)
{
int rc, flags = FOLL_TOUCH | FOLL_HWPOISON | FOLL_WRITE;
rc = __get_user_pages(current, current->mm, addr, 1,
flags, NULL, NULL, NULL);
return rc == -EHWPOISON;
}
/*
* The atomic path to get the writable pfn which will be stored in @pfn,
* true indicates success, otherwise false is returned.
*/
static bool hva_to_pfn_fast(unsigned long addr, bool atomic, bool *async,
bool write_fault, bool *writable, pfn_t *pfn)
{
struct page *page[1];
int npages;
if (!(async || atomic))
return false;
/*
* Fast pin a writable pfn only if it is a write fault request
* or the caller allows to map a writable pfn for a read fault
* request.
*/
if (!(write_fault || writable))
return false;
npages = __get_user_pages_fast(addr, 1, 1, page);
if (npages == 1) {
*pfn = page_to_pfn(page[0]);
if (writable)
*writable = true;
return true;
}
return false;
}
/*
* The slow path to get the pfn of the specified host virtual address,
* 1 indicates success, -errno is returned if error is detected.
*/
static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
bool *writable, pfn_t *pfn)
{
struct page *page[1];
int npages = 0;
might_sleep();
if (writable)
*writable = write_fault;
if (async) {
down_read(¤t->mm->mmap_sem);
npages = get_user_page_nowait(current, current->mm,
addr, write_fault, page);
up_read(¤t->mm->mmap_sem);
} else
npages = get_user_pages_fast(addr, 1, write_fault,
page);
if (npages != 1)
return npages;
/* map read fault as writable if possible */
if (unlikely(!write_fault) && writable) {
struct page *wpage[1];
npages = __get_user_pages_fast(addr, 1, 1, wpage);
if (npages == 1) {
*writable = true;
put_page(page[0]);
page[0] = wpage[0];
}
npages = 1;
}
*pfn = page_to_pfn(page[0]);
return npages;
}
static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
{
if (unlikely(!(vma->vm_flags & VM_READ)))
return false;
if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
return false;
return true;
}
/*
* Pin guest page in memory and return its pfn.
* @addr: host virtual address which maps memory to the guest
* @atomic: whether this function can sleep
* @async: whether this function need to wait IO complete if the
* host page is not in the memory
* @write_fault: whether we should get a writable host page
* @writable: whether it allows to map a writable host page for !@write_fault
*
* The function will map a writable host page for these two cases:
* 1): @write_fault = true
* 2): @write_fault = false && @writable, @writable will tell the caller
* whether the mapping is writable.
*/
static pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
bool write_fault, bool *writable)
{
struct vm_area_struct *vma;
pfn_t pfn = 0;
int npages;
/* we can do it either atomically or asynchronously, not both */
BUG_ON(atomic && async);
if (hva_to_pfn_fast(addr, atomic, async, write_fault, writable, &pfn))
return pfn;
if (atomic)
return KVM_PFN_ERR_FAULT;
npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
if (npages == 1)
return pfn;
down_read(¤t->mm->mmap_sem);
if (npages == -EHWPOISON ||
(!async && check_user_page_hwpoison(addr))) {
pfn = KVM_PFN_ERR_HWPOISON;
goto exit;
}
vma = find_vma_intersection(current->mm, addr, addr + 1);
if (vma == NULL)
pfn = KVM_PFN_ERR_FAULT;
else if ((vma->vm_flags & VM_PFNMAP)) {
pfn = ((addr - vma->vm_start) >> PAGE_SHIFT) +
vma->vm_pgoff;
BUG_ON(!kvm_is_mmio_pfn(pfn));
} else {
if (async && vma_is_valid(vma, write_fault))
*async = true;
pfn = KVM_PFN_ERR_FAULT;
}
exit:
up_read(¤t->mm->mmap_sem);
return pfn;
}
static pfn_t
__gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn, bool atomic,
bool *async, bool write_fault, bool *writable)
{
unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
if (addr == KVM_HVA_ERR_RO_BAD)
return KVM_PFN_ERR_RO_FAULT;
if (kvm_is_error_hva(addr))
return KVM_PFN_NOSLOT;
/* Do not map writable pfn in the readonly memslot. */
if (writable && memslot_is_readonly(slot)) {
*writable = false;
writable = NULL;
}
return hva_to_pfn(addr, atomic, async, write_fault,
writable);
}
static pfn_t __gfn_to_pfn(struct kvm *kvm, gfn_t gfn, bool atomic, bool *async,
bool write_fault, bool *writable)
{
struct kvm_memory_slot *slot;
if (async)
*async = false;
slot = gfn_to_memslot(kvm, gfn);
return __gfn_to_pfn_memslot(slot, gfn, atomic, async, write_fault,
writable);
}
pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
pfn_t gfn_to_pfn_async(struct kvm *kvm, gfn_t gfn, bool *async,
bool write_fault, bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, async, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_async);
pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn);
pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
bool *writable)
{
return __gfn_to_pfn(kvm, gfn, false, NULL, write_fault, writable);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
{
return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
}
pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
{
return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
}
EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
int gfn_to_page_many_atomic(struct kvm *kvm, gfn_t gfn, struct page **pages,
int nr_pages)
{
unsigned long addr;
gfn_t entry;
addr = gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, &entry);
if (kvm_is_error_hva(addr))
return -1;
if (entry < nr_pages)
return 0;
return __get_user_pages_fast(addr, nr_pages, 1, pages);
}
EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
static struct page *kvm_pfn_to_page(pfn_t pfn)
{
if (is_error_noslot_pfn(pfn))
return KVM_ERR_PTR_BAD_PAGE;
if (kvm_is_mmio_pfn(pfn)) {
WARN_ON(1);
return KVM_ERR_PTR_BAD_PAGE;
}
return pfn_to_page(pfn);
}
struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
{
pfn_t pfn;
pfn = gfn_to_pfn(kvm, gfn);
return kvm_pfn_to_page(pfn);
}
EXPORT_SYMBOL_GPL(gfn_to_page);
void kvm_release_page_clean(struct page *page)
{
WARN_ON(is_error_page(page));
kvm_release_pfn_clean(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_clean);
void kvm_release_pfn_clean(pfn_t pfn)
{
if (!is_error_noslot_pfn(pfn) && !kvm_is_mmio_pfn(pfn))
put_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
void kvm_release_page_dirty(struct page *page)
{
WARN_ON(is_error_page(page));
kvm_release_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
void kvm_release_pfn_dirty(pfn_t pfn)
{
kvm_set_pfn_dirty(pfn);
kvm_release_pfn_clean(pfn);
}
EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
void kvm_set_page_dirty(struct page *page)
{
kvm_set_pfn_dirty(page_to_pfn(page));
}
EXPORT_SYMBOL_GPL(kvm_set_page_dirty);
void kvm_set_pfn_dirty(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn)) {
struct page *page = pfn_to_page(pfn);
if (!PageReserved(page))
SetPageDirty(page);
}
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
void kvm_set_pfn_accessed(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
mark_page_accessed(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
void kvm_get_pfn(pfn_t pfn)
{
if (!kvm_is_mmio_pfn(pfn))
get_page(pfn_to_page(pfn));
}
EXPORT_SYMBOL_GPL(kvm_get_pfn);
static int next_segment(unsigned long len, int offset)
{
if (len > PAGE_SIZE - offset)
return PAGE_SIZE - offset;
else
return len;
}
int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva_prot(kvm, gfn, NULL);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = kvm_read_hva(data, (void __user *)addr + offset, len);
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest_page);
int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest);
int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
unsigned long len)
{
int r;
unsigned long addr;
gfn_t gfn = gpa >> PAGE_SHIFT;
int offset = offset_in_page(gpa);
addr = gfn_to_hva_prot(kvm, gfn, NULL);
if (kvm_is_error_hva(addr))
return -EFAULT;
pagefault_disable();
r = kvm_read_hva_atomic(data, (void __user *)addr + offset, len);
pagefault_enable();
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL(kvm_read_guest_atomic);
int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn, const void *data,
int offset, int len)
{
int r;
unsigned long addr;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return -EFAULT;
r = __copy_to_user((void __user *)addr + offset, data, len);
if (r)
return -EFAULT;
mark_page_dirty(kvm, gfn);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_page);
int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
data += seg;
++gfn;
}
return 0;
}
int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
gpa_t gpa, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int offset = offset_in_page(gpa);
gfn_t start_gfn = gpa >> PAGE_SHIFT;
gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
gfn_t nr_pages_avail;
ghc->gpa = gpa;
ghc->generation = slots->generation;
ghc->len = len;
ghc->memslot = gfn_to_memslot(kvm, start_gfn);
ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, &nr_pages_avail);
if (!kvm_is_error_hva(ghc->hva) && nr_pages_avail >= nr_pages_needed) {
ghc->hva += offset;
} else {
/*
* If the requested region crosses two memslots, we still
* verify that the entire region is valid here.
*/
while (start_gfn <= end_gfn) {
ghc->memslot = gfn_to_memslot(kvm, start_gfn);
ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
&nr_pages_avail);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
start_gfn += nr_pages_avail;
}
/* Use the slow path for cross page reads and writes. */
ghc->memslot = NULL;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
void *data, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int r;
BUG_ON(len > ghc->len);
if (slots->generation != ghc->generation)
kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
if (unlikely(!ghc->memslot))
return kvm_write_guest(kvm, ghc->gpa, data, len);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
r = __copy_to_user((void __user *)ghc->hva, data, len);
if (r)
return -EFAULT;
mark_page_dirty_in_slot(kvm, ghc->memslot, ghc->gpa >> PAGE_SHIFT);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
void *data, unsigned long len)
{
struct kvm_memslots *slots = kvm_memslots(kvm);
int r;
BUG_ON(len > ghc->len);
if (slots->generation != ghc->generation)
kvm_gfn_to_hva_cache_init(kvm, ghc, ghc->gpa, ghc->len);
if (unlikely(!ghc->memslot))
return kvm_read_guest(kvm, ghc->gpa, data, len);
if (kvm_is_error_hva(ghc->hva))
return -EFAULT;
r = __copy_from_user(data, (void __user *)ghc->hva, len);
if (r)
return -EFAULT;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
{
const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
}
EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
int seg;
int offset = offset_in_page(gpa);
int ret;
while ((seg = next_segment(len, offset)) != 0) {
ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
if (ret < 0)
return ret;
offset = 0;
len -= seg;
++gfn;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_clear_guest);
void mark_page_dirty_in_slot(struct kvm *kvm, struct kvm_memory_slot *memslot,
gfn_t gfn)
{
if (memslot && memslot->dirty_bitmap) {
unsigned long rel_gfn = gfn - memslot->base_gfn;
set_bit_le(rel_gfn, memslot->dirty_bitmap);
}
}
void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *memslot;
memslot = gfn_to_memslot(kvm, gfn);
mark_page_dirty_in_slot(kvm, memslot, gfn);
}
EXPORT_SYMBOL_GPL(mark_page_dirty);
/*
* The vCPU has executed a HLT instruction with in-kernel mode enabled.
*/
void kvm_vcpu_block(struct kvm_vcpu *vcpu)
{
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
if (kvm_arch_vcpu_runnable(vcpu)) {
kvm_make_request(KVM_REQ_UNHALT, vcpu);
break;
}
if (kvm_cpu_has_pending_timer(vcpu))
break;
if (signal_pending(current))
break;
schedule();
}
finish_wait(&vcpu->wq, &wait);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_block);
#ifndef CONFIG_S390
/*
* Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
*/
void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
{
int me;
int cpu = vcpu->cpu;
wait_queue_head_t *wqp;
wqp = kvm_arch_vcpu_wq(vcpu);
if (waitqueue_active(wqp)) {
wake_up_interruptible(wqp);
++vcpu->stat.halt_wakeup;
}
me = get_cpu();
if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
if (kvm_arch_vcpu_should_kick(vcpu))
smp_send_reschedule(cpu);
put_cpu();
}
EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
#endif /* !CONFIG_S390 */
void kvm_resched(struct kvm_vcpu *vcpu)
{
if (!need_resched())
return;
cond_resched();
}
EXPORT_SYMBOL_GPL(kvm_resched);
bool kvm_vcpu_yield_to(struct kvm_vcpu *target)
{
struct pid *pid;
struct task_struct *task = NULL;
bool ret = false;
rcu_read_lock();
pid = rcu_dereference(target->pid);
if (pid)
task = get_pid_task(target->pid, PIDTYPE_PID);
rcu_read_unlock();
if (!task)
return ret;
if (task->flags & PF_VCPU) {
put_task_struct(task);
return ret;
}
ret = yield_to(task, 1);
put_task_struct(task);
return ret;
}
EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
#ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
/*
* Helper that checks whether a VCPU is eligible for directed yield.
* Most eligible candidate to yield is decided by following heuristics:
*
* (a) VCPU which has not done pl-exit or cpu relax intercepted recently
* (preempted lock holder), indicated by @in_spin_loop.
* Set at the beiginning and cleared at the end of interception/PLE handler.
*
* (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
* chance last time (mostly it has become eligible now since we have probably
* yielded to lockholder in last iteration. This is done by toggling
* @dy_eligible each time a VCPU checked for eligibility.)
*
* Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
* to preempted lock-holder could result in wrong VCPU selection and CPU
* burning. Giving priority for a potential lock-holder increases lock
* progress.
*
* Since algorithm is based on heuristics, accessing another VCPU data without
* locking does not harm. It may result in trying to yield to same VCPU, fail
* and continue with next VCPU and so on.
*/
bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
{
bool eligible;
eligible = !vcpu->spin_loop.in_spin_loop ||
(vcpu->spin_loop.in_spin_loop &&
vcpu->spin_loop.dy_eligible);
if (vcpu->spin_loop.in_spin_loop)
kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
return eligible;
}
#endif
void kvm_vcpu_on_spin(struct kvm_vcpu *me)
{
struct kvm *kvm = me->kvm;
struct kvm_vcpu *vcpu;
int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
int yielded = 0;
int try = 3;
int pass;
int i;
kvm_vcpu_set_in_spin_loop(me, true);
/*
* We boost the priority of a VCPU that is runnable but not
* currently running, because it got preempted by something
* else and called schedule in __vcpu_run. Hopefully that
* VCPU is holding the lock that we need and will release it.
* We approximate round-robin by starting at the last boosted VCPU.
*/
for (pass = 0; pass < 2 && !yielded && try; pass++) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (!pass && i <= last_boosted_vcpu) {
i = last_boosted_vcpu;
continue;
} else if (pass && i > last_boosted_vcpu)
break;
if (!ACCESS_ONCE(vcpu->preempted))
continue;
if (vcpu == me)
continue;
if (waitqueue_active(&vcpu->wq))
continue;
if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
continue;
yielded = kvm_vcpu_yield_to(vcpu);
if (yielded > 0) {
kvm->last_boosted_vcpu = i;
break;
} else if (yielded < 0) {
try--;
if (!try)
break;
}
}
}
kvm_vcpu_set_in_spin_loop(me, false);
/* Ensure vcpu is not eligible during next spinloop */
kvm_vcpu_set_dy_eligible(me, false);
}
EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
static int kvm_vcpu_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct kvm_vcpu *vcpu = vma->vm_file->private_data;
struct page *page;
if (vmf->pgoff == 0)
page = virt_to_page(vcpu->run);
#ifdef CONFIG_X86
else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
page = virt_to_page(vcpu->arch.pio_data);
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
#endif
else
return kvm_arch_vcpu_fault(vcpu, vmf);
get_page(page);
vmf->page = page;
return 0;
}
static const struct vm_operations_struct kvm_vcpu_vm_ops = {
.fault = kvm_vcpu_fault,
};
static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
{
vma->vm_ops = &kvm_vcpu_vm_ops;
return 0;
}
static int kvm_vcpu_release(struct inode *inode, struct file *filp)
{
struct kvm_vcpu *vcpu = filp->private_data;
kvm_put_kvm(vcpu->kvm);
return 0;
}
static struct file_operations kvm_vcpu_fops = {
.release = kvm_vcpu_release,
.unlocked_ioctl = kvm_vcpu_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_vcpu_compat_ioctl,
#endif
.mmap = kvm_vcpu_mmap,
.llseek = noop_llseek,
};
/*
* Allocates an inode for the vcpu.
*/
static int create_vcpu_fd(struct kvm_vcpu *vcpu)
{
return anon_inode_getfd("kvm-vcpu", &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
}
/*
* Creates some virtual cpus. Good luck creating more than one.
*/
static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
{
int r;
struct kvm_vcpu *vcpu, *v;
vcpu = kvm_arch_vcpu_create(kvm, id);
if (IS_ERR(vcpu))
return PTR_ERR(vcpu);
preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
r = kvm_arch_vcpu_setup(vcpu);
if (r)
goto vcpu_destroy;
mutex_lock(&kvm->lock);
if (!kvm_vcpu_compatible(vcpu)) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
if (atomic_read(&kvm->online_vcpus) == KVM_MAX_VCPUS) {
r = -EINVAL;
goto unlock_vcpu_destroy;
}
kvm_for_each_vcpu(r, v, kvm)
if (v->vcpu_id == id) {
r = -EEXIST;
goto unlock_vcpu_destroy;
}
BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
/* Now it's all set up, let userspace reach it */
kvm_get_kvm(kvm);
r = create_vcpu_fd(vcpu);
if (r < 0) {
kvm_put_kvm(kvm);
goto unlock_vcpu_destroy;
}
kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
smp_wmb();
atomic_inc(&kvm->online_vcpus);
mutex_unlock(&kvm->lock);
kvm_arch_vcpu_postcreate(vcpu);
return r;
unlock_vcpu_destroy:
mutex_unlock(&kvm->lock);
vcpu_destroy:
kvm_arch_vcpu_destroy(vcpu);
return r;
}
static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
{
if (sigset) {
sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
vcpu->sigset_active = 1;
vcpu->sigset = *sigset;
} else
vcpu->sigset_active = 0;
return 0;
}
static long kvm_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
struct kvm_fpu *fpu = NULL;
struct kvm_sregs *kvm_sregs = NULL;
if (vcpu->kvm->mm != current->mm)
return -EIO;
#if defined(CONFIG_S390) || defined(CONFIG_PPC) || defined(CONFIG_MIPS)
/*
* Special cases: vcpu ioctls that are asynchronous to vcpu execution,
* so vcpu_load() would break it.
*/
if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT)
return kvm_arch_vcpu_ioctl(filp, ioctl, arg);
#endif
r = vcpu_load(vcpu);
if (r)
return r;
switch (ioctl) {
case KVM_RUN:
r = -EINVAL;
if (arg)
goto out;
r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
break;
case KVM_GET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
if (!kvm_regs)
goto out;
r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
if (r)
goto out_free1;
r = -EFAULT;
if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
goto out_free1;
r = 0;
out_free1:
kfree(kvm_regs);
break;
}
case KVM_SET_REGS: {
struct kvm_regs *kvm_regs;
r = -ENOMEM;
kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
if (IS_ERR(kvm_regs)) {
r = PTR_ERR(kvm_regs);
goto out;
}
r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
kfree(kvm_regs);
break;
}
case KVM_GET_SREGS: {
kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
r = -ENOMEM;
if (!kvm_sregs)
goto out;
r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
goto out;
r = 0;
break;
}
case KVM_SET_SREGS: {
kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
if (IS_ERR(kvm_sregs)) {
r = PTR_ERR(kvm_sregs);
kvm_sregs = NULL;
goto out;
}
r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
break;
}
case KVM_GET_MP_STATE: {
struct kvm_mp_state mp_state;
r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &mp_state, sizeof mp_state))
goto out;
r = 0;
break;
}
case KVM_SET_MP_STATE: {
struct kvm_mp_state mp_state;
r = -EFAULT;
if (copy_from_user(&mp_state, argp, sizeof mp_state))
goto out;
r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
break;
}
case KVM_TRANSLATE: {
struct kvm_translation tr;
r = -EFAULT;
if (copy_from_user(&tr, argp, sizeof tr))
goto out;
r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &tr, sizeof tr))
goto out;
r = 0;
break;
}
case KVM_SET_GUEST_DEBUG: {
struct kvm_guest_debug dbg;
r = -EFAULT;
if (copy_from_user(&dbg, argp, sizeof dbg))
goto out;
r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
break;
}
case KVM_SET_SIGNAL_MASK: {
struct kvm_signal_mask __user *sigmask_arg = argp;
struct kvm_signal_mask kvm_sigmask;
sigset_t sigset, *p;
p = NULL;
if (argp) {
r = -EFAULT;
if (copy_from_user(&kvm_sigmask, argp,
sizeof kvm_sigmask))
goto out;
r = -EINVAL;
if (kvm_sigmask.len != sizeof sigset)
goto out;
r = -EFAULT;
if (copy_from_user(&sigset, sigmask_arg->sigset,
sizeof sigset))
goto out;
p = &sigset;
}
r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
break;
}
case KVM_GET_FPU: {
fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
r = -ENOMEM;
if (!fpu)
goto out;
r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
goto out;
r = 0;
break;
}
case KVM_SET_FPU: {
fpu = memdup_user(argp, sizeof(*fpu));
if (IS_ERR(fpu)) {
r = PTR_ERR(fpu);
fpu = NULL;
goto out;
}
r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
break;
}
default:
r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
}
out:
vcpu_put(vcpu);
kfree(fpu);
kfree(kvm_sregs);
return r;
}
#ifdef CONFIG_COMPAT
static long kvm_vcpu_compat_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = compat_ptr(arg);
int r;
if (vcpu->kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_SET_SIGNAL_MASK: {
struct kvm_signal_mask __user *sigmask_arg = argp;
struct kvm_signal_mask kvm_sigmask;
compat_sigset_t csigset;
sigset_t sigset;
if (argp) {
r = -EFAULT;
if (copy_from_user(&kvm_sigmask, argp,
sizeof kvm_sigmask))
goto out;
r = -EINVAL;
if (kvm_sigmask.len != sizeof csigset)
goto out;
r = -EFAULT;
if (copy_from_user(&csigset, sigmask_arg->sigset,
sizeof csigset))
goto out;
sigset_from_compat(&sigset, &csigset);
r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
} else
r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
break;
}
default:
r = kvm_vcpu_ioctl(filp, ioctl, arg);
}
out:
return r;
}
#endif
static int kvm_device_ioctl_attr(struct kvm_device *dev,
int (*accessor)(struct kvm_device *dev,
struct kvm_device_attr *attr),
unsigned long arg)
{
struct kvm_device_attr attr;
if (!accessor)
return -EPERM;
if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
return -EFAULT;
return accessor(dev, &attr);
}
static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
unsigned long arg)
{
struct kvm_device *dev = filp->private_data;
switch (ioctl) {
case KVM_SET_DEVICE_ATTR:
return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
case KVM_GET_DEVICE_ATTR:
return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
case KVM_HAS_DEVICE_ATTR:
return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
default:
if (dev->ops->ioctl)
return dev->ops->ioctl(dev, ioctl, arg);
return -ENOTTY;
}
}
static int kvm_device_release(struct inode *inode, struct file *filp)
{
struct kvm_device *dev = filp->private_data;
struct kvm *kvm = dev->kvm;
kvm_put_kvm(kvm);
return 0;
}
static const struct file_operations kvm_device_fops = {
.unlocked_ioctl = kvm_device_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_device_ioctl,
#endif
.release = kvm_device_release,
};
struct kvm_device *kvm_device_from_filp(struct file *filp)
{
if (filp->f_op != &kvm_device_fops)
return NULL;
return filp->private_data;
}
static int kvm_ioctl_create_device(struct kvm *kvm,
struct kvm_create_device *cd)
{
struct kvm_device_ops *ops = NULL;
struct kvm_device *dev;
bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
int ret;
switch (cd->type) {
#ifdef CONFIG_KVM_MPIC
case KVM_DEV_TYPE_FSL_MPIC_20:
case KVM_DEV_TYPE_FSL_MPIC_42:
ops = &kvm_mpic_ops;
break;
#endif
#ifdef CONFIG_KVM_XICS
case KVM_DEV_TYPE_XICS:
ops = &kvm_xics_ops;
break;
#endif
#ifdef CONFIG_KVM_VFIO
case KVM_DEV_TYPE_VFIO:
ops = &kvm_vfio_ops;
break;
#endif
default:
return -ENODEV;
}
if (test)
return 0;
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->ops = ops;
dev->kvm = kvm;
ret = ops->create(dev, cd->type);
if (ret < 0) {
kfree(dev);
return ret;
}
ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
if (ret < 0) {
ops->destroy(dev);
return ret;
}
list_add(&dev->vm_node, &kvm->devices);
kvm_get_kvm(kvm);
cd->fd = ret;
return 0;
}
static long kvm_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_CREATE_VCPU:
r = kvm_vm_ioctl_create_vcpu(kvm, arg);
break;
case KVM_SET_USER_MEMORY_REGION: {
struct kvm_userspace_memory_region kvm_userspace_mem;
r = -EFAULT;
if (copy_from_user(&kvm_userspace_mem, argp,
sizeof kvm_userspace_mem))
goto out;
r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
break;
}
case KVM_GET_DIRTY_LOG: {
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&log, argp, sizeof log))
goto out;
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
break;
}
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
case KVM_REGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
break;
}
case KVM_UNREGISTER_COALESCED_MMIO: {
struct kvm_coalesced_mmio_zone zone;
r = -EFAULT;
if (copy_from_user(&zone, argp, sizeof zone))
goto out;
r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
break;
}
#endif
case KVM_IRQFD: {
struct kvm_irqfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_irqfd(kvm, &data);
break;
}
case KVM_IOEVENTFD: {
struct kvm_ioeventfd data;
r = -EFAULT;
if (copy_from_user(&data, argp, sizeof data))
goto out;
r = kvm_ioeventfd(kvm, &data);
break;
}
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_SET_BOOT_CPU_ID:
r = 0;
mutex_lock(&kvm->lock);
if (atomic_read(&kvm->online_vcpus) != 0)
r = -EBUSY;
else
kvm->bsp_vcpu_id = arg;
mutex_unlock(&kvm->lock);
break;
#endif
#ifdef CONFIG_HAVE_KVM_MSI
case KVM_SIGNAL_MSI: {
struct kvm_msi msi;
r = -EFAULT;
if (copy_from_user(&msi, argp, sizeof msi))
goto out;
r = kvm_send_userspace_msi(kvm, &msi);
break;
}
#endif
#ifdef __KVM_HAVE_IRQ_LINE
case KVM_IRQ_LINE_STATUS:
case KVM_IRQ_LINE: {
struct kvm_irq_level irq_event;
r = -EFAULT;
if (copy_from_user(&irq_event, argp, sizeof irq_event))
goto out;
r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
ioctl == KVM_IRQ_LINE_STATUS);
if (r)
goto out;
r = -EFAULT;
if (ioctl == KVM_IRQ_LINE_STATUS) {
if (copy_to_user(argp, &irq_event, sizeof irq_event))
goto out;
}
r = 0;
break;
}
#endif
#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
case KVM_SET_GSI_ROUTING: {
struct kvm_irq_routing routing;
struct kvm_irq_routing __user *urouting;
struct kvm_irq_routing_entry *entries;
r = -EFAULT;
if (copy_from_user(&routing, argp, sizeof(routing)))
goto out;
r = -EINVAL;
if (routing.nr >= KVM_MAX_IRQ_ROUTES)
goto out;
if (routing.flags)
goto out;
r = -ENOMEM;
entries = vmalloc(routing.nr * sizeof(*entries));
if (!entries)
goto out;
r = -EFAULT;
urouting = argp;
if (copy_from_user(entries, urouting->entries,
routing.nr * sizeof(*entries)))
goto out_free_irq_routing;
r = kvm_set_irq_routing(kvm, entries, routing.nr,
routing.flags);
out_free_irq_routing:
vfree(entries);
break;
}
#endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
case KVM_CREATE_DEVICE: {
struct kvm_create_device cd;
r = -EFAULT;
if (copy_from_user(&cd, argp, sizeof(cd)))
goto out;
r = kvm_ioctl_create_device(kvm, &cd);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &cd, sizeof(cd)))
goto out;
r = 0;
break;
}
default:
r = kvm_arch_vm_ioctl(filp, ioctl, arg);
if (r == -ENOTTY)
r = kvm_vm_ioctl_assigned_device(kvm, ioctl, arg);
}
out:
return r;
}
#ifdef CONFIG_COMPAT
struct compat_kvm_dirty_log {
__u32 slot;
__u32 padding1;
union {
compat_uptr_t dirty_bitmap; /* one bit per page */
__u64 padding2;
};
};
static long kvm_vm_compat_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
int r;
if (kvm->mm != current->mm)
return -EIO;
switch (ioctl) {
case KVM_GET_DIRTY_LOG: {
struct compat_kvm_dirty_log compat_log;
struct kvm_dirty_log log;
r = -EFAULT;
if (copy_from_user(&compat_log, (void __user *)arg,
sizeof(compat_log)))
goto out;
log.slot = compat_log.slot;
log.padding1 = compat_log.padding1;
log.padding2 = compat_log.padding2;
log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
break;
}
default:
r = kvm_vm_ioctl(filp, ioctl, arg);
}
out:
return r;
}
#endif
static struct file_operations kvm_vm_fops = {
.release = kvm_vm_release,
.unlocked_ioctl = kvm_vm_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = kvm_vm_compat_ioctl,
#endif
.llseek = noop_llseek,
};
static int kvm_dev_ioctl_create_vm(unsigned long type)
{
int r;
struct kvm *kvm;
kvm = kvm_create_vm(type);
if (IS_ERR(kvm))
return PTR_ERR(kvm);
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r = kvm_coalesced_mmio_init(kvm);
if (r < 0) {
kvm_put_kvm(kvm);
return r;
}
#endif
r = anon_inode_getfd("kvm-vm", &kvm_vm_fops, kvm, O_RDWR | O_CLOEXEC);
if (r < 0)
kvm_put_kvm(kvm);
return r;
}
static long kvm_dev_ioctl_check_extension_generic(long arg)
{
switch (arg) {
case KVM_CAP_USER_MEMORY:
case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
#ifdef CONFIG_KVM_APIC_ARCHITECTURE
case KVM_CAP_SET_BOOT_CPU_ID:
#endif
case KVM_CAP_INTERNAL_ERROR_DATA:
#ifdef CONFIG_HAVE_KVM_MSI
case KVM_CAP_SIGNAL_MSI:
#endif
#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
case KVM_CAP_IRQFD_RESAMPLE:
#endif
return 1;
#ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
case KVM_CAP_IRQ_ROUTING:
return KVM_MAX_IRQ_ROUTES;
#endif
default:
break;
}
return kvm_dev_ioctl_check_extension(arg);
}
static long kvm_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
long r = -EINVAL;
switch (ioctl) {
case KVM_GET_API_VERSION:
r = -EINVAL;
if (arg)
goto out;
r = KVM_API_VERSION;
break;
case KVM_CREATE_VM:
r = kvm_dev_ioctl_create_vm(arg);
break;
case KVM_CHECK_EXTENSION:
r = kvm_dev_ioctl_check_extension_generic(arg);
break;
case KVM_GET_VCPU_MMAP_SIZE:
r = -EINVAL;
if (arg)
goto out;
r = PAGE_SIZE; /* struct kvm_run */
#ifdef CONFIG_X86
r += PAGE_SIZE; /* pio data page */
#endif
#ifdef KVM_COALESCED_MMIO_PAGE_OFFSET
r += PAGE_SIZE; /* coalesced mmio ring page */
#endif
break;
case KVM_TRACE_ENABLE:
case KVM_TRACE_PAUSE:
case KVM_TRACE_DISABLE:
r = -EOPNOTSUPP;
break;
default:
return kvm_arch_dev_ioctl(filp, ioctl, arg);
}
out:
return r;
}
static struct file_operations kvm_chardev_ops = {
.unlocked_ioctl = kvm_dev_ioctl,
.compat_ioctl = kvm_dev_ioctl,
.llseek = noop_llseek,
};
static struct miscdevice kvm_dev = {
KVM_MINOR,
"kvm",
&kvm_chardev_ops,
};
static void hardware_enable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
int r;
if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_set_cpu(cpu, cpus_hardware_enabled);
r = kvm_arch_hardware_enable(NULL);
if (r) {
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
atomic_inc(&hardware_enable_failed);
printk(KERN_INFO "kvm: enabling virtualization on "
"CPU%d failed\n", cpu);
}
}
static void hardware_enable(void)
{
raw_spin_lock(&kvm_count_lock);
if (kvm_usage_count)
hardware_enable_nolock(NULL);
raw_spin_unlock(&kvm_count_lock);
}
static void hardware_disable_nolock(void *junk)
{
int cpu = raw_smp_processor_id();
if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
return;
cpumask_clear_cpu(cpu, cpus_hardware_enabled);
kvm_arch_hardware_disable(NULL);
}
static void hardware_disable(void)
{
raw_spin_lock(&kvm_count_lock);
if (kvm_usage_count)
hardware_disable_nolock(NULL);
raw_spin_unlock(&kvm_count_lock);
}
static void hardware_disable_all_nolock(void)
{
BUG_ON(!kvm_usage_count);
kvm_usage_count--;
if (!kvm_usage_count)
on_each_cpu(hardware_disable_nolock, NULL, 1);
}
static void hardware_disable_all(void)
{
raw_spin_lock(&kvm_count_lock);
hardware_disable_all_nolock();
raw_spin_unlock(&kvm_count_lock);
}
static int hardware_enable_all(void)
{
int r = 0;
raw_spin_lock(&kvm_count_lock);
kvm_usage_count++;
if (kvm_usage_count == 1) {
atomic_set(&hardware_enable_failed, 0);
on_each_cpu(hardware_enable_nolock, NULL, 1);
if (atomic_read(&hardware_enable_failed)) {
hardware_disable_all_nolock();
r = -EBUSY;
}
}
raw_spin_unlock(&kvm_count_lock);
return r;
}
static int kvm_cpu_hotplug(struct notifier_block *notifier, unsigned long val,
void *v)
{
int cpu = (long)v;
val &= ~CPU_TASKS_FROZEN;
switch (val) {
case CPU_DYING:
printk(KERN_INFO "kvm: disabling virtualization on CPU%d\n",
cpu);
hardware_disable();
break;
case CPU_STARTING:
printk(KERN_INFO "kvm: enabling virtualization on CPU%d\n",
cpu);
hardware_enable();
break;
}
return NOTIFY_OK;
}
static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
void *v)
{
/*
* Some (well, at least mine) BIOSes hang on reboot if
* in vmx root mode.
*
* And Intel TXT required VMX off for all cpu when system shutdown.
*/
printk(KERN_INFO "kvm: exiting hardware virtualization\n");
kvm_rebooting = true;
on_each_cpu(hardware_disable_nolock, NULL, 1);
return NOTIFY_OK;
}
static struct notifier_block kvm_reboot_notifier = {
.notifier_call = kvm_reboot,
.priority = 0,
};
static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
{
int i;
for (i = 0; i < bus->dev_count; i++) {
struct kvm_io_device *pos = bus->range[i].dev;
kvm_iodevice_destructor(pos);
}
kfree(bus);
}
static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
const struct kvm_io_range *r2)
{
if (r1->addr < r2->addr)
return -1;
if (r1->addr + r1->len > r2->addr + r2->len)
return 1;
return 0;
}
static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
{
return kvm_io_bus_cmp(p1, p2);
}
static int kvm_io_bus_insert_dev(struct kvm_io_bus *bus, struct kvm_io_device *dev,
gpa_t addr, int len)
{
bus->range[bus->dev_count++] = (struct kvm_io_range) {
.addr = addr,
.len = len,
.dev = dev,
};
sort(bus->range, bus->dev_count, sizeof(struct kvm_io_range),
kvm_io_bus_sort_cmp, NULL);
return 0;
}
static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
gpa_t addr, int len)
{
struct kvm_io_range *range, key;
int off;
key = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
range = bsearch(&key, bus->range, bus->dev_count,
sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
if (range == NULL)
return -ENOENT;
off = range - bus->range;
while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
off--;
return off;
}
static int __kvm_io_bus_write(struct kvm_io_bus *bus,
struct kvm_io_range *range, const void *val)
{
int idx;
idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
if (idx < 0)
return -EOPNOTSUPP;
while (idx < bus->dev_count &&
kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
if (!kvm_iodevice_write(bus->range[idx].dev, range->addr,
range->len, val))
return idx;
idx++;
}
return -EOPNOTSUPP;
}
/* kvm_io_bus_write - called under kvm->slots_lock */
int kvm_io_bus_write(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, const void *val)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
int r;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
r = __kvm_io_bus_write(bus, &range, val);
return r < 0 ? r : 0;
}
/* kvm_io_bus_write_cookie - called under kvm->slots_lock */
int kvm_io_bus_write_cookie(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, const void *val, long cookie)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
/* First try the device referenced by cookie. */
if ((cookie >= 0) && (cookie < bus->dev_count) &&
(kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
if (!kvm_iodevice_write(bus->range[cookie].dev, addr, len,
val))
return cookie;
/*
* cookie contained garbage; fall back to search and return the
* correct cookie value.
*/
return __kvm_io_bus_write(bus, &range, val);
}
static int __kvm_io_bus_read(struct kvm_io_bus *bus, struct kvm_io_range *range,
void *val)
{
int idx;
idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
if (idx < 0)
return -EOPNOTSUPP;
while (idx < bus->dev_count &&
kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
if (!kvm_iodevice_read(bus->range[idx].dev, range->addr,
range->len, val))
return idx;
idx++;
}
return -EOPNOTSUPP;
}
/* kvm_io_bus_read - called under kvm->slots_lock */
int kvm_io_bus_read(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, void *val)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
int r;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
r = __kvm_io_bus_read(bus, &range, val);
return r < 0 ? r : 0;
}
/* kvm_io_bus_read_cookie - called under kvm->slots_lock */
int kvm_io_bus_read_cookie(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, void *val, long cookie)
{
struct kvm_io_bus *bus;
struct kvm_io_range range;
range = (struct kvm_io_range) {
.addr = addr,
.len = len,
};
bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
/* First try the device referenced by cookie. */
if ((cookie >= 0) && (cookie < bus->dev_count) &&
(kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
if (!kvm_iodevice_read(bus->range[cookie].dev, addr, len,
val))
return cookie;
/*
* cookie contained garbage; fall back to search and return the
* correct cookie value.
*/
return __kvm_io_bus_read(bus, &range, val);
}
/* Caller must hold slots_lock. */
int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
int len, struct kvm_io_device *dev)
{
struct kvm_io_bus *new_bus, *bus;
bus = kvm->buses[bus_idx];
/* exclude ioeventfd which is limited by maximum fd */
if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
return -ENOSPC;
new_bus = kzalloc(sizeof(*bus) + ((bus->dev_count + 1) *
sizeof(struct kvm_io_range)), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
memcpy(new_bus, bus, sizeof(*bus) + (bus->dev_count *
sizeof(struct kvm_io_range)));
kvm_io_bus_insert_dev(new_bus, dev, addr, len);
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return 0;
}
/* Caller must hold slots_lock. */
int kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
struct kvm_io_device *dev)
{
int i, r;
struct kvm_io_bus *new_bus, *bus;
bus = kvm->buses[bus_idx];
r = -ENOENT;
for (i = 0; i < bus->dev_count; i++)
if (bus->range[i].dev == dev) {
r = 0;
break;
}
if (r)
return r;
new_bus = kzalloc(sizeof(*bus) + ((bus->dev_count - 1) *
sizeof(struct kvm_io_range)), GFP_KERNEL);
if (!new_bus)
return -ENOMEM;
memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
new_bus->dev_count--;
memcpy(new_bus->range + i, bus->range + i + 1,
(new_bus->dev_count - i) * sizeof(struct kvm_io_range));
rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
synchronize_srcu_expedited(&kvm->srcu);
kfree(bus);
return r;
}
static struct notifier_block kvm_cpu_notifier = {
.notifier_call = kvm_cpu_hotplug,
};
static int vm_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
*val = 0;
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
*val += *(u32 *)((void *)kvm + offset);
spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, NULL, "%llu\n");
static int vcpu_stat_get(void *_offset, u64 *val)
{
unsigned offset = (long)_offset;
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
*val = 0;
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
kvm_for_each_vcpu(i, vcpu, kvm)
*val += *(u32 *)((void *)vcpu + offset);
spin_unlock(&kvm_lock);
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, NULL, "%llu\n");
static const struct file_operations *stat_fops[] = {
[KVM_STAT_VCPU] = &vcpu_stat_fops,
[KVM_STAT_VM] = &vm_stat_fops,
};
static int kvm_init_debug(void)
{
int r = -EEXIST;
struct kvm_stats_debugfs_item *p;
kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
if (kvm_debugfs_dir == NULL)
goto out;
for (p = debugfs_entries; p->name; ++p) {
p->dentry = debugfs_create_file(p->name, 0444, kvm_debugfs_dir,
(void *)(long)p->offset,
stat_fops[p->kind]);
if (p->dentry == NULL)
goto out_dir;
}
return 0;
out_dir:
debugfs_remove_recursive(kvm_debugfs_dir);
out:
return r;
}
static void kvm_exit_debug(void)
{
struct kvm_stats_debugfs_item *p;
for (p = debugfs_entries; p->name; ++p)
debugfs_remove(p->dentry);
debugfs_remove(kvm_debugfs_dir);
}
static int kvm_suspend(void)
{
if (kvm_usage_count)
hardware_disable_nolock(NULL);
return 0;
}
static void kvm_resume(void)
{
if (kvm_usage_count) {
WARN_ON(raw_spin_is_locked(&kvm_count_lock));
hardware_enable_nolock(NULL);
}
}
static struct syscore_ops kvm_syscore_ops = {
.suspend = kvm_suspend,
.resume = kvm_resume,
};
static inline
struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
{
return container_of(pn, struct kvm_vcpu, preempt_notifier);
}
static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
if (vcpu->preempted)
vcpu->preempted = false;
kvm_arch_vcpu_load(vcpu, cpu);
}
static void kvm_sched_out(struct preempt_notifier *pn,
struct task_struct *next)
{
struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
if (current->state == TASK_RUNNING)
vcpu->preempted = true;
kvm_arch_vcpu_put(vcpu);
}
int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
struct module *module)
{
int r;
int cpu;
r = kvm_arch_init(opaque);
if (r)
goto out_fail;
/*
* kvm_arch_init makes sure there's at most one caller
* for architectures that support multiple implementations,
* like intel and amd on x86.
* kvm_arch_init must be called before kvm_irqfd_init to avoid creating
* conflicts in case kvm is already setup for another implementation.
*/
r = kvm_irqfd_init();
if (r)
goto out_irqfd;
if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
r = -ENOMEM;
goto out_free_0;
}
r = kvm_arch_hardware_setup();
if (r < 0)
goto out_free_0a;
for_each_online_cpu(cpu) {
smp_call_function_single(cpu,
kvm_arch_check_processor_compat,
&r, 1);
if (r < 0)
goto out_free_1;
}
r = register_cpu_notifier(&kvm_cpu_notifier);
if (r)
goto out_free_2;
register_reboot_notifier(&kvm_reboot_notifier);
/* A kmem cache lets us meet the alignment requirements of fx_save. */
if (!vcpu_align)
vcpu_align = __alignof__(struct kvm_vcpu);
kvm_vcpu_cache = kmem_cache_create("kvm_vcpu", vcpu_size, vcpu_align,
0, NULL);
if (!kvm_vcpu_cache) {
r = -ENOMEM;
goto out_free_3;
}
r = kvm_async_pf_init();
if (r)
goto out_free;
kvm_chardev_ops.owner = module;
kvm_vm_fops.owner = module;
kvm_vcpu_fops.owner = module;
r = misc_register(&kvm_dev);
if (r) {
printk(KERN_ERR "kvm: misc device register failed\n");
goto out_unreg;
}
register_syscore_ops(&kvm_syscore_ops);
kvm_preempt_ops.sched_in = kvm_sched_in;
kvm_preempt_ops.sched_out = kvm_sched_out;
r = kvm_init_debug();
if (r) {
printk(KERN_ERR "kvm: create debugfs files failed\n");
goto out_undebugfs;
}
return 0;
out_undebugfs:
unregister_syscore_ops(&kvm_syscore_ops);
misc_deregister(&kvm_dev);
out_unreg:
kvm_async_pf_deinit();
out_free:
kmem_cache_destroy(kvm_vcpu_cache);
out_free_3:
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
out_free_2:
out_free_1:
kvm_arch_hardware_unsetup();
out_free_0a:
free_cpumask_var(cpus_hardware_enabled);
out_free_0:
kvm_irqfd_exit();
out_irqfd:
kvm_arch_exit();
out_fail:
return r;
}
EXPORT_SYMBOL_GPL(kvm_init);
void kvm_exit(void)
{
kvm_exit_debug();
misc_deregister(&kvm_dev);
kmem_cache_destroy(kvm_vcpu_cache);
kvm_async_pf_deinit();
unregister_syscore_ops(&kvm_syscore_ops);
unregister_reboot_notifier(&kvm_reboot_notifier);
unregister_cpu_notifier(&kvm_cpu_notifier);
on_each_cpu(hardware_disable_nolock, NULL, 1);
kvm_arch_hardware_unsetup();
kvm_arch_exit();
kvm_irqfd_exit();
free_cpumask_var(cpus_hardware_enabled);
}
EXPORT_SYMBOL_GPL(kvm_exit);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5765_0 |
crossvul-cpp_data_bad_4685_1 | /*-
* Copyright (c) 2018 Grzegorz Antoniak (http://antoniak.org)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "archive_platform.h"
#include "archive_endian.h"
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#include <time.h>
#ifdef HAVE_ZLIB_H
#include <zlib.h> /* crc32 */
#endif
#ifdef HAVE_LIMITS_H
#include <limits.h>
#endif
#include "archive.h"
#ifndef HAVE_ZLIB_H
#include "archive_crc32.h"
#endif
#include "archive_entry.h"
#include "archive_entry_locale.h"
#include "archive_ppmd7_private.h"
#include "archive_entry_private.h"
#ifdef HAVE_BLAKE2_H
#include <blake2.h>
#else
#include "archive_blake2.h"
#endif
/*#define CHECK_CRC_ON_SOLID_SKIP*/
/*#define DONT_FAIL_ON_CRC_ERROR*/
/*#define DEBUG*/
#define rar5_min(a, b) (((a) > (b)) ? (b) : (a))
#define rar5_max(a, b) (((a) > (b)) ? (a) : (b))
#define rar5_countof(X) ((const ssize_t) (sizeof(X) / sizeof(*X)))
#if defined DEBUG
#define DEBUG_CODE if(1)
#define LOG(...) do { printf("rar5: " __VA_ARGS__); puts(""); } while(0)
#else
#define DEBUG_CODE if(0)
#endif
/* Real RAR5 magic number is:
*
* 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0x00
* "Rar!→•☺·\x00"
*
* It's stored in `rar5_signature` after XOR'ing it with 0xA1, because I don't
* want to put this magic sequence in each binary that uses libarchive, so
* applications that scan through the file for this marker won't trigger on
* this "false" one.
*
* The array itself is decrypted in `rar5_init` function. */
static unsigned char rar5_signature[] = { 243, 192, 211, 128, 187, 166, 160, 161 };
static const ssize_t rar5_signature_size = sizeof(rar5_signature);
static const size_t g_unpack_window_size = 0x20000;
/* These could have been static const's, but they aren't, because of
* Visual Studio. */
#define MAX_NAME_IN_CHARS 2048
#define MAX_NAME_IN_BYTES (4 * MAX_NAME_IN_CHARS)
struct file_header {
ssize_t bytes_remaining;
ssize_t unpacked_size;
int64_t last_offset; /* Used in sanity checks. */
int64_t last_size; /* Used in sanity checks. */
uint8_t solid : 1; /* Is this a solid stream? */
uint8_t service : 1; /* Is this file a service data? */
uint8_t eof : 1; /* Did we finish unpacking the file? */
uint8_t dir : 1; /* Is this file entry a directory? */
/* Optional time fields. */
uint64_t e_mtime;
uint64_t e_ctime;
uint64_t e_atime;
uint32_t e_unix_ns;
/* Optional hash fields. */
uint32_t stored_crc32;
uint32_t calculated_crc32;
uint8_t blake2sp[32];
blake2sp_state b2state;
char has_blake2;
/* Optional redir fields */
uint64_t redir_type;
uint64_t redir_flags;
ssize_t solid_window_size; /* Used in file format check. */
};
enum EXTRA {
EX_CRYPT = 0x01,
EX_HASH = 0x02,
EX_HTIME = 0x03,
EX_VERSION = 0x04,
EX_REDIR = 0x05,
EX_UOWNER = 0x06,
EX_SUBDATA = 0x07
};
#define REDIR_SYMLINK_IS_DIR 1
enum REDIR_TYPE {
REDIR_TYPE_NONE = 0,
REDIR_TYPE_UNIXSYMLINK = 1,
REDIR_TYPE_WINSYMLINK = 2,
REDIR_TYPE_JUNCTION = 3,
REDIR_TYPE_HARDLINK = 4,
REDIR_TYPE_FILECOPY = 5,
};
#define OWNER_USER_NAME 0x01
#define OWNER_GROUP_NAME 0x02
#define OWNER_USER_UID 0x04
#define OWNER_GROUP_GID 0x08
#define OWNER_MAXNAMELEN 256
enum FILTER_TYPE {
FILTER_DELTA = 0, /* Generic pattern. */
FILTER_E8 = 1, /* Intel x86 code. */
FILTER_E8E9 = 2, /* Intel x86 code. */
FILTER_ARM = 3, /* ARM code. */
FILTER_AUDIO = 4, /* Audio filter, not used in RARv5. */
FILTER_RGB = 5, /* Color palette, not used in RARv5. */
FILTER_ITANIUM = 6, /* Intel's Itanium, not used in RARv5. */
FILTER_PPM = 7, /* Predictive pattern matching, not used in
RARv5. */
FILTER_NONE = 8,
};
struct filter_info {
int type;
int channels;
int pos_r;
int64_t block_start;
ssize_t block_length;
uint16_t width;
};
struct data_ready {
char used;
const uint8_t* buf;
size_t size;
int64_t offset;
};
struct cdeque {
uint16_t beg_pos;
uint16_t end_pos;
uint16_t cap_mask;
uint16_t size;
size_t* arr;
};
struct decode_table {
uint32_t size;
int32_t decode_len[16];
uint32_t decode_pos[16];
uint32_t quick_bits;
uint8_t quick_len[1 << 10];
uint16_t quick_num[1 << 10];
uint16_t decode_num[306];
};
struct comp_state {
/* Flag used to specify if unpacker needs to reinitialize the
uncompression context. */
uint8_t initialized : 1;
/* Flag used when applying filters. */
uint8_t all_filters_applied : 1;
/* Flag used to skip file context reinitialization, used when unpacker
is skipping through different multivolume archives. */
uint8_t switch_multivolume : 1;
/* Flag used to specify if unpacker has processed the whole data block
or just a part of it. */
uint8_t block_parsing_finished : 1;
signed int notused : 4;
int flags; /* Uncompression flags. */
int method; /* Uncompression algorithm method. */
int version; /* Uncompression algorithm version. */
ssize_t window_size; /* Size of window_buf. */
uint8_t* window_buf; /* Circular buffer used during
decompression. */
uint8_t* filtered_buf; /* Buffer used when applying filters. */
const uint8_t* block_buf; /* Buffer used when merging blocks. */
size_t window_mask; /* Convenience field; window_size - 1. */
int64_t write_ptr; /* This amount of data has been unpacked
in the window buffer. */
int64_t last_write_ptr; /* This amount of data has been stored in
the output file. */
int64_t last_unstore_ptr; /* Counter of bytes extracted during
unstoring. This is separate from
last_write_ptr because of how SERVICE
base blocks are handled during skipping
in solid multiarchive archives. */
int64_t solid_offset; /* Additional offset inside the window
buffer, used in unpacking solid
archives. */
ssize_t cur_block_size; /* Size of current data block. */
int last_len; /* Flag used in lzss decompression. */
/* Decode tables used during lzss uncompression. */
#define HUFF_BC 20
struct decode_table bd; /* huffman bit lengths */
#define HUFF_NC 306
struct decode_table ld; /* literals */
#define HUFF_DC 64
struct decode_table dd; /* distances */
#define HUFF_LDC 16
struct decode_table ldd; /* lower bits of distances */
#define HUFF_RC 44
struct decode_table rd; /* repeating distances */
#define HUFF_TABLE_SIZE (HUFF_NC + HUFF_DC + HUFF_RC + HUFF_LDC)
/* Circular deque for storing filters. */
struct cdeque filters;
int64_t last_block_start; /* Used for sanity checking. */
ssize_t last_block_length; /* Used for sanity checking. */
/* Distance cache used during lzss uncompression. */
int dist_cache[4];
/* Data buffer stack. */
struct data_ready dready[2];
};
/* Bit reader state. */
struct bit_reader {
int8_t bit_addr; /* Current bit pointer inside current byte. */
int in_addr; /* Current byte pointer. */
};
/* RARv5 block header structure. Use bf_* functions to get values from
* block_flags_u8 field. I.e. bf_byte_count, etc. */
struct compressed_block_header {
/* block_flags_u8 contain fields encoded in little-endian bitfield:
*
* - table present flag (shr 7, and 1),
* - last block flag (shr 6, and 1),
* - byte_count (shr 3, and 7),
* - bit_size (shr 0, and 7).
*/
uint8_t block_flags_u8;
uint8_t block_cksum;
};
/* RARv5 main header structure. */
struct main_header {
/* Does the archive contain solid streams? */
uint8_t solid : 1;
/* If this a multi-file archive? */
uint8_t volume : 1;
uint8_t endarc : 1;
uint8_t notused : 5;
unsigned int vol_no;
};
struct generic_header {
uint8_t split_after : 1;
uint8_t split_before : 1;
uint8_t padding : 6;
int size;
int last_header_id;
};
struct multivolume {
unsigned int expected_vol_no;
uint8_t* push_buf;
};
/* Main context structure. */
struct rar5 {
int header_initialized;
/* Set to 1 if current file is positioned AFTER the magic value
* of the archive file. This is used in header reading functions. */
int skipped_magic;
/* Set to not zero if we're in skip mode (either by calling
* rar5_data_skip function or when skipping over solid streams).
* Set to 0 when in * extraction mode. This is used during checksum
* calculation functions. */
int skip_mode;
/* Set to not zero if we're in block merging mode (i.e. when switching
* to another file in multivolume archive, last block from 1st archive
* needs to be merged with 1st block from 2nd archive). This flag
* guards against recursive use of the merging function, which doesn't
* support recursive calls. */
int merge_mode;
/* An offset to QuickOpen list. This is not supported by this unpacker,
* because we're focusing on streaming interface. QuickOpen is designed
* to make things quicker for non-stream interfaces, so it's not our
* use case. */
uint64_t qlist_offset;
/* An offset to additional Recovery data. This is not supported by this
* unpacker. Recovery data are additional Reed-Solomon codes that could
* be used to calculate bytes that are missing in archive or are
* corrupted. */
uint64_t rr_offset;
/* Various context variables grouped to different structures. */
struct generic_header generic;
struct main_header main;
struct comp_state cstate;
struct file_header file;
struct bit_reader bits;
struct multivolume vol;
/* The header of currently processed RARv5 block. Used in main
* decompression logic loop. */
struct compressed_block_header last_block_hdr;
};
/* Forward function declarations. */
static int verify_global_checksums(struct archive_read* a);
static int rar5_read_data_skip(struct archive_read *a);
static int push_data_ready(struct archive_read* a, struct rar5* rar,
const uint8_t* buf, size_t size, int64_t offset);
/* CDE_xxx = Circular Double Ended (Queue) return values. */
enum CDE_RETURN_VALUES {
CDE_OK, CDE_ALLOC, CDE_PARAM, CDE_OUT_OF_BOUNDS,
};
/* Clears the contents of this circular deque. */
static void cdeque_clear(struct cdeque* d) {
d->size = 0;
d->beg_pos = 0;
d->end_pos = 0;
}
/* Creates a new circular deque object. Capacity must be power of 2: 8, 16, 32,
* 64, 256, etc. When the user will add another item above current capacity,
* the circular deque will overwrite the oldest entry. */
static int cdeque_init(struct cdeque* d, int max_capacity_power_of_2) {
if(d == NULL || max_capacity_power_of_2 == 0)
return CDE_PARAM;
d->cap_mask = max_capacity_power_of_2 - 1;
d->arr = NULL;
if((max_capacity_power_of_2 & d->cap_mask) != 0)
return CDE_PARAM;
cdeque_clear(d);
d->arr = malloc(sizeof(void*) * max_capacity_power_of_2);
return d->arr ? CDE_OK : CDE_ALLOC;
}
/* Return the current size (not capacity) of circular deque `d`. */
static size_t cdeque_size(struct cdeque* d) {
return d->size;
}
/* Returns the first element of current circular deque. Note that this function
* doesn't perform any bounds checking. If you need bounds checking, use
* `cdeque_front()` function instead. */
static void cdeque_front_fast(struct cdeque* d, void** value) {
*value = (void*) d->arr[d->beg_pos];
}
/* Returns the first element of current circular deque. This function
* performs bounds checking. */
static int cdeque_front(struct cdeque* d, void** value) {
if(d->size > 0) {
cdeque_front_fast(d, value);
return CDE_OK;
} else
return CDE_OUT_OF_BOUNDS;
}
/* Pushes a new element into the end of this circular deque object. If current
* size will exceed capacity, the oldest element will be overwritten. */
static int cdeque_push_back(struct cdeque* d, void* item) {
if(d == NULL)
return CDE_PARAM;
if(d->size == d->cap_mask + 1)
return CDE_OUT_OF_BOUNDS;
d->arr[d->end_pos] = (size_t) item;
d->end_pos = (d->end_pos + 1) & d->cap_mask;
d->size++;
return CDE_OK;
}
/* Pops a front element of this circular deque object and returns its value.
* This function doesn't perform any bounds checking. */
static void cdeque_pop_front_fast(struct cdeque* d, void** value) {
*value = (void*) d->arr[d->beg_pos];
d->beg_pos = (d->beg_pos + 1) & d->cap_mask;
d->size--;
}
/* Pops a front element of this circular deque object and returns its value.
* This function performs bounds checking. */
static int cdeque_pop_front(struct cdeque* d, void** value) {
if(!d || !value)
return CDE_PARAM;
if(d->size == 0)
return CDE_OUT_OF_BOUNDS;
cdeque_pop_front_fast(d, value);
return CDE_OK;
}
/* Convenience function to cast filter_info** to void **. */
static void** cdeque_filter_p(struct filter_info** f) {
return (void**) (size_t) f;
}
/* Convenience function to cast filter_info* to void *. */
static void* cdeque_filter(struct filter_info* f) {
return (void**) (size_t) f;
}
/* Destroys this circular deque object. Deallocates the memory of the
* collection buffer, but doesn't deallocate the memory of any pointer passed
* to this deque as a value. */
static void cdeque_free(struct cdeque* d) {
if(!d)
return;
if(!d->arr)
return;
free(d->arr);
d->arr = NULL;
d->beg_pos = -1;
d->end_pos = -1;
d->cap_mask = 0;
}
static inline
uint8_t bf_bit_size(const struct compressed_block_header* hdr) {
return hdr->block_flags_u8 & 7;
}
static inline
uint8_t bf_byte_count(const struct compressed_block_header* hdr) {
return (hdr->block_flags_u8 >> 3) & 7;
}
static inline
uint8_t bf_is_table_present(const struct compressed_block_header* hdr) {
return (hdr->block_flags_u8 >> 7) & 1;
}
static inline struct rar5* get_context(struct archive_read* a) {
return (struct rar5*) a->format->data;
}
/* Convenience functions used by filter implementations. */
static void circular_memcpy(uint8_t* dst, uint8_t* window, const uint64_t mask,
int64_t start, int64_t end)
{
if((start & mask) > (end & mask)) {
ssize_t len1 = mask + 1 - (start & mask);
ssize_t len2 = end & mask;
memcpy(dst, &window[start & mask], len1);
memcpy(dst + len1, window, len2);
} else {
memcpy(dst, &window[start & mask], (size_t) (end - start));
}
}
static uint32_t read_filter_data(struct rar5* rar, uint32_t offset) {
uint8_t linear_buf[4];
circular_memcpy(linear_buf, rar->cstate.window_buf,
rar->cstate.window_mask, offset, offset + 4);
return archive_le32dec(linear_buf);
}
static void write_filter_data(struct rar5* rar, uint32_t offset,
uint32_t value)
{
archive_le32enc(&rar->cstate.filtered_buf[offset], value);
}
/* Allocates a new filter descriptor and adds it to the filter array. */
static struct filter_info* add_new_filter(struct rar5* rar) {
struct filter_info* f =
(struct filter_info*) calloc(1, sizeof(struct filter_info));
if(!f) {
return NULL;
}
cdeque_push_back(&rar->cstate.filters, cdeque_filter(f));
return f;
}
static int run_delta_filter(struct rar5* rar, struct filter_info* flt) {
int i;
ssize_t dest_pos, src_pos = 0;
for(i = 0; i < flt->channels; i++) {
uint8_t prev_byte = 0;
for(dest_pos = i;
dest_pos < flt->block_length;
dest_pos += flt->channels)
{
uint8_t byte;
byte = rar->cstate.window_buf[
(rar->cstate.solid_offset + flt->block_start +
src_pos) & rar->cstate.window_mask];
prev_byte -= byte;
rar->cstate.filtered_buf[dest_pos] = prev_byte;
src_pos++;
}
}
return ARCHIVE_OK;
}
static int run_e8e9_filter(struct rar5* rar, struct filter_info* flt,
int extended)
{
const uint32_t file_size = 0x1000000;
ssize_t i;
circular_memcpy(rar->cstate.filtered_buf,
rar->cstate.window_buf, rar->cstate.window_mask,
rar->cstate.solid_offset + flt->block_start,
rar->cstate.solid_offset + flt->block_start + flt->block_length);
for(i = 0; i < flt->block_length - 4;) {
uint8_t b = rar->cstate.window_buf[
(rar->cstate.solid_offset + flt->block_start +
i++) & rar->cstate.window_mask];
/*
* 0xE8 = x86's call <relative_addr_uint32> (function call)
* 0xE9 = x86's jmp <relative_addr_uint32> (unconditional jump)
*/
if(b == 0xE8 || (extended && b == 0xE9)) {
uint32_t addr;
uint32_t offset = (i + flt->block_start) % file_size;
addr = read_filter_data(rar,
(uint32_t)(rar->cstate.solid_offset +
flt->block_start + i) & rar->cstate.window_mask);
if(addr & 0x80000000) {
if(((addr + offset) & 0x80000000) == 0) {
write_filter_data(rar, (uint32_t)i,
addr + file_size);
}
} else {
if((addr - file_size) & 0x80000000) {
uint32_t naddr = addr - offset;
write_filter_data(rar, (uint32_t)i,
naddr);
}
}
i += 4;
}
}
return ARCHIVE_OK;
}
static int run_arm_filter(struct rar5* rar, struct filter_info* flt) {
ssize_t i = 0;
uint32_t offset;
circular_memcpy(rar->cstate.filtered_buf,
rar->cstate.window_buf, rar->cstate.window_mask,
rar->cstate.solid_offset + flt->block_start,
rar->cstate.solid_offset + flt->block_start + flt->block_length);
for(i = 0; i < flt->block_length - 3; i += 4) {
uint8_t* b = &rar->cstate.window_buf[
(rar->cstate.solid_offset +
flt->block_start + i + 3) & rar->cstate.window_mask];
if(*b == 0xEB) {
/* 0xEB = ARM's BL (branch + link) instruction. */
offset = read_filter_data(rar,
(rar->cstate.solid_offset + flt->block_start + i) &
rar->cstate.window_mask) & 0x00ffffff;
offset -= (uint32_t) ((i + flt->block_start) / 4);
offset = (offset & 0x00ffffff) | 0xeb000000;
write_filter_data(rar, (uint32_t)i, offset);
}
}
return ARCHIVE_OK;
}
static int run_filter(struct archive_read* a, struct filter_info* flt) {
int ret;
struct rar5* rar = get_context(a);
free(rar->cstate.filtered_buf);
rar->cstate.filtered_buf = malloc(flt->block_length);
if(!rar->cstate.filtered_buf) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for filter data.");
return ARCHIVE_FATAL;
}
switch(flt->type) {
case FILTER_DELTA:
ret = run_delta_filter(rar, flt);
break;
case FILTER_E8:
/* fallthrough */
case FILTER_E8E9:
ret = run_e8e9_filter(rar, flt,
flt->type == FILTER_E8E9);
break;
case FILTER_ARM:
ret = run_arm_filter(rar, flt);
break;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported filter type: 0x%x", flt->type);
return ARCHIVE_FATAL;
}
if(ret != ARCHIVE_OK) {
/* Filter has failed. */
return ret;
}
if(ARCHIVE_OK != push_data_ready(a, rar, rar->cstate.filtered_buf,
flt->block_length, rar->cstate.last_write_ptr))
{
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Stack overflow when submitting unpacked data");
return ARCHIVE_FATAL;
}
rar->cstate.last_write_ptr += flt->block_length;
return ARCHIVE_OK;
}
/* The `push_data` function submits the selected data range to the user.
* Next call of `use_data` will use the pointer, size and offset arguments
* that are specified here. These arguments are pushed to the FIFO stack here,
* and popped from the stack by the `use_data` function. */
static void push_data(struct archive_read* a, struct rar5* rar,
const uint8_t* buf, int64_t idx_begin, int64_t idx_end)
{
const uint64_t wmask = rar->cstate.window_mask;
const ssize_t solid_write_ptr = (rar->cstate.solid_offset +
rar->cstate.last_write_ptr) & wmask;
idx_begin += rar->cstate.solid_offset;
idx_end += rar->cstate.solid_offset;
/* Check if our unpacked data is wrapped inside the window circular
* buffer. If it's not wrapped, it can be copied out by using
* a single memcpy, but when it's wrapped, we need to copy the first
* part with one memcpy, and the second part with another memcpy. */
if((idx_begin & wmask) > (idx_end & wmask)) {
/* The data is wrapped (begin offset sis bigger than end
* offset). */
const ssize_t frag1_size = rar->cstate.window_size -
(idx_begin & wmask);
const ssize_t frag2_size = idx_end & wmask;
/* Copy the first part of the buffer first. */
push_data_ready(a, rar, buf + solid_write_ptr, frag1_size,
rar->cstate.last_write_ptr);
/* Copy the second part of the buffer. */
push_data_ready(a, rar, buf, frag2_size,
rar->cstate.last_write_ptr + frag1_size);
rar->cstate.last_write_ptr += frag1_size + frag2_size;
} else {
/* Data is not wrapped, so we can just use one call to copy the
* data. */
push_data_ready(a, rar,
buf + solid_write_ptr, (idx_end - idx_begin) & wmask,
rar->cstate.last_write_ptr);
rar->cstate.last_write_ptr += idx_end - idx_begin;
}
}
/* Convenience function that submits the data to the user. It uses the
* unpack window buffer as a source location. */
static void push_window_data(struct archive_read* a, struct rar5* rar,
int64_t idx_begin, int64_t idx_end)
{
push_data(a, rar, rar->cstate.window_buf, idx_begin, idx_end);
}
static int apply_filters(struct archive_read* a) {
struct filter_info* flt;
struct rar5* rar = get_context(a);
int ret;
rar->cstate.all_filters_applied = 0;
/* Get the first filter that can be applied to our data. The data
* needs to be fully unpacked before the filter can be run. */
if(CDE_OK == cdeque_front(&rar->cstate.filters,
cdeque_filter_p(&flt))) {
/* Check if our unpacked data fully covers this filter's
* range. */
if(rar->cstate.write_ptr > flt->block_start &&
rar->cstate.write_ptr >= flt->block_start +
flt->block_length) {
/* Check if we have some data pending to be written
* right before the filter's start offset. */
if(rar->cstate.last_write_ptr == flt->block_start) {
/* Run the filter specified by descriptor
* `flt`. */
ret = run_filter(a, flt);
if(ret != ARCHIVE_OK) {
/* Filter failure, return error. */
return ret;
}
/* Filter descriptor won't be needed anymore
* after it's used, * so remove it from the
* filter list and free its memory. */
(void) cdeque_pop_front(&rar->cstate.filters,
cdeque_filter_p(&flt));
free(flt);
} else {
/* We can't run filters yet, dump the memory
* right before the filter. */
push_window_data(a, rar,
rar->cstate.last_write_ptr,
flt->block_start);
}
/* Return 'filter applied or not needed' state to the
* caller. */
return ARCHIVE_RETRY;
}
}
rar->cstate.all_filters_applied = 1;
return ARCHIVE_OK;
}
static void dist_cache_push(struct rar5* rar, int value) {
int* q = rar->cstate.dist_cache;
q[3] = q[2];
q[2] = q[1];
q[1] = q[0];
q[0] = value;
}
static int dist_cache_touch(struct rar5* rar, int idx) {
int* q = rar->cstate.dist_cache;
int i, dist = q[idx];
for(i = idx; i > 0; i--)
q[i] = q[i - 1];
q[0] = dist;
return dist;
}
static void free_filters(struct rar5* rar) {
struct cdeque* d = &rar->cstate.filters;
/* Free any remaining filters. All filters should be naturally
* consumed by the unpacking function, so remaining filters after
* unpacking normally mean that unpacking wasn't successful.
* But still of course we shouldn't leak memory in such case. */
/* cdeque_size() is a fast operation, so we can use it as a loop
* expression. */
while(cdeque_size(d) > 0) {
struct filter_info* f = NULL;
/* Pop_front will also decrease the collection's size. */
if (CDE_OK == cdeque_pop_front(d, cdeque_filter_p(&f)))
free(f);
}
cdeque_clear(d);
/* Also clear out the variables needed for sanity checking. */
rar->cstate.last_block_start = 0;
rar->cstate.last_block_length = 0;
}
static void reset_file_context(struct rar5* rar) {
memset(&rar->file, 0, sizeof(rar->file));
blake2sp_init(&rar->file.b2state, 32);
if(rar->main.solid) {
rar->cstate.solid_offset += rar->cstate.write_ptr;
} else {
rar->cstate.solid_offset = 0;
}
rar->cstate.write_ptr = 0;
rar->cstate.last_write_ptr = 0;
rar->cstate.last_unstore_ptr = 0;
rar->file.redir_type = REDIR_TYPE_NONE;
rar->file.redir_flags = 0;
free_filters(rar);
}
static inline int get_archive_read(struct archive* a,
struct archive_read** ar)
{
*ar = (struct archive_read*) a;
archive_check_magic(a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
"archive_read_support_format_rar5");
return ARCHIVE_OK;
}
static int read_ahead(struct archive_read* a, size_t how_many,
const uint8_t** ptr)
{
ssize_t avail = -1;
if(!ptr)
return 0;
*ptr = __archive_read_ahead(a, how_many, &avail);
if(*ptr == NULL) {
return 0;
}
return 1;
}
static int consume(struct archive_read* a, int64_t how_many) {
int ret;
ret = how_many == __archive_read_consume(a, how_many)
? ARCHIVE_OK
: ARCHIVE_FATAL;
return ret;
}
/**
* Read a RAR5 variable sized numeric value. This value will be stored in
* `pvalue`. The `pvalue_len` argument points to a variable that will receive
* the byte count that was consumed in order to decode the `pvalue` value, plus
* one.
*
* pvalue_len is optional and can be NULL.
*
* NOTE: if `pvalue_len` is NOT NULL, the caller needs to manually consume
* the number of bytes that `pvalue_len` value contains. If the `pvalue_len`
* is NULL, this consuming operation is done automatically.
*
* Returns 1 if *pvalue was successfully read.
* Returns 0 if there was an error. In this case, *pvalue contains an
* invalid value.
*/
static int read_var(struct archive_read* a, uint64_t* pvalue,
uint64_t* pvalue_len)
{
uint64_t result = 0;
size_t shift, i;
const uint8_t* p;
uint8_t b;
/* We will read maximum of 8 bytes. We don't have to handle the
* situation to read the RAR5 variable-sized value stored at the end of
* the file, because such situation will never happen. */
if(!read_ahead(a, 8, &p))
return 0;
for(shift = 0, i = 0; i < 8; i++, shift += 7) {
b = p[i];
/* Strip the MSB from the input byte and add the resulting
* number to the `result`. */
result += (b & (uint64_t)0x7F) << shift;
/* MSB set to 1 means we need to continue decoding process.
* MSB set to 0 means we're done.
*
* This conditional checks for the second case. */
if((b & 0x80) == 0) {
if(pvalue) {
*pvalue = result;
}
/* If the caller has passed the `pvalue_len` pointer,
* store the number of consumed bytes in it and do NOT
* consume those bytes, since the caller has all the
* information it needs to perform */
if(pvalue_len) {
*pvalue_len = 1 + i;
} else {
/* If the caller did not provide the
* `pvalue_len` pointer, it will not have the
* possibility to advance the file pointer,
* because it will not know how many bytes it
* needs to consume. This is why we handle
* such situation here automatically. */
if(ARCHIVE_OK != consume(a, 1 + i)) {
return 0;
}
}
/* End of decoding process, return success. */
return 1;
}
}
/* The decoded value takes the maximum number of 8 bytes.
* It's a maximum number of bytes, so end decoding process here
* even if the first bit of last byte is 1. */
if(pvalue) {
*pvalue = result;
}
if(pvalue_len) {
*pvalue_len = 9;
} else {
if(ARCHIVE_OK != consume(a, 9)) {
return 0;
}
}
return 1;
}
static int read_var_sized(struct archive_read* a, size_t* pvalue,
size_t* pvalue_len)
{
uint64_t v;
uint64_t v_size = 0;
const int ret = pvalue_len ? read_var(a, &v, &v_size)
: read_var(a, &v, NULL);
if(ret == 1 && pvalue) {
*pvalue = (size_t) v;
}
if(pvalue_len) {
/* Possible data truncation should be safe. */
*pvalue_len = (size_t) v_size;
}
return ret;
}
static int read_bits_32(struct rar5* rar, const uint8_t* p, uint32_t* value) {
uint32_t bits = ((uint32_t) p[rar->bits.in_addr]) << 24;
bits |= p[rar->bits.in_addr + 1] << 16;
bits |= p[rar->bits.in_addr + 2] << 8;
bits |= p[rar->bits.in_addr + 3];
bits <<= rar->bits.bit_addr;
bits |= p[rar->bits.in_addr + 4] >> (8 - rar->bits.bit_addr);
*value = bits;
return ARCHIVE_OK;
}
static int read_bits_16(struct rar5* rar, const uint8_t* p, uint16_t* value) {
int bits = (int) ((uint32_t) p[rar->bits.in_addr]) << 16;
bits |= (int) p[rar->bits.in_addr + 1] << 8;
bits |= (int) p[rar->bits.in_addr + 2];
bits >>= (8 - rar->bits.bit_addr);
*value = bits & 0xffff;
return ARCHIVE_OK;
}
static void skip_bits(struct rar5* rar, int bits) {
const int new_bits = rar->bits.bit_addr + bits;
rar->bits.in_addr += new_bits >> 3;
rar->bits.bit_addr = new_bits & 7;
}
/* n = up to 16 */
static int read_consume_bits(struct rar5* rar, const uint8_t* p, int n,
int* value)
{
uint16_t v;
int ret, num;
if(n == 0 || n > 16) {
/* This is a programmer error and should never happen
* in runtime. */
return ARCHIVE_FATAL;
}
ret = read_bits_16(rar, p, &v);
if(ret != ARCHIVE_OK)
return ret;
num = (int) v;
num >>= 16 - n;
skip_bits(rar, n);
if(value)
*value = num;
return ARCHIVE_OK;
}
static int read_u32(struct archive_read* a, uint32_t* pvalue) {
const uint8_t* p;
if(!read_ahead(a, 4, &p))
return 0;
*pvalue = archive_le32dec(p);
return ARCHIVE_OK == consume(a, 4) ? 1 : 0;
}
static int read_u64(struct archive_read* a, uint64_t* pvalue) {
const uint8_t* p;
if(!read_ahead(a, 8, &p))
return 0;
*pvalue = archive_le64dec(p);
return ARCHIVE_OK == consume(a, 8) ? 1 : 0;
}
static int bid_standard(struct archive_read* a) {
const uint8_t* p;
if(!read_ahead(a, rar5_signature_size, &p))
return -1;
if(!memcmp(rar5_signature, p, rar5_signature_size))
return 30;
return -1;
}
static int rar5_bid(struct archive_read* a, int best_bid) {
int my_bid;
if(best_bid > 30)
return -1;
my_bid = bid_standard(a);
if(my_bid > -1) {
return my_bid;
}
return -1;
}
static int rar5_options(struct archive_read *a, const char *key,
const char *val) {
(void) a;
(void) key;
(void) val;
/* No options supported in this version. Return the ARCHIVE_WARN code
* to signal the options supervisor that the unpacker didn't handle
* setting this option. */
return ARCHIVE_WARN;
}
static void init_header(struct archive_read* a) {
a->archive.archive_format = ARCHIVE_FORMAT_RAR_V5;
a->archive.archive_format_name = "RAR5";
}
static void init_window_mask(struct rar5* rar) {
if (rar->cstate.window_size)
rar->cstate.window_mask = rar->cstate.window_size - 1;
else
rar->cstate.window_mask = 0;
}
enum HEADER_FLAGS {
HFL_EXTRA_DATA = 0x0001,
HFL_DATA = 0x0002,
HFL_SKIP_IF_UNKNOWN = 0x0004,
HFL_SPLIT_BEFORE = 0x0008,
HFL_SPLIT_AFTER = 0x0010,
HFL_CHILD = 0x0020,
HFL_INHERITED = 0x0040
};
static int process_main_locator_extra_block(struct archive_read* a,
struct rar5* rar)
{
uint64_t locator_flags;
enum LOCATOR_FLAGS {
QLIST = 0x01, RECOVERY = 0x02,
};
if(!read_var(a, &locator_flags, NULL)) {
return ARCHIVE_EOF;
}
if(locator_flags & QLIST) {
if(!read_var(a, &rar->qlist_offset, NULL)) {
return ARCHIVE_EOF;
}
/* qlist is not used */
}
if(locator_flags & RECOVERY) {
if(!read_var(a, &rar->rr_offset, NULL)) {
return ARCHIVE_EOF;
}
/* rr is not used */
}
return ARCHIVE_OK;
}
static int parse_file_extra_hash(struct archive_read* a, struct rar5* rar,
ssize_t* extra_data_size)
{
size_t hash_type = 0;
size_t value_len;
enum HASH_TYPE {
BLAKE2sp = 0x00
};
if(!read_var_sized(a, &hash_type, &value_len))
return ARCHIVE_EOF;
*extra_data_size -= value_len;
if(ARCHIVE_OK != consume(a, value_len)) {
return ARCHIVE_EOF;
}
/* The file uses BLAKE2sp checksum algorithm instead of plain old
* CRC32. */
if(hash_type == BLAKE2sp) {
const uint8_t* p;
const int hash_size = sizeof(rar->file.blake2sp);
if(!read_ahead(a, hash_size, &p))
return ARCHIVE_EOF;
rar->file.has_blake2 = 1;
memcpy(&rar->file.blake2sp, p, hash_size);
if(ARCHIVE_OK != consume(a, hash_size)) {
return ARCHIVE_EOF;
}
*extra_data_size -= hash_size;
} else {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported hash type (0x%x)", (int) hash_type);
return ARCHIVE_FATAL;
}
return ARCHIVE_OK;
}
static uint64_t time_win_to_unix(uint64_t win_time) {
const size_t ns_in_sec = 10000000;
const uint64_t sec_to_unix = 11644473600LL;
return win_time / ns_in_sec - sec_to_unix;
}
static int parse_htime_item(struct archive_read* a, char unix_time,
uint64_t* where, ssize_t* extra_data_size)
{
if(unix_time) {
uint32_t time_val;
if(!read_u32(a, &time_val))
return ARCHIVE_EOF;
*extra_data_size -= 4;
*where = (uint64_t) time_val;
} else {
uint64_t windows_time;
if(!read_u64(a, &windows_time))
return ARCHIVE_EOF;
*where = time_win_to_unix(windows_time);
*extra_data_size -= 8;
}
return ARCHIVE_OK;
}
static int parse_file_extra_version(struct archive_read* a,
struct archive_entry* e, ssize_t* extra_data_size)
{
size_t flags = 0;
size_t version = 0;
size_t value_len = 0;
struct archive_string version_string;
struct archive_string name_utf8_string;
const char* cur_filename;
/* Flags are ignored. */
if(!read_var_sized(a, &flags, &value_len))
return ARCHIVE_EOF;
*extra_data_size -= value_len;
if(ARCHIVE_OK != consume(a, value_len))
return ARCHIVE_EOF;
if(!read_var_sized(a, &version, &value_len))
return ARCHIVE_EOF;
*extra_data_size -= value_len;
if(ARCHIVE_OK != consume(a, value_len))
return ARCHIVE_EOF;
/* extra_data_size should be zero here. */
cur_filename = archive_entry_pathname_utf8(e);
if(cur_filename == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Version entry without file name");
return ARCHIVE_FATAL;
}
archive_string_init(&version_string);
archive_string_init(&name_utf8_string);
/* Prepare a ;123 suffix for the filename, where '123' is the version
* value of this file. */
archive_string_sprintf(&version_string, ";%zu", version);
/* Build the new filename. */
archive_strcat(&name_utf8_string, cur_filename);
archive_strcat(&name_utf8_string, version_string.s);
/* Apply the new filename into this file's context. */
archive_entry_update_pathname_utf8(e, name_utf8_string.s);
/* Free buffers. */
archive_string_free(&version_string);
archive_string_free(&name_utf8_string);
return ARCHIVE_OK;
}
static int parse_file_extra_htime(struct archive_read* a,
struct archive_entry* e, struct rar5* rar, ssize_t* extra_data_size)
{
char unix_time = 0;
size_t flags = 0;
size_t value_len;
enum HTIME_FLAGS {
IS_UNIX = 0x01,
HAS_MTIME = 0x02,
HAS_CTIME = 0x04,
HAS_ATIME = 0x08,
HAS_UNIX_NS = 0x10,
};
if(!read_var_sized(a, &flags, &value_len))
return ARCHIVE_EOF;
*extra_data_size -= value_len;
if(ARCHIVE_OK != consume(a, value_len)) {
return ARCHIVE_EOF;
}
unix_time = flags & IS_UNIX;
if(flags & HAS_MTIME) {
parse_htime_item(a, unix_time, &rar->file.e_mtime,
extra_data_size);
archive_entry_set_mtime(e, rar->file.e_mtime, 0);
}
if(flags & HAS_CTIME) {
parse_htime_item(a, unix_time, &rar->file.e_ctime,
extra_data_size);
archive_entry_set_ctime(e, rar->file.e_ctime, 0);
}
if(flags & HAS_ATIME) {
parse_htime_item(a, unix_time, &rar->file.e_atime,
extra_data_size);
archive_entry_set_atime(e, rar->file.e_atime, 0);
}
if(flags & HAS_UNIX_NS) {
if(!read_u32(a, &rar->file.e_unix_ns))
return ARCHIVE_EOF;
*extra_data_size -= 4;
}
return ARCHIVE_OK;
}
static int parse_file_extra_redir(struct archive_read* a,
struct archive_entry* e, struct rar5* rar, ssize_t* extra_data_size)
{
uint64_t value_size = 0;
size_t target_size = 0;
char target_utf8_buf[MAX_NAME_IN_BYTES];
const uint8_t* p;
if(!read_var(a, &rar->file.redir_type, &value_size))
return ARCHIVE_EOF;
if(ARCHIVE_OK != consume(a, (int64_t)value_size))
return ARCHIVE_EOF;
*extra_data_size -= value_size;
if(!read_var(a, &rar->file.redir_flags, &value_size))
return ARCHIVE_EOF;
if(ARCHIVE_OK != consume(a, (int64_t)value_size))
return ARCHIVE_EOF;
*extra_data_size -= value_size;
if(!read_var_sized(a, &target_size, NULL))
return ARCHIVE_EOF;
*extra_data_size -= target_size + 1;
if(!read_ahead(a, target_size, &p))
return ARCHIVE_EOF;
if(target_size > (MAX_NAME_IN_CHARS - 1)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Link target is too long");
return ARCHIVE_FATAL;
}
if(target_size == 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"No link target specified");
return ARCHIVE_FATAL;
}
memcpy(target_utf8_buf, p, target_size);
target_utf8_buf[target_size] = 0;
if(ARCHIVE_OK != consume(a, (int64_t)target_size))
return ARCHIVE_EOF;
switch(rar->file.redir_type) {
case REDIR_TYPE_UNIXSYMLINK:
case REDIR_TYPE_WINSYMLINK:
archive_entry_set_filetype(e, AE_IFLNK);
archive_entry_update_symlink_utf8(e, target_utf8_buf);
if (rar->file.redir_flags & REDIR_SYMLINK_IS_DIR) {
archive_entry_set_symlink_type(e,
AE_SYMLINK_TYPE_DIRECTORY);
} else {
archive_entry_set_symlink_type(e,
AE_SYMLINK_TYPE_FILE);
}
break;
case REDIR_TYPE_HARDLINK:
archive_entry_set_filetype(e, AE_IFREG);
archive_entry_update_hardlink_utf8(e, target_utf8_buf);
break;
default:
/* Unknown redir type, skip it. */
break;
}
return ARCHIVE_OK;
}
static int parse_file_extra_owner(struct archive_read* a,
struct archive_entry* e, ssize_t* extra_data_size)
{
uint64_t flags = 0;
uint64_t value_size = 0;
uint64_t id = 0;
size_t name_len = 0;
size_t name_size = 0;
char namebuf[OWNER_MAXNAMELEN];
const uint8_t* p;
if(!read_var(a, &flags, &value_size))
return ARCHIVE_EOF;
if(ARCHIVE_OK != consume(a, (int64_t)value_size))
return ARCHIVE_EOF;
*extra_data_size -= value_size;
if ((flags & OWNER_USER_NAME) != 0) {
if(!read_var_sized(a, &name_size, NULL))
return ARCHIVE_EOF;
*extra_data_size -= name_size + 1;
if(!read_ahead(a, name_size, &p))
return ARCHIVE_EOF;
if (name_size >= OWNER_MAXNAMELEN) {
name_len = OWNER_MAXNAMELEN - 1;
} else {
name_len = name_size;
}
memcpy(namebuf, p, name_len);
namebuf[name_len] = 0;
if(ARCHIVE_OK != consume(a, (int64_t)name_size))
return ARCHIVE_EOF;
archive_entry_set_uname(e, namebuf);
}
if ((flags & OWNER_GROUP_NAME) != 0) {
if(!read_var_sized(a, &name_size, NULL))
return ARCHIVE_EOF;
*extra_data_size -= name_size + 1;
if(!read_ahead(a, name_size, &p))
return ARCHIVE_EOF;
if (name_size >= OWNER_MAXNAMELEN) {
name_len = OWNER_MAXNAMELEN - 1;
} else {
name_len = name_size;
}
memcpy(namebuf, p, name_len);
namebuf[name_len] = 0;
if(ARCHIVE_OK != consume(a, (int64_t)name_size))
return ARCHIVE_EOF;
archive_entry_set_gname(e, namebuf);
}
if ((flags & OWNER_USER_UID) != 0) {
if(!read_var(a, &id, &value_size))
return ARCHIVE_EOF;
if(ARCHIVE_OK != consume(a, (int64_t)value_size))
return ARCHIVE_EOF;
*extra_data_size -= value_size;
archive_entry_set_uid(e, (la_int64_t)id);
}
if ((flags & OWNER_GROUP_GID) != 0) {
if(!read_var(a, &id, &value_size))
return ARCHIVE_EOF;
if(ARCHIVE_OK != consume(a, (int64_t)value_size))
return ARCHIVE_EOF;
*extra_data_size -= value_size;
archive_entry_set_gid(e, (la_int64_t)id);
}
return ARCHIVE_OK;
}
static int process_head_file_extra(struct archive_read* a,
struct archive_entry* e, struct rar5* rar, ssize_t extra_data_size)
{
size_t extra_field_size;
size_t extra_field_id = 0;
int ret = ARCHIVE_FATAL;
size_t var_size;
while(extra_data_size > 0) {
if(!read_var_sized(a, &extra_field_size, &var_size))
return ARCHIVE_EOF;
extra_data_size -= var_size;
if(ARCHIVE_OK != consume(a, var_size)) {
return ARCHIVE_EOF;
}
if(!read_var_sized(a, &extra_field_id, &var_size))
return ARCHIVE_EOF;
extra_data_size -= var_size;
if(ARCHIVE_OK != consume(a, var_size)) {
return ARCHIVE_EOF;
}
switch(extra_field_id) {
case EX_HASH:
ret = parse_file_extra_hash(a, rar,
&extra_data_size);
break;
case EX_HTIME:
ret = parse_file_extra_htime(a, e, rar,
&extra_data_size);
break;
case EX_REDIR:
ret = parse_file_extra_redir(a, e, rar,
&extra_data_size);
break;
case EX_UOWNER:
ret = parse_file_extra_owner(a, e,
&extra_data_size);
break;
case EX_VERSION:
ret = parse_file_extra_version(a, e,
&extra_data_size);
break;
case EX_CRYPT:
/* fallthrough */
case EX_SUBDATA:
/* fallthrough */
default:
/* Skip unsupported entry. */
return consume(a, extra_data_size);
}
}
if(ret != ARCHIVE_OK) {
/* Attribute not implemented. */
return ret;
}
return ARCHIVE_OK;
}
static int process_head_file(struct archive_read* a, struct rar5* rar,
struct archive_entry* entry, size_t block_flags)
{
ssize_t extra_data_size = 0;
size_t data_size = 0;
size_t file_flags = 0;
size_t file_attr = 0;
size_t compression_info = 0;
size_t host_os = 0;
size_t name_size = 0;
uint64_t unpacked_size, window_size;
uint32_t mtime = 0, crc = 0;
int c_method = 0, c_version = 0;
char name_utf8_buf[MAX_NAME_IN_BYTES];
const uint8_t* p;
enum FILE_FLAGS {
DIRECTORY = 0x0001, UTIME = 0x0002, CRC32 = 0x0004,
UNKNOWN_UNPACKED_SIZE = 0x0008,
};
enum FILE_ATTRS {
ATTR_READONLY = 0x1, ATTR_HIDDEN = 0x2, ATTR_SYSTEM = 0x4,
ATTR_DIRECTORY = 0x10,
};
enum COMP_INFO_FLAGS {
SOLID = 0x0040,
};
enum HOST_OS {
HOST_WINDOWS = 0,
HOST_UNIX = 1,
};
archive_entry_clear(entry);
/* Do not reset file context if we're switching archives. */
if(!rar->cstate.switch_multivolume) {
reset_file_context(rar);
}
if(block_flags & HFL_EXTRA_DATA) {
size_t edata_size = 0;
if(!read_var_sized(a, &edata_size, NULL))
return ARCHIVE_EOF;
/* Intentional type cast from unsigned to signed. */
extra_data_size = (ssize_t) edata_size;
}
if(block_flags & HFL_DATA) {
if(!read_var_sized(a, &data_size, NULL))
return ARCHIVE_EOF;
rar->file.bytes_remaining = data_size;
} else {
rar->file.bytes_remaining = 0;
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"no data found in file/service block");
return ARCHIVE_FATAL;
}
if(!read_var_sized(a, &file_flags, NULL))
return ARCHIVE_EOF;
if(!read_var(a, &unpacked_size, NULL))
return ARCHIVE_EOF;
if(file_flags & UNKNOWN_UNPACKED_SIZE) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Files with unknown unpacked size are not supported");
return ARCHIVE_FATAL;
}
rar->file.dir = (uint8_t) ((file_flags & DIRECTORY) > 0);
if(!read_var_sized(a, &file_attr, NULL))
return ARCHIVE_EOF;
if(file_flags & UTIME) {
if(!read_u32(a, &mtime))
return ARCHIVE_EOF;
}
if(file_flags & CRC32) {
if(!read_u32(a, &crc))
return ARCHIVE_EOF;
}
if(!read_var_sized(a, &compression_info, NULL))
return ARCHIVE_EOF;
c_method = (int) (compression_info >> 7) & 0x7;
c_version = (int) (compression_info & 0x3f);
/* RAR5 seems to limit the dictionary size to 64MB. */
window_size = (rar->file.dir > 0) ?
0 :
g_unpack_window_size << ((compression_info >> 10) & 15);
rar->cstate.method = c_method;
rar->cstate.version = c_version + 50;
rar->file.solid = (compression_info & SOLID) > 0;
/* Archives which declare solid files without initializing the window
* buffer first are invalid. */
if(rar->file.solid > 0 && rar->cstate.window_buf == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Declared solid file, but no window buffer "
"initialized yet.");
return ARCHIVE_FATAL;
}
/* Check if window_size is a sane value. Also, if the file is not
* declared as a directory, disallow window_size == 0. */
if(window_size > (64 * 1024 * 1024) ||
(rar->file.dir == 0 && window_size == 0))
{
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Declared dictionary size is not supported.");
return ARCHIVE_FATAL;
}
if(rar->file.solid > 0) {
/* Re-check if current window size is the same as previous
* window size (for solid files only). */
if(rar->file.solid_window_size > 0 &&
rar->file.solid_window_size != (ssize_t) window_size)
{
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Window size for this solid file doesn't match "
"the window size used in previous solid file. ");
return ARCHIVE_FATAL;
}
}
/* If we're currently switching volumes, ignore the new definition of
* window_size. */
if(rar->cstate.switch_multivolume == 0) {
/* Values up to 64M should fit into ssize_t on every
* architecture. */
rar->cstate.window_size = (ssize_t) window_size;
}
if(rar->file.solid > 0 && rar->file.solid_window_size == 0) {
/* Solid files have to have the same window_size across
whole archive. Remember the window_size parameter
for first solid file found. */
rar->file.solid_window_size = rar->cstate.window_size;
}
init_window_mask(rar);
rar->file.service = 0;
if(!read_var_sized(a, &host_os, NULL))
return ARCHIVE_EOF;
if(host_os == HOST_WINDOWS) {
/* Host OS is Windows */
__LA_MODE_T mode;
if(file_attr & ATTR_DIRECTORY) {
if (file_attr & ATTR_READONLY) {
mode = 0555 | AE_IFDIR;
} else {
mode = 0755 | AE_IFDIR;
}
} else {
if (file_attr & ATTR_READONLY) {
mode = 0444 | AE_IFREG;
} else {
mode = 0644 | AE_IFREG;
}
}
archive_entry_set_mode(entry, mode);
if (file_attr & (ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM)) {
char *fflags_text, *ptr;
/* allocate for "rdonly,hidden,system," */
fflags_text = malloc(22 * sizeof(char));
if (fflags_text != NULL) {
ptr = fflags_text;
if (file_attr & ATTR_READONLY) {
strcpy(ptr, "rdonly,");
ptr = ptr + 7;
}
if (file_attr & ATTR_HIDDEN) {
strcpy(ptr, "hidden,");
ptr = ptr + 7;
}
if (file_attr & ATTR_SYSTEM) {
strcpy(ptr, "system,");
ptr = ptr + 7;
}
if (ptr > fflags_text) {
/* Delete trailing comma */
*(ptr - 1) = '\0';
archive_entry_copy_fflags_text(entry,
fflags_text);
}
free(fflags_text);
}
}
} else if(host_os == HOST_UNIX) {
/* Host OS is Unix */
archive_entry_set_mode(entry, (__LA_MODE_T) file_attr);
} else {
/* Unknown host OS */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported Host OS: 0x%x", (int) host_os);
return ARCHIVE_FATAL;
}
if(!read_var_sized(a, &name_size, NULL))
return ARCHIVE_EOF;
if(!read_ahead(a, name_size, &p))
return ARCHIVE_EOF;
if(name_size > (MAX_NAME_IN_CHARS - 1)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Filename is too long");
return ARCHIVE_FATAL;
}
if(name_size == 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"No filename specified");
return ARCHIVE_FATAL;
}
memcpy(name_utf8_buf, p, name_size);
name_utf8_buf[name_size] = 0;
if(ARCHIVE_OK != consume(a, name_size)) {
return ARCHIVE_EOF;
}
archive_entry_update_pathname_utf8(entry, name_utf8_buf);
if(extra_data_size > 0) {
int ret = process_head_file_extra(a, entry, rar,
extra_data_size);
/*
* TODO: rewrite or remove useless sanity check
* as extra_data_size is not passed as a pointer
*
if(extra_data_size < 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"File extra data size is not zero");
return ARCHIVE_FATAL;
}
*/
if(ret != ARCHIVE_OK)
return ret;
}
if((file_flags & UNKNOWN_UNPACKED_SIZE) == 0) {
rar->file.unpacked_size = (ssize_t) unpacked_size;
if(rar->file.redir_type == REDIR_TYPE_NONE)
archive_entry_set_size(entry, unpacked_size);
}
if(file_flags & UTIME) {
archive_entry_set_mtime(entry, (time_t) mtime, 0);
}
if(file_flags & CRC32) {
rar->file.stored_crc32 = crc;
}
if(!rar->cstate.switch_multivolume) {
/* Do not reinitialize unpacking state if we're switching
* archives. */
rar->cstate.block_parsing_finished = 1;
rar->cstate.all_filters_applied = 1;
rar->cstate.initialized = 0;
}
if(rar->generic.split_before > 0) {
/* If now we're standing on a header that has a 'split before'
* mark, it means we're standing on a 'continuation' file
* header. Signal the caller that if it wants to move to
* another file, it must call rar5_read_header() function
* again. */
return ARCHIVE_RETRY;
} else {
return ARCHIVE_OK;
}
}
static int process_head_service(struct archive_read* a, struct rar5* rar,
struct archive_entry* entry, size_t block_flags)
{
/* Process this SERVICE block the same way as FILE blocks. */
int ret = process_head_file(a, rar, entry, block_flags);
if(ret != ARCHIVE_OK)
return ret;
rar->file.service = 1;
/* But skip the data part automatically. It's no use for the user
* anyway. It contains only service data, not even needed to
* properly unpack the file. */
ret = rar5_read_data_skip(a);
if(ret != ARCHIVE_OK)
return ret;
/* After skipping, try parsing another block automatically. */
return ARCHIVE_RETRY;
}
static int process_head_main(struct archive_read* a, struct rar5* rar,
struct archive_entry* entry, size_t block_flags)
{
int ret;
size_t extra_data_size = 0;
size_t extra_field_size = 0;
size_t extra_field_id = 0;
size_t archive_flags = 0;
enum MAIN_FLAGS {
VOLUME = 0x0001, /* multi-volume archive */
VOLUME_NUMBER = 0x0002, /* volume number, first vol doesn't
* have it */
SOLID = 0x0004, /* solid archive */
PROTECT = 0x0008, /* contains Recovery info */
LOCK = 0x0010, /* readonly flag, not used */
};
enum MAIN_EXTRA {
// Just one attribute here.
LOCATOR = 0x01,
};
(void) entry;
if(block_flags & HFL_EXTRA_DATA) {
if(!read_var_sized(a, &extra_data_size, NULL))
return ARCHIVE_EOF;
} else {
extra_data_size = 0;
}
if(!read_var_sized(a, &archive_flags, NULL)) {
return ARCHIVE_EOF;
}
rar->main.volume = (archive_flags & VOLUME) > 0;
rar->main.solid = (archive_flags & SOLID) > 0;
if(archive_flags & VOLUME_NUMBER) {
size_t v = 0;
if(!read_var_sized(a, &v, NULL)) {
return ARCHIVE_EOF;
}
if (v > UINT_MAX) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid volume number");
return ARCHIVE_FATAL;
}
rar->main.vol_no = (unsigned int) v;
} else {
rar->main.vol_no = 0;
}
if(rar->vol.expected_vol_no > 0 &&
rar->main.vol_no != rar->vol.expected_vol_no)
{
/* Returning EOF instead of FATAL because of strange
* libarchive behavior. When opening multiple files via
* archive_read_open_filenames(), after reading up the whole
* last file, the __archive_read_ahead function wraps up to
* the first archive instead of returning EOF. */
return ARCHIVE_EOF;
}
if(extra_data_size == 0) {
/* Early return. */
return ARCHIVE_OK;
}
if(!read_var_sized(a, &extra_field_size, NULL)) {
return ARCHIVE_EOF;
}
if(!read_var_sized(a, &extra_field_id, NULL)) {
return ARCHIVE_EOF;
}
if(extra_field_size == 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid extra field size");
return ARCHIVE_FATAL;
}
switch(extra_field_id) {
case LOCATOR:
ret = process_main_locator_extra_block(a, rar);
if(ret != ARCHIVE_OK) {
/* Error while parsing main locator extra
* block. */
return ret;
}
break;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported extra type (0x%x)",
(int) extra_field_id);
return ARCHIVE_FATAL;
}
return ARCHIVE_OK;
}
static int skip_unprocessed_bytes(struct archive_read* a) {
struct rar5* rar = get_context(a);
int ret;
if(rar->file.bytes_remaining) {
/* Use different skipping method in block merging mode than in
* normal mode. If merge mode is active, rar5_read_data_skip
* can't be used, because it could allow recursive use of
* merge_block() * function, and this function doesn't support
* recursive use. */
if(rar->merge_mode) {
/* Discard whole merged block. This is valid in solid
* mode as well, because the code will discard blocks
* only if those blocks are safe to discard (i.e.
* they're not FILE blocks). */
ret = consume(a, rar->file.bytes_remaining);
if(ret != ARCHIVE_OK) {
return ret;
}
rar->file.bytes_remaining = 0;
} else {
/* If we're not in merge mode, use safe skipping code.
* This will ensure we'll handle solid archives
* properly. */
ret = rar5_read_data_skip(a);
if(ret != ARCHIVE_OK) {
return ret;
}
}
}
return ARCHIVE_OK;
}
static int scan_for_signature(struct archive_read* a);
/* Base block processing function. A 'base block' is a RARv5 header block
* that tells the reader what kind of data is stored inside the block.
*
* From the birds-eye view a RAR file looks file this:
*
* <magic><base_block_1><base_block_2>...<base_block_n>
*
* There are a few types of base blocks. Those types are specified inside
* the 'switch' statement in this function. For example purposes, I'll write
* how a standard RARv5 file could look like here:
*
* <magic><MAIN><FILE><FILE><FILE><SERVICE><ENDARC>
*
* The structure above could describe an archive file with 3 files in it,
* one service "QuickOpen" block (that is ignored by this parser), and an
* end of file base block marker.
*
* If the file is stored in multiple archive files ("multiarchive"), it might
* look like this:
*
* .part01.rar: <magic><MAIN><FILE><ENDARC>
* .part02.rar: <magic><MAIN><FILE><ENDARC>
* .part03.rar: <magic><MAIN><FILE><ENDARC>
*
* This example could describe 3 RAR files that contain ONE archived file.
* Or it could describe 3 RAR files that contain 3 different files. Or 3
* RAR files than contain 2 files. It all depends what metadata is stored in
* the headers of <FILE> blocks.
*
* Each <FILE> block contains info about its size, the name of the file it's
* storing inside, and whether this FILE block is a continuation block of
* previous archive ('split before'), and is this FILE block should be
* continued in another archive ('split after'). By parsing the 'split before'
* and 'split after' flags, we're able to tell if multiple <FILE> base blocks
* are describing one file, or multiple files (with the same filename, for
* example).
*
* One thing to note is that if we're parsing the first <FILE> block, and
* we see 'split after' flag, then we need to jump over to another <FILE>
* block to be able to decompress rest of the data. To do this, we need
* to skip the <ENDARC> block, then switch to another file, then skip the
* <magic> block, <MAIN> block, and then we're standing on the proper
* <FILE> block.
*/
static int process_base_block(struct archive_read* a,
struct archive_entry* entry)
{
struct rar5* rar = get_context(a);
uint32_t hdr_crc, computed_crc;
size_t raw_hdr_size = 0, hdr_size_len, hdr_size;
size_t header_id = 0;
size_t header_flags = 0;
const uint8_t* p;
int ret;
enum HEADER_TYPE {
HEAD_MARK = 0x00, HEAD_MAIN = 0x01, HEAD_FILE = 0x02,
HEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05,
HEAD_UNKNOWN = 0xff,
};
/* Skip any unprocessed data for this file. */
ret = skip_unprocessed_bytes(a);
if(ret != ARCHIVE_OK)
return ret;
/* Read the expected CRC32 checksum. */
if(!read_u32(a, &hdr_crc)) {
return ARCHIVE_EOF;
}
/* Read header size. */
if(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) {
return ARCHIVE_EOF;
}
/* Sanity check, maximum header size for RAR5 is 2MB. */
if(raw_hdr_size > (2 * 1024 * 1024)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Base block header is too large");
return ARCHIVE_FATAL;
}
hdr_size = raw_hdr_size + hdr_size_len;
/* Read the whole header data into memory, maximum memory use here is
* 2MB. */
if(!read_ahead(a, hdr_size, &p)) {
return ARCHIVE_EOF;
}
/* Verify the CRC32 of the header data. */
computed_crc = (uint32_t) crc32(0, p, (int) hdr_size);
if(computed_crc != hdr_crc) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Header CRC error");
return ARCHIVE_FATAL;
}
/* If the checksum is OK, we proceed with parsing. */
if(ARCHIVE_OK != consume(a, hdr_size_len)) {
return ARCHIVE_EOF;
}
if(!read_var_sized(a, &header_id, NULL))
return ARCHIVE_EOF;
if(!read_var_sized(a, &header_flags, NULL))
return ARCHIVE_EOF;
rar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0;
rar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0;
rar->generic.size = (int)hdr_size;
rar->generic.last_header_id = (int)header_id;
rar->main.endarc = 0;
/* Those are possible header ids in RARv5. */
switch(header_id) {
case HEAD_MAIN:
ret = process_head_main(a, rar, entry, header_flags);
/* Main header doesn't have any files in it, so it's
* pointless to return to the caller. Retry to next
* header, which should be HEAD_FILE/HEAD_SERVICE. */
if(ret == ARCHIVE_OK)
return ARCHIVE_RETRY;
return ret;
case HEAD_SERVICE:
ret = process_head_service(a, rar, entry, header_flags);
return ret;
case HEAD_FILE:
ret = process_head_file(a, rar, entry, header_flags);
return ret;
case HEAD_CRYPT:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Encryption is not supported");
return ARCHIVE_FATAL;
case HEAD_ENDARC:
rar->main.endarc = 1;
/* After encountering an end of file marker, we need
* to take into consideration if this archive is
* continued in another file (i.e. is it part01.rar:
* is there a part02.rar?) */
if(rar->main.volume) {
/* In case there is part02.rar, position the
* read pointer in a proper place, so we can
* resume parsing. */
ret = scan_for_signature(a);
if(ret == ARCHIVE_FATAL) {
return ARCHIVE_EOF;
} else {
if(rar->vol.expected_vol_no ==
UINT_MAX) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Header error");
return ARCHIVE_FATAL;
}
rar->vol.expected_vol_no =
rar->main.vol_no + 1;
return ARCHIVE_OK;
}
} else {
return ARCHIVE_EOF;
}
case HEAD_MARK:
return ARCHIVE_EOF;
default:
if((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Header type error");
return ARCHIVE_FATAL;
} else {
/* If the block is marked as 'skip if unknown',
* do as the flag says: skip the block
* instead on failing on it. */
return ARCHIVE_RETRY;
}
}
#if !defined WIN32
// Not reached.
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Internal unpacker error");
return ARCHIVE_FATAL;
#endif
}
static int skip_base_block(struct archive_read* a) {
int ret;
struct rar5* rar = get_context(a);
/* Create a new local archive_entry structure that will be operated on
* by header reader; operations on this archive_entry will be discarded.
*/
struct archive_entry* entry = archive_entry_new();
ret = process_base_block(a, entry);
/* Discard operations on this archive_entry structure. */
archive_entry_free(entry);
if(ret == ARCHIVE_FATAL)
return ret;
if(rar->generic.last_header_id == 2 && rar->generic.split_before > 0)
return ARCHIVE_OK;
if(ret == ARCHIVE_OK)
return ARCHIVE_RETRY;
else
return ret;
}
static int rar5_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct rar5* rar = get_context(a);
int ret;
if(rar->header_initialized == 0) {
init_header(a);
rar->header_initialized = 1;
}
if(rar->skipped_magic == 0) {
if(ARCHIVE_OK != consume(a, rar5_signature_size)) {
return ARCHIVE_EOF;
}
rar->skipped_magic = 1;
}
do {
ret = process_base_block(a, entry);
} while(ret == ARCHIVE_RETRY ||
(rar->main.endarc > 0 && ret == ARCHIVE_OK));
return ret;
}
static void init_unpack(struct rar5* rar) {
rar->file.calculated_crc32 = 0;
init_window_mask(rar);
free(rar->cstate.window_buf);
free(rar->cstate.filtered_buf);
if(rar->cstate.window_size > 0) {
rar->cstate.window_buf = calloc(1, rar->cstate.window_size);
rar->cstate.filtered_buf = calloc(1, rar->cstate.window_size);
} else {
rar->cstate.window_buf = NULL;
rar->cstate.filtered_buf = NULL;
}
rar->cstate.write_ptr = 0;
rar->cstate.last_write_ptr = 0;
memset(&rar->cstate.bd, 0, sizeof(rar->cstate.bd));
memset(&rar->cstate.ld, 0, sizeof(rar->cstate.ld));
memset(&rar->cstate.dd, 0, sizeof(rar->cstate.dd));
memset(&rar->cstate.ldd, 0, sizeof(rar->cstate.ldd));
memset(&rar->cstate.rd, 0, sizeof(rar->cstate.rd));
}
static void update_crc(struct rar5* rar, const uint8_t* p, size_t to_read) {
int verify_crc;
if(rar->skip_mode) {
#if defined CHECK_CRC_ON_SOLID_SKIP
verify_crc = 1;
#else
verify_crc = 0;
#endif
} else
verify_crc = 1;
if(verify_crc) {
/* Don't update CRC32 if the file doesn't have the
* `stored_crc32` info filled in. */
if(rar->file.stored_crc32 > 0) {
rar->file.calculated_crc32 =
crc32(rar->file.calculated_crc32, p, to_read);
}
/* Check if the file uses an optional BLAKE2sp checksum
* algorithm. */
if(rar->file.has_blake2 > 0) {
/* Return value of the `update` function is always 0,
* so we can explicitly ignore it here. */
(void) blake2sp_update(&rar->file.b2state, p, to_read);
}
}
}
static int create_decode_tables(uint8_t* bit_length,
struct decode_table* table, int size)
{
int code, upper_limit = 0, i, lc[16];
uint32_t decode_pos_clone[rar5_countof(table->decode_pos)];
ssize_t cur_len, quick_data_size;
memset(&lc, 0, sizeof(lc));
memset(table->decode_num, 0, sizeof(table->decode_num));
table->size = size;
table->quick_bits = size == HUFF_NC ? 10 : 7;
for(i = 0; i < size; i++) {
lc[bit_length[i] & 15]++;
}
lc[0] = 0;
table->decode_pos[0] = 0;
table->decode_len[0] = 0;
for(i = 1; i < 16; i++) {
upper_limit += lc[i];
table->decode_len[i] = upper_limit << (16 - i);
table->decode_pos[i] = table->decode_pos[i - 1] + lc[i - 1];
upper_limit <<= 1;
}
memcpy(decode_pos_clone, table->decode_pos, sizeof(decode_pos_clone));
for(i = 0; i < size; i++) {
uint8_t clen = bit_length[i] & 15;
if(clen > 0) {
int last_pos = decode_pos_clone[clen];
table->decode_num[last_pos] = i;
decode_pos_clone[clen]++;
}
}
quick_data_size = (int64_t)1 << table->quick_bits;
cur_len = 1;
for(code = 0; code < quick_data_size; code++) {
int bit_field = code << (16 - table->quick_bits);
int dist, pos;
while(cur_len < rar5_countof(table->decode_len) &&
bit_field >= table->decode_len[cur_len]) {
cur_len++;
}
table->quick_len[code] = (uint8_t) cur_len;
dist = bit_field - table->decode_len[cur_len - 1];
dist >>= (16 - cur_len);
pos = table->decode_pos[cur_len & 15] + dist;
if(cur_len < rar5_countof(table->decode_pos) && pos < size) {
table->quick_num[code] = table->decode_num[pos];
} else {
table->quick_num[code] = 0;
}
}
return ARCHIVE_OK;
}
static int decode_number(struct archive_read* a, struct decode_table* table,
const uint8_t* p, uint16_t* num)
{
int i, bits, dist;
uint16_t bitfield;
uint32_t pos;
struct rar5* rar = get_context(a);
if(ARCHIVE_OK != read_bits_16(rar, p, &bitfield)) {
return ARCHIVE_EOF;
}
bitfield &= 0xfffe;
if(bitfield < table->decode_len[table->quick_bits]) {
int code = bitfield >> (16 - table->quick_bits);
skip_bits(rar, table->quick_len[code]);
*num = table->quick_num[code];
return ARCHIVE_OK;
}
bits = 15;
for(i = table->quick_bits + 1; i < 15; i++) {
if(bitfield < table->decode_len[i]) {
bits = i;
break;
}
}
skip_bits(rar, bits);
dist = bitfield - table->decode_len[bits - 1];
dist >>= (16 - bits);
pos = table->decode_pos[bits] + dist;
if(pos >= table->size)
pos = 0;
*num = table->decode_num[pos];
return ARCHIVE_OK;
}
/* Reads and parses Huffman tables from the beginning of the block. */
static int parse_tables(struct archive_read* a, struct rar5* rar,
const uint8_t* p)
{
int ret, value, i, w, idx = 0;
uint8_t bit_length[HUFF_BC],
table[HUFF_TABLE_SIZE],
nibble_mask = 0xF0,
nibble_shift = 4;
enum { ESCAPE = 15 };
/* The data for table generation is compressed using a simple RLE-like
* algorithm when storing zeroes, so we need to unpack it first. */
for(w = 0, i = 0; w < HUFF_BC;) {
if(i >= rar->cstate.cur_block_size) {
/* Truncated data, can't continue. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated data in huffman tables");
return ARCHIVE_FATAL;
}
value = (p[i] & nibble_mask) >> nibble_shift;
if(nibble_mask == 0x0F)
++i;
nibble_mask ^= 0xFF;
nibble_shift ^= 4;
/* Values smaller than 15 is data, so we write it directly.
* Value 15 is a flag telling us that we need to unpack more
* bytes. */
if(value == ESCAPE) {
value = (p[i] & nibble_mask) >> nibble_shift;
if(nibble_mask == 0x0F)
++i;
nibble_mask ^= 0xFF;
nibble_shift ^= 4;
if(value == 0) {
/* We sometimes need to write the actual value
* of 15, so this case handles that. */
bit_length[w++] = ESCAPE;
} else {
int k;
/* Fill zeroes. */
for(k = 0; (k < value + 2) && (w < HUFF_BC);
k++) {
bit_length[w++] = 0;
}
}
} else {
bit_length[w++] = value;
}
}
rar->bits.in_addr = i;
rar->bits.bit_addr = nibble_shift ^ 4;
ret = create_decode_tables(bit_length, &rar->cstate.bd, HUFF_BC);
if(ret != ARCHIVE_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Decoding huffman tables failed");
return ARCHIVE_FATAL;
}
for(i = 0; i < HUFF_TABLE_SIZE;) {
uint16_t num;
if((rar->bits.in_addr + 6) >= rar->cstate.cur_block_size) {
/* Truncated data, can't continue. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated data in huffman tables (#2)");
return ARCHIVE_FATAL;
}
ret = decode_number(a, &rar->cstate.bd, p, &num);
if(ret != ARCHIVE_OK) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Decoding huffman tables failed");
return ARCHIVE_FATAL;
}
if(num < 16) {
/* 0..15: store directly */
table[i] = (uint8_t) num;
i++;
} else if(num < 18) {
/* 16..17: repeat previous code */
uint16_t n;
if(ARCHIVE_OK != read_bits_16(rar, p, &n))
return ARCHIVE_EOF;
if(num == 16) {
n >>= 13;
n += 3;
skip_bits(rar, 3);
} else {
n >>= 9;
n += 11;
skip_bits(rar, 7);
}
if(i > 0) {
while(n-- > 0 && i < HUFF_TABLE_SIZE) {
table[i] = table[i - 1];
i++;
}
} else {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unexpected error when decoding "
"huffman tables");
return ARCHIVE_FATAL;
}
} else {
/* other codes: fill with zeroes `n` times */
uint16_t n;
if(ARCHIVE_OK != read_bits_16(rar, p, &n))
return ARCHIVE_EOF;
if(num == 18) {
n >>= 13;
n += 3;
skip_bits(rar, 3);
} else {
n >>= 9;
n += 11;
skip_bits(rar, 7);
}
while(n-- > 0 && i < HUFF_TABLE_SIZE)
table[i++] = 0;
}
}
ret = create_decode_tables(&table[idx], &rar->cstate.ld, HUFF_NC);
if(ret != ARCHIVE_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Failed to create literal table");
return ARCHIVE_FATAL;
}
idx += HUFF_NC;
ret = create_decode_tables(&table[idx], &rar->cstate.dd, HUFF_DC);
if(ret != ARCHIVE_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Failed to create distance table");
return ARCHIVE_FATAL;
}
idx += HUFF_DC;
ret = create_decode_tables(&table[idx], &rar->cstate.ldd, HUFF_LDC);
if(ret != ARCHIVE_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Failed to create lower bits of distances table");
return ARCHIVE_FATAL;
}
idx += HUFF_LDC;
ret = create_decode_tables(&table[idx], &rar->cstate.rd, HUFF_RC);
if(ret != ARCHIVE_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Failed to create repeating distances table");
return ARCHIVE_FATAL;
}
return ARCHIVE_OK;
}
/* Parses the block header, verifies its CRC byte, and saves the header
* fields inside the `hdr` pointer. */
static int parse_block_header(struct archive_read* a, const uint8_t* p,
ssize_t* block_size, struct compressed_block_header* hdr)
{
uint8_t calculated_cksum;
memcpy(hdr, p, sizeof(struct compressed_block_header));
if(bf_byte_count(hdr) > 2) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported block header size (was %d, max is 2)",
bf_byte_count(hdr));
return ARCHIVE_FATAL;
}
/* This should probably use bit reader interface in order to be more
* future-proof. */
*block_size = 0;
switch(bf_byte_count(hdr)) {
/* 1-byte block size */
case 0:
*block_size = *(const uint8_t*) &p[2];
break;
/* 2-byte block size */
case 1:
*block_size = archive_le16dec(&p[2]);
break;
/* 3-byte block size */
case 2:
*block_size = archive_le32dec(&p[2]);
*block_size &= 0x00FFFFFF;
break;
/* Other block sizes are not supported. This case is not
* reached, because we have an 'if' guard before the switch
* that makes sure of it. */
default:
return ARCHIVE_FATAL;
}
/* Verify the block header checksum. 0x5A is a magic value and is
* always * constant. */
calculated_cksum = 0x5A
^ (uint8_t) hdr->block_flags_u8
^ (uint8_t) *block_size
^ (uint8_t) (*block_size >> 8)
^ (uint8_t) (*block_size >> 16);
if(calculated_cksum != hdr->block_cksum) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Block checksum error: got 0x%x, expected 0x%x",
hdr->block_cksum, calculated_cksum);
return ARCHIVE_FATAL;
}
return ARCHIVE_OK;
}
/* Convenience function used during filter processing. */
static int parse_filter_data(struct rar5* rar, const uint8_t* p,
uint32_t* filter_data)
{
int i, bytes;
uint32_t data = 0;
if(ARCHIVE_OK != read_consume_bits(rar, p, 2, &bytes))
return ARCHIVE_EOF;
bytes++;
for(i = 0; i < bytes; i++) {
uint16_t byte;
if(ARCHIVE_OK != read_bits_16(rar, p, &byte)) {
return ARCHIVE_EOF;
}
/* Cast to uint32_t will ensure the shift operation will not
* produce undefined result. */
data += ((uint32_t) byte >> 8) << (i * 8);
skip_bits(rar, 8);
}
*filter_data = data;
return ARCHIVE_OK;
}
/* Function is used during sanity checking. */
static int is_valid_filter_block_start(struct rar5* rar,
uint32_t start)
{
const int64_t block_start = (ssize_t) start + rar->cstate.write_ptr;
const int64_t last_bs = rar->cstate.last_block_start;
const ssize_t last_bl = rar->cstate.last_block_length;
if(last_bs == 0 || last_bl == 0) {
/* We didn't have any filters yet, so accept this offset. */
return 1;
}
if(block_start >= last_bs + last_bl) {
/* Current offset is bigger than last block's end offset, so
* accept current offset. */
return 1;
}
/* Any other case is not a normal situation and we should fail. */
return 0;
}
/* The function will create a new filter, read its parameters from the input
* stream and add it to the filter collection. */
static int parse_filter(struct archive_read* ar, const uint8_t* p) {
uint32_t block_start, block_length;
uint16_t filter_type;
struct filter_info* filt = NULL;
struct rar5* rar = get_context(ar);
/* Read the parameters from the input stream. */
if(ARCHIVE_OK != parse_filter_data(rar, p, &block_start))
return ARCHIVE_EOF;
if(ARCHIVE_OK != parse_filter_data(rar, p, &block_length))
return ARCHIVE_EOF;
if(ARCHIVE_OK != read_bits_16(rar, p, &filter_type))
return ARCHIVE_EOF;
filter_type >>= 13;
skip_bits(rar, 3);
/* Perform some sanity checks on this filter parameters. Note that we
* allow only DELTA, E8/E9 and ARM filters here, because rest of
* filters are not used in RARv5. */
if(block_length < 4 ||
block_length > 0x400000 ||
filter_type > FILTER_ARM ||
!is_valid_filter_block_start(rar, block_start))
{
archive_set_error(&ar->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Invalid filter encountered");
return ARCHIVE_FATAL;
}
/* Allocate a new filter. */
filt = add_new_filter(rar);
if(filt == NULL) {
archive_set_error(&ar->archive, ENOMEM,
"Can't allocate memory for a filter descriptor.");
return ARCHIVE_FATAL;
}
filt->type = filter_type;
filt->block_start = rar->cstate.write_ptr + block_start;
filt->block_length = block_length;
rar->cstate.last_block_start = filt->block_start;
rar->cstate.last_block_length = filt->block_length;
/* Read some more data in case this is a DELTA filter. Other filter
* types don't require any additional data over what was already
* read. */
if(filter_type == FILTER_DELTA) {
int channels;
if(ARCHIVE_OK != read_consume_bits(rar, p, 5, &channels))
return ARCHIVE_EOF;
filt->channels = channels + 1;
}
return ARCHIVE_OK;
}
static int decode_code_length(struct rar5* rar, const uint8_t* p,
uint16_t code)
{
int lbits, length = 2;
if(code < 8) {
lbits = 0;
length += code;
} else {
lbits = code / 4 - 1;
length += (4 | (code & 3)) << lbits;
}
if(lbits > 0) {
int add;
if(ARCHIVE_OK != read_consume_bits(rar, p, lbits, &add))
return -1;
length += add;
}
return length;
}
static int copy_string(struct archive_read* a, int len, int dist) {
struct rar5* rar = get_context(a);
const uint64_t cmask = rar->cstate.window_mask;
const uint64_t write_ptr = rar->cstate.write_ptr +
rar->cstate.solid_offset;
int i;
if (rar->cstate.window_buf == NULL)
return ARCHIVE_FATAL;
/* The unpacker spends most of the time in this function. It would be
* a good idea to introduce some optimizations here.
*
* Just remember that this loop treats buffers that overlap differently
* than buffers that do not overlap. This is why a simple memcpy(3)
* call will not be enough. */
for(i = 0; i < len; i++) {
const ssize_t write_idx = (write_ptr + i) & cmask;
const ssize_t read_idx = (write_ptr + i - dist) & cmask;
rar->cstate.window_buf[write_idx] =
rar->cstate.window_buf[read_idx];
}
rar->cstate.write_ptr += len;
return ARCHIVE_OK;
}
static int do_uncompress_block(struct archive_read* a, const uint8_t* p) {
struct rar5* rar = get_context(a);
uint16_t num;
int ret;
const uint64_t cmask = rar->cstate.window_mask;
const struct compressed_block_header* hdr = &rar->last_block_hdr;
const uint8_t bit_size = 1 + bf_bit_size(hdr);
while(1) {
if(rar->cstate.write_ptr - rar->cstate.last_write_ptr >
(rar->cstate.window_size >> 1)) {
/* Don't allow growing data by more than half of the
* window size at a time. In such case, break the loop;
* next call to this function will continue processing
* from this moment. */
break;
}
if(rar->bits.in_addr > rar->cstate.cur_block_size - 1 ||
(rar->bits.in_addr == rar->cstate.cur_block_size - 1 &&
rar->bits.bit_addr >= bit_size))
{
/* If the program counter is here, it means the
* function has finished processing the block. */
rar->cstate.block_parsing_finished = 1;
break;
}
/* Decode the next literal. */
if(ARCHIVE_OK != decode_number(a, &rar->cstate.ld, p, &num)) {
return ARCHIVE_EOF;
}
/* Num holds a decompression literal, or 'command code'.
*
* - Values lower than 256 are just bytes. Those codes
* can be stored in the output buffer directly.
*
* - Code 256 defines a new filter, which is later used to
* ransform the data block accordingly to the filter type.
* The data block needs to be fully uncompressed first.
*
* - Code bigger than 257 and smaller than 262 define
* a repetition pattern that should be copied from
* an already uncompressed chunk of data.
*/
if(num < 256) {
/* Directly store the byte. */
int64_t write_idx = rar->cstate.solid_offset +
rar->cstate.write_ptr++;
rar->cstate.window_buf[write_idx & cmask] =
(uint8_t) num;
continue;
} else if(num >= 262) {
uint16_t dist_slot;
int len = decode_code_length(rar, p, num - 262),
dbits,
dist = 1;
if(len == -1) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_PROGRAMMER,
"Failed to decode the code length");
return ARCHIVE_FATAL;
}
if(ARCHIVE_OK != decode_number(a, &rar->cstate.dd, p,
&dist_slot))
{
archive_set_error(&a->archive,
ARCHIVE_ERRNO_PROGRAMMER,
"Failed to decode the distance slot");
return ARCHIVE_FATAL;
}
if(dist_slot < 4) {
dbits = 0;
dist += dist_slot;
} else {
dbits = dist_slot / 2 - 1;
/* Cast to uint32_t will make sure the shift
* left operation won't produce undefined
* result. Then, the uint32_t type will
* be implicitly casted to int. */
dist += (uint32_t) (2 |
(dist_slot & 1)) << dbits;
}
if(dbits > 0) {
if(dbits >= 4) {
uint32_t add = 0;
uint16_t low_dist;
if(dbits > 4) {
if(ARCHIVE_OK != read_bits_32(
rar, p, &add)) {
/* Return EOF if we
* can't read more
* data. */
return ARCHIVE_EOF;
}
skip_bits(rar, dbits - 4);
add = (add >> (
36 - dbits)) << 4;
dist += add;
}
if(ARCHIVE_OK != decode_number(a,
&rar->cstate.ldd, p, &low_dist))
{
archive_set_error(&a->archive,
ARCHIVE_ERRNO_PROGRAMMER,
"Failed to decode the "
"distance slot");
return ARCHIVE_FATAL;
}
if(dist >= INT_MAX - low_dist - 1) {
/* This only happens in
* invalid archives. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Distance pointer "
"overflow");
return ARCHIVE_FATAL;
}
dist += low_dist;
} else {
/* dbits is one of [0,1,2,3] */
int add;
if(ARCHIVE_OK != read_consume_bits(rar,
p, dbits, &add)) {
/* Return EOF if we can't read
* more data. */
return ARCHIVE_EOF;
}
dist += add;
}
}
if(dist > 0x100) {
len++;
if(dist > 0x2000) {
len++;
if(dist > 0x40000) {
len++;
}
}
}
dist_cache_push(rar, dist);
rar->cstate.last_len = len;
if(ARCHIVE_OK != copy_string(a, len, dist))
return ARCHIVE_FATAL;
continue;
} else if(num == 256) {
/* Create a filter. */
ret = parse_filter(a, p);
if(ret != ARCHIVE_OK)
return ret;
continue;
} else if(num == 257) {
if(rar->cstate.last_len != 0) {
if(ARCHIVE_OK != copy_string(a,
rar->cstate.last_len,
rar->cstate.dist_cache[0]))
{
return ARCHIVE_FATAL;
}
}
continue;
} else {
/* num < 262 */
const int idx = num - 258;
const int dist = dist_cache_touch(rar, idx);
uint16_t len_slot;
int len;
if(ARCHIVE_OK != decode_number(a, &rar->cstate.rd, p,
&len_slot)) {
return ARCHIVE_FATAL;
}
len = decode_code_length(rar, p, len_slot);
rar->cstate.last_len = len;
if(ARCHIVE_OK != copy_string(a, len, dist))
return ARCHIVE_FATAL;
continue;
}
/* The program counter shouldn't reach here. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported block code: 0x%x", num);
return ARCHIVE_FATAL;
}
return ARCHIVE_OK;
}
/* Binary search for the RARv5 signature. */
static int scan_for_signature(struct archive_read* a) {
const uint8_t* p;
const int chunk_size = 512;
ssize_t i;
/* If we're here, it means we're on an 'unknown territory' data.
* There's no indication what kind of data we're reading here.
* It could be some text comment, any kind of binary data,
* digital sign, dragons, etc.
*
* We want to find a valid RARv5 magic header inside this unknown
* data. */
/* Is it possible in libarchive to just skip everything until the
* end of the file? If so, it would be a better approach than the
* current implementation of this function. */
while(1) {
if(!read_ahead(a, chunk_size, &p))
return ARCHIVE_EOF;
for(i = 0; i < chunk_size - rar5_signature_size; i++) {
if(memcmp(&p[i], rar5_signature,
rar5_signature_size) == 0) {
/* Consume the number of bytes we've used to
* search for the signature, as well as the
* number of bytes used by the signature
* itself. After this we should be standing
* on a valid base block header. */
(void) consume(a, i + rar5_signature_size);
return ARCHIVE_OK;
}
}
consume(a, chunk_size);
}
return ARCHIVE_FATAL;
}
/* This function will switch the multivolume archive file to another file,
* i.e. from part03 to part 04. */
static int advance_multivolume(struct archive_read* a) {
int lret;
struct rar5* rar = get_context(a);
/* A small state machine that will skip unnecessary data, needed to
* switch from one multivolume to another. Such skipping is needed if
* we want to be an stream-oriented (instead of file-oriented)
* unpacker.
*
* The state machine starts with `rar->main.endarc` == 0. It also
* assumes that current stream pointer points to some base block
* header.
*
* The `endarc` field is being set when the base block parsing
* function encounters the 'end of archive' marker.
*/
while(1) {
if(rar->main.endarc == 1) {
int looping = 1;
rar->main.endarc = 0;
while(looping) {
lret = skip_base_block(a);
switch(lret) {
case ARCHIVE_RETRY:
/* Continue looping. */
break;
case ARCHIVE_OK:
/* Break loop. */
looping = 0;
break;
default:
/* Forward any errors to the
* caller. */
return lret;
}
}
break;
} else {
/* Skip current base block. In order to properly skip
* it, we really need to simply parse it and discard
* the results. */
lret = skip_base_block(a);
if(lret == ARCHIVE_FATAL || lret == ARCHIVE_FAILED)
return lret;
/* The `skip_base_block` function tells us if we
* should continue with skipping, or we should stop
* skipping. We're trying to skip everything up to
* a base FILE block. */
if(lret != ARCHIVE_RETRY) {
/* If there was an error during skipping, or we
* have just skipped a FILE base block... */
if(rar->main.endarc == 0) {
return lret;
} else {
continue;
}
}
}
}
return ARCHIVE_OK;
}
/* Merges the partial block from the first multivolume archive file, and
* partial block from the second multivolume archive file. The result is
* a chunk of memory containing the whole block, and the stream pointer
* is advanced to the next block in the second multivolume archive file. */
static int merge_block(struct archive_read* a, ssize_t block_size,
const uint8_t** p)
{
struct rar5* rar = get_context(a);
ssize_t cur_block_size, partial_offset = 0;
const uint8_t* lp;
int ret;
if(rar->merge_mode) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Recursive merge is not allowed");
return ARCHIVE_FATAL;
}
/* Set a flag that we're in the switching mode. */
rar->cstate.switch_multivolume = 1;
/* Reallocate the memory which will hold the whole block. */
if(rar->vol.push_buf)
free((void*) rar->vol.push_buf);
/* Increasing the allocation block by 8 is due to bit reading functions,
* which are using additional 2 or 4 bytes. Allocating the block size
* by exact value would make bit reader perform reads from invalid
* memory block when reading the last byte from the buffer. */
rar->vol.push_buf = malloc(block_size + 8);
if(!rar->vol.push_buf) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for a merge block buffer.");
return ARCHIVE_FATAL;
}
/* Valgrind complains if the extension block for bit reader is not
* initialized, so initialize it. */
memset(&rar->vol.push_buf[block_size], 0, 8);
/* A single block can span across multiple multivolume archive files,
* so we use a loop here. This loop will consume enough multivolume
* archive files until the whole block is read. */
while(1) {
/* Get the size of current block chunk in this multivolume
* archive file and read it. */
cur_block_size = rar5_min(rar->file.bytes_remaining,
block_size - partial_offset);
if(cur_block_size == 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Encountered block size == 0 during block merge");
return ARCHIVE_FATAL;
}
if(!read_ahead(a, cur_block_size, &lp))
return ARCHIVE_EOF;
/* Sanity check; there should never be a situation where this
* function reads more data than the block's size. */
if(partial_offset + cur_block_size > block_size) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_PROGRAMMER,
"Consumed too much data when merging blocks.");
return ARCHIVE_FATAL;
}
/* Merge previous block chunk with current block chunk,
* or create first block chunk if this is our first
* iteration. */
memcpy(&rar->vol.push_buf[partial_offset], lp, cur_block_size);
/* Advance the stream read pointer by this block chunk size. */
if(ARCHIVE_OK != consume(a, cur_block_size))
return ARCHIVE_EOF;
/* Update the pointers. `partial_offset` contains information
* about the sum of merged block chunks. */
partial_offset += cur_block_size;
rar->file.bytes_remaining -= cur_block_size;
/* If `partial_offset` is the same as `block_size`, this means
* we've merged all block chunks and we have a valid full
* block. */
if(partial_offset == block_size) {
break;
}
/* If we don't have any bytes to read, this means we should
* switch to another multivolume archive file. */
if(rar->file.bytes_remaining == 0) {
rar->merge_mode++;
ret = advance_multivolume(a);
rar->merge_mode--;
if(ret != ARCHIVE_OK) {
return ret;
}
}
}
*p = rar->vol.push_buf;
/* If we're here, we can resume unpacking by processing the block
* pointed to by the `*p` memory pointer. */
return ARCHIVE_OK;
}
static int process_block(struct archive_read* a) {
const uint8_t* p;
struct rar5* rar = get_context(a);
int ret;
/* If we don't have any data to be processed, this most probably means
* we need to switch to the next volume. */
if(rar->main.volume && rar->file.bytes_remaining == 0) {
ret = advance_multivolume(a);
if(ret != ARCHIVE_OK)
return ret;
}
if(rar->cstate.block_parsing_finished) {
ssize_t block_size;
ssize_t to_skip;
ssize_t cur_block_size;
/* The header size won't be bigger than 6 bytes. */
if(!read_ahead(a, 6, &p)) {
/* Failed to prefetch data block header. */
return ARCHIVE_EOF;
}
/*
* Read block_size by parsing block header. Validate the header
* by calculating CRC byte stored inside the header. Size of
* the header is not constant (block size can be stored either
* in 1 or 2 bytes), that's why block size is left out from the
* `compressed_block_header` structure and returned by
* `parse_block_header` as the second argument. */
ret = parse_block_header(a, p, &block_size,
&rar->last_block_hdr);
if(ret != ARCHIVE_OK) {
return ret;
}
/* Skip block header. Next data is huffman tables,
* if present. */
to_skip = sizeof(struct compressed_block_header) +
bf_byte_count(&rar->last_block_hdr) + 1;
if(ARCHIVE_OK != consume(a, to_skip))
return ARCHIVE_EOF;
rar->file.bytes_remaining -= to_skip;
/* The block size gives information about the whole block size,
* but the block could be stored in split form when using
* multi-volume archives. In this case, the block size will be
* bigger than the actual data stored in this file. Remaining
* part of the data will be in another file. */
cur_block_size =
rar5_min(rar->file.bytes_remaining, block_size);
if(block_size > rar->file.bytes_remaining) {
/* If current blocks' size is bigger than our data
* size, this means we have a multivolume archive.
* In this case, skip all base headers until the end
* of the file, proceed to next "partXXX.rar" volume,
* find its signature, skip all headers up to the first
* FILE base header, and continue from there.
*
* Note that `merge_block` will update the `rar`
* context structure quite extensively. */
ret = merge_block(a, block_size, &p);
if(ret != ARCHIVE_OK) {
return ret;
}
cur_block_size = block_size;
/* Current stream pointer should be now directly
* *after* the block that spanned through multiple
* archive files. `p` pointer should have the data of
* the *whole* block (merged from partial blocks
* stored in multiple archives files). */
} else {
rar->cstate.switch_multivolume = 0;
/* Read the whole block size into memory. This can take
* up to 8 megabytes of memory in theoretical cases.
* Might be worth to optimize this and use a standard
* chunk of 4kb's. */
if(!read_ahead(a, 4 + cur_block_size, &p)) {
/* Failed to prefetch block data. */
return ARCHIVE_EOF;
}
}
rar->cstate.block_buf = p;
rar->cstate.cur_block_size = cur_block_size;
rar->cstate.block_parsing_finished = 0;
rar->bits.in_addr = 0;
rar->bits.bit_addr = 0;
if(bf_is_table_present(&rar->last_block_hdr)) {
/* Load Huffman tables. */
ret = parse_tables(a, rar, p);
if(ret != ARCHIVE_OK) {
/* Error during decompression of Huffman
* tables. */
return ret;
}
}
} else {
/* Block parsing not finished, reuse previous memory buffer. */
p = rar->cstate.block_buf;
}
/* Uncompress the block, or a part of it, depending on how many bytes
* will be generated by uncompressing the block.
*
* In case too many bytes will be generated, calling this function
* again will resume the uncompression operation. */
ret = do_uncompress_block(a, p);
if(ret != ARCHIVE_OK) {
return ret;
}
if(rar->cstate.block_parsing_finished &&
rar->cstate.switch_multivolume == 0 &&
rar->cstate.cur_block_size > 0)
{
/* If we're processing a normal block, consume the whole
* block. We can do this because we've already read the whole
* block to memory. */
if(ARCHIVE_OK != consume(a, rar->cstate.cur_block_size))
return ARCHIVE_FATAL;
rar->file.bytes_remaining -= rar->cstate.cur_block_size;
} else if(rar->cstate.switch_multivolume) {
/* Don't consume the block if we're doing multivolume
* processing. The volume switching function will consume
* the proper count of bytes instead. */
rar->cstate.switch_multivolume = 0;
}
return ARCHIVE_OK;
}
/* Pops the `buf`, `size` and `offset` from the "data ready" stack.
*
* Returns ARCHIVE_OK when those arguments can be used, ARCHIVE_RETRY
* when there is no data on the stack. */
static int use_data(struct rar5* rar, const void** buf, size_t* size,
int64_t* offset)
{
int i;
for(i = 0; i < rar5_countof(rar->cstate.dready); i++) {
struct data_ready *d = &rar->cstate.dready[i];
if(d->used) {
if(buf) *buf = d->buf;
if(size) *size = d->size;
if(offset) *offset = d->offset;
d->used = 0;
return ARCHIVE_OK;
}
}
return ARCHIVE_RETRY;
}
/* Pushes the `buf`, `size` and `offset` arguments to the rar->cstate.dready
* FIFO stack. Those values will be popped from this stack by the `use_data`
* function. */
static int push_data_ready(struct archive_read* a, struct rar5* rar,
const uint8_t* buf, size_t size, int64_t offset)
{
int i;
/* Don't push if we're in skip mode. This is needed because solid
* streams need full processing even if we're skipping data. After
* fully processing the stream, we need to discard the generated bytes,
* because we're interested only in the side effect: building up the
* internal window circular buffer. This window buffer will be used
* later during unpacking of requested data. */
if(rar->skip_mode)
return ARCHIVE_OK;
/* Sanity check. */
if(offset != rar->file.last_offset + rar->file.last_size) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Sanity check error: output stream is not continuous");
return ARCHIVE_FATAL;
}
for(i = 0; i < rar5_countof(rar->cstate.dready); i++) {
struct data_ready* d = &rar->cstate.dready[i];
if(!d->used) {
d->used = 1;
d->buf = buf;
d->size = size;
d->offset = offset;
/* These fields are used only in sanity checking. */
rar->file.last_offset = offset;
rar->file.last_size = size;
/* Calculate the checksum of this new block before
* submitting data to libarchive's engine. */
update_crc(rar, d->buf, d->size);
return ARCHIVE_OK;
}
}
/* Program counter will reach this code if the `rar->cstate.data_ready`
* stack will be filled up so that no new entries will be allowed. The
* code shouldn't allow such situation to occur. So we treat this case
* as an internal error. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Error: premature end of data_ready stack");
return ARCHIVE_FATAL;
}
/* This function uncompresses the data that is stored in the <FILE> base
* block.
*
* The FILE base block looks like this:
*
* <header><huffman tables><block_1><block_2>...<block_n>
*
* The <header> is a block header, that is parsed in parse_block_header().
* It's a "compressed_block_header" structure, containing metadata needed
* to know when we should stop looking for more <block_n> blocks.
*
* <huffman tables> contain data needed to set up the huffman tables, needed
* for the actual decompression.
*
* Each <block_n> consists of series of literals:
*
* <literal><literal><literal>...<literal>
*
* Those literals generate the uncompression data. They operate on a circular
* buffer, sometimes writing raw data into it, sometimes referencing
* some previous data inside this buffer, and sometimes declaring a filter
* that will need to be executed on the data stored in the circular buffer.
* It all depends on the literal that is used.
*
* Sometimes blocks produce output data, sometimes they don't. For example, for
* some huge files that use lots of filters, sometimes a block is filled with
* only filter declaration literals. Such blocks won't produce any data in the
* circular buffer.
*
* Sometimes blocks will produce 4 bytes of data, and sometimes 1 megabyte,
* because a literal can reference previously decompressed data. For example,
* there can be a literal that says: 'append a byte 0xFE here', and after
* it another literal can say 'append 1 megabyte of data from circular buffer
* offset 0x12345'. This is how RAR format handles compressing repeated
* patterns.
*
* The RAR compressor creates those literals and the actual efficiency of
* compression depends on what those literals are. The literals can also
* be seen as a kind of a non-turing-complete virtual machine that simply
* tells the decompressor what it should do.
* */
static int do_uncompress_file(struct archive_read* a) {
struct rar5* rar = get_context(a);
int ret;
int64_t max_end_pos;
if(!rar->cstate.initialized) {
/* Don't perform full context reinitialization if we're
* processing a solid archive. */
if(!rar->main.solid || !rar->cstate.window_buf) {
init_unpack(rar);
}
rar->cstate.initialized = 1;
}
if(rar->cstate.all_filters_applied == 1) {
/* We use while(1) here, but standard case allows for just 1
* iteration. The loop will iterate if process_block() didn't
* generate any data at all. This can happen if the block
* contains only filter definitions (this is common in big
* files). */
while(1) {
ret = process_block(a);
if(ret == ARCHIVE_EOF || ret == ARCHIVE_FATAL)
return ret;
if(rar->cstate.last_write_ptr ==
rar->cstate.write_ptr) {
/* The block didn't generate any new data,
* so just process a new block. */
continue;
}
/* The block has generated some new data, so break
* the loop. */
break;
}
}
/* Try to run filters. If filters won't be applied, it means that
* insufficient data was generated. */
ret = apply_filters(a);
if(ret == ARCHIVE_RETRY) {
return ARCHIVE_OK;
} else if(ret == ARCHIVE_FATAL) {
return ARCHIVE_FATAL;
}
/* If apply_filters() will return ARCHIVE_OK, we can continue here. */
if(cdeque_size(&rar->cstate.filters) > 0) {
/* Check if we can write something before hitting first
* filter. */
struct filter_info* flt;
/* Get the block_start offset from the first filter. */
if(CDE_OK != cdeque_front(&rar->cstate.filters,
cdeque_filter_p(&flt)))
{
archive_set_error(&a->archive,
ARCHIVE_ERRNO_PROGRAMMER,
"Can't read first filter");
return ARCHIVE_FATAL;
}
max_end_pos = rar5_min(flt->block_start,
rar->cstate.write_ptr);
} else {
/* There are no filters defined, or all filters were applied.
* This means we can just store the data without any
* postprocessing. */
max_end_pos = rar->cstate.write_ptr;
}
if(max_end_pos == rar->cstate.last_write_ptr) {
/* We can't write anything yet. The block uncompression
* function did not generate enough data, and no filter can be
* applied. At the same time we don't have any data that can be
* stored without filter postprocessing. This means we need to
* wait for more data to be generated, so we can apply the
* filters.
*
* Signal the caller that we need more data to be able to do
* anything.
*/
return ARCHIVE_RETRY;
} else {
/* We can write the data before hitting the first filter.
* So let's do it. The push_window_data() function will
* effectively return the selected data block to the user
* application. */
push_window_data(a, rar, rar->cstate.last_write_ptr,
max_end_pos);
rar->cstate.last_write_ptr = max_end_pos;
}
return ARCHIVE_OK;
}
static int uncompress_file(struct archive_read* a) {
int ret;
while(1) {
/* Sometimes the uncompression function will return a
* 'retry' signal. If this will happen, we have to retry
* the function. */
ret = do_uncompress_file(a);
if(ret != ARCHIVE_RETRY)
return ret;
}
}
static int do_unstore_file(struct archive_read* a,
struct rar5* rar, const void** buf, size_t* size, int64_t* offset)
{
size_t to_read;
const uint8_t* p;
if(rar->file.bytes_remaining == 0 && rar->main.volume > 0 &&
rar->generic.split_after > 0)
{
int ret;
rar->cstate.switch_multivolume = 1;
ret = advance_multivolume(a);
rar->cstate.switch_multivolume = 0;
if(ret != ARCHIVE_OK) {
/* Failed to advance to next multivolume archive
* file. */
return ret;
}
}
to_read = rar5_min(rar->file.bytes_remaining, 64 * 1024);
if(to_read == 0) {
return ARCHIVE_EOF;
}
if(!read_ahead(a, to_read, &p)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"I/O error when unstoring file");
return ARCHIVE_FATAL;
}
if(ARCHIVE_OK != consume(a, to_read)) {
return ARCHIVE_EOF;
}
if(buf) *buf = p;
if(size) *size = to_read;
if(offset) *offset = rar->cstate.last_unstore_ptr;
rar->file.bytes_remaining -= to_read;
rar->cstate.last_unstore_ptr += to_read;
update_crc(rar, p, to_read);
return ARCHIVE_OK;
}
static int do_unpack(struct archive_read* a, struct rar5* rar,
const void** buf, size_t* size, int64_t* offset)
{
enum COMPRESSION_METHOD {
STORE = 0, FASTEST = 1, FAST = 2, NORMAL = 3, GOOD = 4,
BEST = 5
};
if(rar->file.service > 0) {
return do_unstore_file(a, rar, buf, size, offset);
} else {
switch(rar->cstate.method) {
case STORE:
return do_unstore_file(a, rar, buf, size,
offset);
case FASTEST:
/* fallthrough */
case FAST:
/* fallthrough */
case NORMAL:
/* fallthrough */
case GOOD:
/* fallthrough */
case BEST:
return uncompress_file(a);
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Compression method not supported: 0x%x",
rar->cstate.method);
return ARCHIVE_FATAL;
}
}
#if !defined WIN32
/* Not reached. */
return ARCHIVE_OK;
#endif
}
static int verify_checksums(struct archive_read* a) {
int verify_crc;
struct rar5* rar = get_context(a);
/* Check checksums only when actually unpacking the data. There's no
* need to calculate checksum when we're skipping data in solid archives
* (skipping in solid archives is the same thing as unpacking compressed
* data and discarding the result). */
if(!rar->skip_mode) {
/* Always check checksums if we're not in skip mode */
verify_crc = 1;
} else {
/* We can override the logic above with a compile-time option
* NO_CRC_ON_SOLID_SKIP. This option is used during debugging,
* and it will check checksums of unpacked data even when
* we're skipping it. */
#if defined CHECK_CRC_ON_SOLID_SKIP
/* Debug case */
verify_crc = 1;
#else
/* Normal case */
verify_crc = 0;
#endif
}
if(verify_crc) {
/* During unpacking, on each unpacked block we're calling the
* update_crc() function. Since we are here, the unpacking
* process is already over and we can check if calculated
* checksum (CRC32 or BLAKE2sp) is the same as what is stored
* in the archive. */
if(rar->file.stored_crc32 > 0) {
/* Check CRC32 only when the file contains a CRC32
* value for this file. */
if(rar->file.calculated_crc32 !=
rar->file.stored_crc32) {
/* Checksums do not match; the unpacked file
* is corrupted. */
DEBUG_CODE {
printf("Checksum error: CRC32 "
"(was: %08x, expected: %08x)\n",
rar->file.calculated_crc32,
rar->file.stored_crc32);
}
#ifndef DONT_FAIL_ON_CRC_ERROR
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Checksum error: CRC32");
return ARCHIVE_FATAL;
#endif
} else {
DEBUG_CODE {
printf("Checksum OK: CRC32 "
"(%08x/%08x)\n",
rar->file.stored_crc32,
rar->file.calculated_crc32);
}
}
}
if(rar->file.has_blake2 > 0) {
/* BLAKE2sp is an optional checksum algorithm that is
* added to RARv5 archives when using the `-htb` switch
* during creation of archive.
*
* We now finalize the hash calculation by calling the
* `final` function. This will generate the final hash
* value we can use to compare it with the BLAKE2sp
* checksum that is stored in the archive.
*
* The return value of this `final` function is not
* very helpful, as it guards only against improper use.
* This is why we're explicitly ignoring it. */
uint8_t b2_buf[32];
(void) blake2sp_final(&rar->file.b2state, b2_buf, 32);
if(memcmp(&rar->file.blake2sp, b2_buf, 32) != 0) {
#ifndef DONT_FAIL_ON_CRC_ERROR
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Checksum error: BLAKE2");
return ARCHIVE_FATAL;
#endif
}
}
}
/* Finalization for this file has been successfully completed. */
return ARCHIVE_OK;
}
static int verify_global_checksums(struct archive_read* a) {
return verify_checksums(a);
}
static int rar5_read_data(struct archive_read *a, const void **buff,
size_t *size, int64_t *offset) {
int ret;
struct rar5* rar = get_context(a);
if(rar->file.dir > 0) {
/* Don't process any data if this file entry was declared
* as a directory. This is needed, because entries marked as
* directory doesn't have any dictionary buffer allocated, so
* it's impossible to perform any decompression. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Can't decompress an entry marked as a directory");
return ARCHIVE_FAILED;
}
if(!rar->skip_mode && (rar->cstate.last_write_ptr > rar->file.unpacked_size)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
"Unpacker has written too many bytes");
return ARCHIVE_FATAL;
}
ret = use_data(rar, buff, size, offset);
if(ret == ARCHIVE_OK) {
return ret;
}
if(rar->file.eof == 1) {
return ARCHIVE_EOF;
}
ret = do_unpack(a, rar, buff, size, offset);
if(ret != ARCHIVE_OK) {
return ret;
}
if(rar->file.bytes_remaining == 0 &&
rar->cstate.last_write_ptr == rar->file.unpacked_size)
{
/* If all bytes of current file were processed, run
* finalization.
*
* Finalization will check checksum against proper values. If
* some of the checksums will not match, we'll return an error
* value in the last `archive_read_data` call to signal an error
* to the user. */
rar->file.eof = 1;
return verify_global_checksums(a);
}
return ARCHIVE_OK;
}
static int rar5_read_data_skip(struct archive_read *a) {
struct rar5* rar = get_context(a);
if(rar->main.solid) {
/* In solid archives, instead of skipping the data, we need to
* extract it, and dispose the result. The side effect of this
* operation will be setting up the initial window buffer state
* needed to be able to extract the selected file. */
int ret;
/* Make sure to process all blocks in the compressed stream. */
while(rar->file.bytes_remaining > 0) {
/* Setting the "skip mode" will allow us to skip
* checksum checks during data skipping. Checking the
* checksum of skipped data isn't really necessary and
* it's only slowing things down.
*
* This is incremented instead of setting to 1 because
* this data skipping function can be called
* recursively. */
rar->skip_mode++;
/* We're disposing 1 block of data, so we use triple
* NULLs in arguments. */
ret = rar5_read_data(a, NULL, NULL, NULL);
/* Turn off "skip mode". */
rar->skip_mode--;
if(ret < 0 || ret == ARCHIVE_EOF) {
/* Propagate any potential error conditions
* to the caller. */
return ret;
}
}
} else {
/* In standard archives, we can just jump over the compressed
* stream. Each file in non-solid archives starts from an empty
* window buffer. */
if(ARCHIVE_OK != consume(a, rar->file.bytes_remaining)) {
return ARCHIVE_FATAL;
}
rar->file.bytes_remaining = 0;
}
return ARCHIVE_OK;
}
static int64_t rar5_seek_data(struct archive_read *a, int64_t offset,
int whence)
{
(void) a;
(void) offset;
(void) whence;
/* We're a streaming unpacker, and we don't support seeking. */
return ARCHIVE_FATAL;
}
static int rar5_cleanup(struct archive_read *a) {
struct rar5* rar = get_context(a);
free(rar->cstate.window_buf);
free(rar->cstate.filtered_buf);
free(rar->vol.push_buf);
free_filters(rar);
cdeque_free(&rar->cstate.filters);
free(rar);
a->format->data = NULL;
return ARCHIVE_OK;
}
static int rar5_capabilities(struct archive_read * a) {
(void) a;
return 0;
}
static int rar5_has_encrypted_entries(struct archive_read *_a) {
(void) _a;
/* Unsupported for now. */
return ARCHIVE_READ_FORMAT_ENCRYPTION_UNSUPPORTED;
}
static int rar5_init(struct rar5* rar) {
ssize_t i;
memset(rar, 0, sizeof(struct rar5));
/* Decrypt the magic signature pattern. Check the comment near the
* `rar5_signature` symbol to read the rationale behind this. */
if(rar5_signature[0] == 243) {
for(i = 0; i < rar5_signature_size; i++) {
rar5_signature[i] ^= 0xA1;
}
}
if(CDE_OK != cdeque_init(&rar->cstate.filters, 8192))
return ARCHIVE_FATAL;
return ARCHIVE_OK;
}
int archive_read_support_format_rar5(struct archive *_a) {
struct archive_read* ar;
int ret;
struct rar5* rar;
if(ARCHIVE_OK != (ret = get_archive_read(_a, &ar)))
return ret;
rar = malloc(sizeof(*rar));
if(rar == NULL) {
archive_set_error(&ar->archive, ENOMEM,
"Can't allocate rar5 data");
return ARCHIVE_FATAL;
}
if(ARCHIVE_OK != rar5_init(rar)) {
archive_set_error(&ar->archive, ENOMEM,
"Can't allocate rar5 filter buffer");
return ARCHIVE_FATAL;
}
ret = __archive_read_register_format(ar,
rar,
"rar5",
rar5_bid,
rar5_options,
rar5_read_header,
rar5_read_data,
rar5_read_data_skip,
rar5_seek_data,
rar5_cleanup,
rar5_capabilities,
rar5_has_encrypted_entries);
if(ret != ARCHIVE_OK) {
(void) rar5_cleanup(ar);
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4685_1 |
crossvul-cpp_data_bad_3443_0 | /*
* ebtables
*
* Author:
* Bart De Schuymer <bdschuym@pandora.be>
*
* ebtables.c,v 2.0, July, 2002
*
* This code is stongly inspired on the iptables code which is
* Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_bridge/ebtables.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/smp.h>
#include <linux/cpumask.h>
#include <net/sock.h>
/* needed for logical [in,out]-dev filtering */
#include "../br_private.h"
#define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\
"report to author: "format, ## args)
/* #define BUGPRINT(format, args...) */
/*
* Each cpu has its own set of counters, so there is no need for write_lock in
* the softirq
* For reading or updating the counters, the user context needs to
* get a write_lock
*/
/* The size of each set of counters is altered to get cache alignment */
#define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1))
#define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter)))
#define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \
COUNTER_OFFSET(n) * cpu))
static DEFINE_MUTEX(ebt_mutex);
#ifdef CONFIG_COMPAT
static void ebt_standard_compat_from_user(void *dst, const void *src)
{
int v = *(compat_int_t *)src;
if (v >= 0)
v += xt_compat_calc_jump(NFPROTO_BRIDGE, v);
memcpy(dst, &v, sizeof(v));
}
static int ebt_standard_compat_to_user(void __user *dst, const void *src)
{
compat_int_t cv = *(int *)src;
if (cv >= 0)
cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv);
return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0;
}
#endif
static struct xt_target ebt_standard_target = {
.name = "standard",
.revision = 0,
.family = NFPROTO_BRIDGE,
.targetsize = sizeof(int),
#ifdef CONFIG_COMPAT
.compatsize = sizeof(compat_int_t),
.compat_from_user = ebt_standard_compat_from_user,
.compat_to_user = ebt_standard_compat_to_user,
#endif
};
static inline int
ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb,
struct xt_action_param *par)
{
par->target = w->u.watcher;
par->targinfo = w->data;
w->u.watcher->target(skb, par);
/* watchers don't give a verdict */
return 0;
}
static inline int
ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb,
struct xt_action_param *par)
{
par->match = m->u.match;
par->matchinfo = m->data;
return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH;
}
static inline int
ebt_dev_check(const char *entry, const struct net_device *device)
{
int i = 0;
const char *devname;
if (*entry == '\0')
return 0;
if (!device)
return 1;
devname = device->name;
/* 1 is the wildcard token */
while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i])
i++;
return (devname[i] != entry[i] && entry[i] != 1);
}
#define FWINV2(bool,invflg) ((bool) ^ !!(e->invflags & invflg))
/* process standard matches */
static inline int
ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb,
const struct net_device *in, const struct net_device *out)
{
const struct ethhdr *h = eth_hdr(skb);
const struct net_bridge_port *p;
__be16 ethproto;
int verdict, i;
if (vlan_tx_tag_present(skb))
ethproto = htons(ETH_P_8021Q);
else
ethproto = h->h_proto;
if (e->bitmask & EBT_802_3) {
if (FWINV2(ntohs(ethproto) >= 1536, EBT_IPROTO))
return 1;
} else if (!(e->bitmask & EBT_NOPROTO) &&
FWINV2(e->ethproto != ethproto, EBT_IPROTO))
return 1;
if (FWINV2(ebt_dev_check(e->in, in), EBT_IIN))
return 1;
if (FWINV2(ebt_dev_check(e->out, out), EBT_IOUT))
return 1;
/* rcu_read_lock()ed by nf_hook_slow */
if (in && (p = br_port_get_rcu(in)) != NULL &&
FWINV2(ebt_dev_check(e->logical_in, p->br->dev), EBT_ILOGICALIN))
return 1;
if (out && (p = br_port_get_rcu(out)) != NULL &&
FWINV2(ebt_dev_check(e->logical_out, p->br->dev), EBT_ILOGICALOUT))
return 1;
if (e->bitmask & EBT_SOURCEMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_source[i] ^ e->sourcemac[i]) &
e->sourcemsk[i];
if (FWINV2(verdict != 0, EBT_ISOURCE) )
return 1;
}
if (e->bitmask & EBT_DESTMAC) {
verdict = 0;
for (i = 0; i < 6; i++)
verdict |= (h->h_dest[i] ^ e->destmac[i]) &
e->destmsk[i];
if (FWINV2(verdict != 0, EBT_IDEST) )
return 1;
}
return 0;
}
static inline __pure
struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry)
{
return (void *)entry + entry->next_offset;
}
/* Do some firewalling */
unsigned int ebt_do_table (unsigned int hook, struct sk_buff *skb,
const struct net_device *in, const struct net_device *out,
struct ebt_table *table)
{
int i, nentries;
struct ebt_entry *point;
struct ebt_counter *counter_base, *cb_base;
const struct ebt_entry_target *t;
int verdict, sp = 0;
struct ebt_chainstack *cs;
struct ebt_entries *chaininfo;
const char *base;
const struct ebt_table_info *private;
struct xt_action_param acpar;
acpar.family = NFPROTO_BRIDGE;
acpar.in = in;
acpar.out = out;
acpar.hotdrop = false;
acpar.hooknum = hook;
read_lock_bh(&table->lock);
private = table->private;
cb_base = COUNTER_BASE(private->counters, private->nentries,
smp_processor_id());
if (private->chainstack)
cs = private->chainstack[smp_processor_id()];
else
cs = NULL;
chaininfo = private->hook_entry[hook];
nentries = private->hook_entry[hook]->nentries;
point = (struct ebt_entry *)(private->hook_entry[hook]->data);
counter_base = cb_base + private->hook_entry[hook]->counter_offset;
/* base for chain jumps */
base = private->entries;
i = 0;
while (i < nentries) {
if (ebt_basic_match(point, skb, in, out))
goto letscontinue;
if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0)
goto letscontinue;
if (acpar.hotdrop) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* increase counter */
(*(counter_base + i)).pcnt++;
(*(counter_base + i)).bcnt += skb->len;
/* these should only watch: not modify, nor tell us
what to do with the packet */
EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar);
t = (struct ebt_entry_target *)
(((char *)point) + point->target_offset);
/* standard target */
if (!t->u.target->target)
verdict = ((struct ebt_standard_target *)t)->verdict;
else {
acpar.target = t->u.target;
acpar.targinfo = t->data;
verdict = t->u.target->target(skb, &acpar);
}
if (verdict == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
if (verdict == EBT_DROP) {
read_unlock_bh(&table->lock);
return NF_DROP;
}
if (verdict == EBT_RETURN) {
letsreturn:
#ifdef CONFIG_NETFILTER_DEBUG
if (sp == 0) {
BUGPRINT("RETURN on base chain");
/* act like this is EBT_CONTINUE */
goto letscontinue;
}
#endif
sp--;
/* put all the local variables right */
i = cs[sp].n;
chaininfo = cs[sp].chaininfo;
nentries = chaininfo->nentries;
point = cs[sp].e;
counter_base = cb_base +
chaininfo->counter_offset;
continue;
}
if (verdict == EBT_CONTINUE)
goto letscontinue;
#ifdef CONFIG_NETFILTER_DEBUG
if (verdict < 0) {
BUGPRINT("bogus standard verdict\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
/* jump to a udc */
cs[sp].n = i + 1;
cs[sp].chaininfo = chaininfo;
cs[sp].e = ebt_next_entry(point);
i = 0;
chaininfo = (struct ebt_entries *) (base + verdict);
#ifdef CONFIG_NETFILTER_DEBUG
if (chaininfo->distinguisher) {
BUGPRINT("jump to non-chain\n");
read_unlock_bh(&table->lock);
return NF_DROP;
}
#endif
nentries = chaininfo->nentries;
point = (struct ebt_entry *)chaininfo->data;
counter_base = cb_base + chaininfo->counter_offset;
sp++;
continue;
letscontinue:
point = ebt_next_entry(point);
i++;
}
/* I actually like this :) */
if (chaininfo->policy == EBT_RETURN)
goto letsreturn;
if (chaininfo->policy == EBT_ACCEPT) {
read_unlock_bh(&table->lock);
return NF_ACCEPT;
}
read_unlock_bh(&table->lock);
return NF_DROP;
}
/* If it succeeds, returns element and locks mutex */
static inline void *
find_inlist_lock_noload(struct list_head *head, const char *name, int *error,
struct mutex *mutex)
{
struct {
struct list_head list;
char name[EBT_FUNCTION_MAXNAMELEN];
} *e;
*error = mutex_lock_interruptible(mutex);
if (*error != 0)
return NULL;
list_for_each_entry(e, head, list) {
if (strcmp(e->name, name) == 0)
return e;
}
*error = -ENOENT;
mutex_unlock(mutex);
return NULL;
}
static void *
find_inlist_lock(struct list_head *head, const char *name, const char *prefix,
int *error, struct mutex *mutex)
{
return try_then_request_module(
find_inlist_lock_noload(head, name, error, mutex),
"%s%s", prefix, name);
}
static inline struct ebt_table *
find_table_lock(struct net *net, const char *name, int *error,
struct mutex *mutex)
{
return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name,
"ebtable_", error, mutex);
}
static inline int
ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_match *match;
size_t left = ((char *)e + e->watchers_offset) - (char *)m;
int ret;
if (left < sizeof(struct ebt_entry_match) ||
left - sizeof(struct ebt_entry_match) < m->match_size)
return -EINVAL;
match = xt_request_find_match(NFPROTO_BRIDGE, m->u.name, 0);
if (IS_ERR(match))
return PTR_ERR(match);
m->u.match = match;
par->match = match;
par->matchinfo = m->data;
ret = xt_check_match(par, m->match_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(match->me);
return ret;
}
(*cnt)++;
return 0;
}
static inline int
ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par,
unsigned int *cnt)
{
const struct ebt_entry *e = par->entryinfo;
struct xt_target *watcher;
size_t left = ((char *)e + e->target_offset) - (char *)w;
int ret;
if (left < sizeof(struct ebt_entry_watcher) ||
left - sizeof(struct ebt_entry_watcher) < w->watcher_size)
return -EINVAL;
watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0);
if (IS_ERR(watcher))
return PTR_ERR(watcher);
w->u.watcher = watcher;
par->target = watcher;
par->targinfo = w->data;
ret = xt_check_target(par, w->watcher_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(watcher->me);
return ret;
}
(*cnt)++;
return 0;
}
static int ebt_verify_pointers(const struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
unsigned int limit = repl->entries_size;
unsigned int valid_hooks = repl->valid_hooks;
unsigned int offset = 0;
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++)
newinfo->hook_entry[i] = NULL;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
while (offset < limit) {
size_t left = limit - offset;
struct ebt_entry *e = (void *)newinfo->entries + offset;
if (left < sizeof(unsigned int))
break;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((valid_hooks & (1 << i)) == 0)
continue;
if ((char __user *)repl->hook_entry[i] ==
repl->entries + offset)
break;
}
if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) {
if (e->bitmask != 0) {
/* we make userspace set this right,
so there is no misunderstanding */
BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set "
"in distinguisher\n");
return -EINVAL;
}
if (i != NF_BR_NUMHOOKS)
newinfo->hook_entry[i] = (struct ebt_entries *)e;
if (left < sizeof(struct ebt_entries))
break;
offset += sizeof(struct ebt_entries);
} else {
if (left < sizeof(struct ebt_entry))
break;
if (left < e->next_offset)
break;
if (e->next_offset < sizeof(struct ebt_entry))
return -EINVAL;
offset += e->next_offset;
}
}
if (offset != limit) {
BUGPRINT("entries_size too small\n");
return -EINVAL;
}
/* check if all valid hooks have a chain */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i] &&
(valid_hooks & (1 << i))) {
BUGPRINT("Valid hook without chain\n");
return -EINVAL;
}
}
return 0;
}
/*
* this one is very careful, as it is the first function
* to parse the userspace data
*/
static inline int
ebt_check_entry_size_and_hooks(const struct ebt_entry *e,
const struct ebt_table_info *newinfo,
unsigned int *n, unsigned int *cnt,
unsigned int *totalcnt, unsigned int *udc_cnt)
{
int i;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((void *)e == (void *)newinfo->hook_entry[i])
break;
}
/* beginning of a new chain
if i == NF_BR_NUMHOOKS it must be a user defined chain */
if (i != NF_BR_NUMHOOKS || !e->bitmask) {
/* this checks if the previous chain has as many entries
as it said it has */
if (*n != *cnt) {
BUGPRINT("nentries does not equal the nr of entries "
"in the chain\n");
return -EINVAL;
}
if (((struct ebt_entries *)e)->policy != EBT_DROP &&
((struct ebt_entries *)e)->policy != EBT_ACCEPT) {
/* only RETURN from udc */
if (i != NF_BR_NUMHOOKS ||
((struct ebt_entries *)e)->policy != EBT_RETURN) {
BUGPRINT("bad policy\n");
return -EINVAL;
}
}
if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */
(*udc_cnt)++;
if (((struct ebt_entries *)e)->counter_offset != *totalcnt) {
BUGPRINT("counter_offset != totalcnt");
return -EINVAL;
}
*n = ((struct ebt_entries *)e)->nentries;
*cnt = 0;
return 0;
}
/* a plain old entry, heh */
if (sizeof(struct ebt_entry) > e->watchers_offset ||
e->watchers_offset > e->target_offset ||
e->target_offset >= e->next_offset) {
BUGPRINT("entry offsets not in right order\n");
return -EINVAL;
}
/* this is not checked anywhere else */
if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) {
BUGPRINT("target size too small\n");
return -EINVAL;
}
(*cnt)++;
(*totalcnt)++;
return 0;
}
struct ebt_cl_stack
{
struct ebt_chainstack cs;
int from;
unsigned int hookmask;
};
/*
* we need these positions to check that the jumps to a different part of the
* entries is a jump to the beginning of a new chain.
*/
static inline int
ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo,
unsigned int *n, struct ebt_cl_stack *udc)
{
int i;
/* we're only interested in chain starts */
if (e->bitmask)
return 0;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (newinfo->hook_entry[i] == (struct ebt_entries *)e)
break;
}
/* only care about udc */
if (i != NF_BR_NUMHOOKS)
return 0;
udc[*n].cs.chaininfo = (struct ebt_entries *)e;
/* these initialisations are depended on later in check_chainloops() */
udc[*n].cs.n = 0;
udc[*n].hookmask = 0;
(*n)++;
return 0;
}
static inline int
ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i)
{
struct xt_mtdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.match = m->u.match;
par.matchinfo = m->data;
par.family = NFPROTO_BRIDGE;
if (par.match->destroy != NULL)
par.match->destroy(&par);
module_put(par.match->me);
return 0;
}
static inline int
ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i)
{
struct xt_tgdtor_param par;
if (i && (*i)-- == 0)
return 1;
par.net = net;
par.target = w->u.watcher;
par.targinfo = w->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt)
{
struct xt_tgdtor_param par;
struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
/* we're done */
if (cnt && (*cnt)-- == 0)
return 1;
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL);
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
par.net = net;
par.target = t->u.target;
par.targinfo = t->data;
par.family = NFPROTO_BRIDGE;
if (par.target->destroy != NULL)
par.target->destroy(&par);
module_put(par.target->me);
return 0;
}
static inline int
ebt_check_entry(struct ebt_entry *e, struct net *net,
const struct ebt_table_info *newinfo,
const char *name, unsigned int *cnt,
struct ebt_cl_stack *cl_s, unsigned int udc_cnt)
{
struct ebt_entry_target *t;
struct xt_target *target;
unsigned int i, j, hook = 0, hookmask = 0;
size_t gap;
int ret;
struct xt_mtchk_param mtpar;
struct xt_tgchk_param tgpar;
/* don't mess with the struct ebt_entries */
if (e->bitmask == 0)
return 0;
if (e->bitmask & ~EBT_F_MASK) {
BUGPRINT("Unknown flag for bitmask\n");
return -EINVAL;
}
if (e->invflags & ~EBT_INV_MASK) {
BUGPRINT("Unknown flag for inv bitmask\n");
return -EINVAL;
}
if ( (e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3) ) {
BUGPRINT("NOPROTO & 802_3 not allowed\n");
return -EINVAL;
}
/* what hook do we belong to? */
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if (!newinfo->hook_entry[i])
continue;
if ((char *)newinfo->hook_entry[i] < (char *)e)
hook = i;
else
break;
}
/* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on
a base chain */
if (i < NF_BR_NUMHOOKS)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else {
for (i = 0; i < udc_cnt; i++)
if ((char *)(cl_s[i].cs.chaininfo) > (char *)e)
break;
if (i == 0)
hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS);
else
hookmask = cl_s[i - 1].hookmask;
}
i = 0;
mtpar.net = tgpar.net = net;
mtpar.table = tgpar.table = name;
mtpar.entryinfo = tgpar.entryinfo = e;
mtpar.hook_mask = tgpar.hook_mask = hookmask;
mtpar.family = tgpar.family = NFPROTO_BRIDGE;
ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i);
if (ret != 0)
goto cleanup_matches;
j = 0;
ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j);
if (ret != 0)
goto cleanup_watchers;
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
gap = e->next_offset - e->target_offset;
target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0);
if (IS_ERR(target)) {
ret = PTR_ERR(target);
goto cleanup_watchers;
}
t->u.target = target;
if (t->u.target == &ebt_standard_target) {
if (gap < sizeof(struct ebt_standard_target)) {
BUGPRINT("Standard target size too big\n");
ret = -EFAULT;
goto cleanup_watchers;
}
if (((struct ebt_standard_target *)t)->verdict <
-NUM_STANDARD_TARGETS) {
BUGPRINT("Invalid standard target\n");
ret = -EFAULT;
goto cleanup_watchers;
}
} else if (t->target_size > gap - sizeof(struct ebt_entry_target)) {
module_put(t->u.target->me);
ret = -EFAULT;
goto cleanup_watchers;
}
tgpar.target = target;
tgpar.targinfo = t->data;
ret = xt_check_target(&tgpar, t->target_size,
e->ethproto, e->invflags & EBT_IPROTO);
if (ret < 0) {
module_put(target->me);
goto cleanup_watchers;
}
(*cnt)++;
return 0;
cleanup_watchers:
EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j);
cleanup_matches:
EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i);
return ret;
}
/*
* checks for loops and sets the hook mask for udc
* the hook mask for udc tells us from which base chains the udc can be
* accessed. This mask is a parameter to the check() functions of the extensions
*/
static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s,
unsigned int udc_cnt, unsigned int hooknr, char *base)
{
int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict;
const struct ebt_entry *e = (struct ebt_entry *)chain->data;
const struct ebt_entry_target *t;
while (pos < nentries || chain_nr != -1) {
/* end of udc, go back one 'recursion' step */
if (pos == nentries) {
/* put back values of the time when this chain was called */
e = cl_s[chain_nr].cs.e;
if (cl_s[chain_nr].from != -1)
nentries =
cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries;
else
nentries = chain->nentries;
pos = cl_s[chain_nr].cs.n;
/* make sure we won't see a loop that isn't one */
cl_s[chain_nr].cs.n = 0;
chain_nr = cl_s[chain_nr].from;
if (pos == nentries)
continue;
}
t = (struct ebt_entry_target *)
(((char *)e) + e->target_offset);
if (strcmp(t->u.name, EBT_STANDARD_TARGET))
goto letscontinue;
if (e->target_offset + sizeof(struct ebt_standard_target) >
e->next_offset) {
BUGPRINT("Standard target size too big\n");
return -1;
}
verdict = ((struct ebt_standard_target *)t)->verdict;
if (verdict >= 0) { /* jump to another chain */
struct ebt_entries *hlp2 =
(struct ebt_entries *)(base + verdict);
for (i = 0; i < udc_cnt; i++)
if (hlp2 == cl_s[i].cs.chaininfo)
break;
/* bad destination or loop */
if (i == udc_cnt) {
BUGPRINT("bad destination\n");
return -1;
}
if (cl_s[i].cs.n) {
BUGPRINT("loop\n");
return -1;
}
if (cl_s[i].hookmask & (1 << hooknr))
goto letscontinue;
/* this can't be 0, so the loop test is correct */
cl_s[i].cs.n = pos + 1;
pos = 0;
cl_s[i].cs.e = ebt_next_entry(e);
e = (struct ebt_entry *)(hlp2->data);
nentries = hlp2->nentries;
cl_s[i].from = chain_nr;
chain_nr = i;
/* this udc is accessible from the base chain for hooknr */
cl_s[i].hookmask |= (1 << hooknr);
continue;
}
letscontinue:
e = ebt_next_entry(e);
pos++;
}
return 0;
}
/* do the parsing of the table/chains/entries/matches/watchers/targets, heh */
static int translate_table(struct net *net, const char *name,
struct ebt_table_info *newinfo)
{
unsigned int i, j, k, udc_cnt;
int ret;
struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */
i = 0;
while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i])
i++;
if (i == NF_BR_NUMHOOKS) {
BUGPRINT("No valid hooks specified\n");
return -EINVAL;
}
if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) {
BUGPRINT("Chains don't start at beginning\n");
return -EINVAL;
}
/* make sure chains are ordered after each other in same order
as their corresponding hooks */
for (j = i + 1; j < NF_BR_NUMHOOKS; j++) {
if (!newinfo->hook_entry[j])
continue;
if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) {
BUGPRINT("Hook order must be followed\n");
return -EINVAL;
}
i = j;
}
/* do some early checkings and initialize some things */
i = 0; /* holds the expected nr. of entries for the chain */
j = 0; /* holds the up to now counted entries for the chain */
k = 0; /* holds the total nr. of entries, should equal
newinfo->nentries afterwards */
udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry_size_and_hooks, newinfo,
&i, &j, &k, &udc_cnt);
if (ret != 0)
return ret;
if (i != j) {
BUGPRINT("nentries does not equal the nr of entries in the "
"(last) chain\n");
return -EINVAL;
}
if (k != newinfo->nentries) {
BUGPRINT("Total nentries is wrong\n");
return -EINVAL;
}
/* get the location of the udc, put them in an array
while we're at it, allocate the chainstack */
if (udc_cnt) {
/* this will get free'd in do_replace()/ebt_register_table()
if an error occurs */
newinfo->chainstack =
vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack)));
if (!newinfo->chainstack)
return -ENOMEM;
for_each_possible_cpu(i) {
newinfo->chainstack[i] =
vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0])));
if (!newinfo->chainstack[i]) {
while (i)
vfree(newinfo->chainstack[--i]);
vfree(newinfo->chainstack);
newinfo->chainstack = NULL;
return -ENOMEM;
}
}
cl_s = vmalloc(udc_cnt * sizeof(*cl_s));
if (!cl_s)
return -ENOMEM;
i = 0; /* the i'th udc */
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_get_udc_positions, newinfo, &i, cl_s);
/* sanity check */
if (i != udc_cnt) {
BUGPRINT("i != udc_cnt\n");
vfree(cl_s);
return -EFAULT;
}
}
/* Check for loops */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
if (newinfo->hook_entry[i])
if (check_chainloops(newinfo->hook_entry[i],
cl_s, udc_cnt, i, newinfo->entries)) {
vfree(cl_s);
return -EINVAL;
}
/* we now know the following (along with E=mc²):
- the nr of entries in each chain is right
- the size of the allocated space is right
- all valid hooks have a corresponding chain
- there are no loops
- wrong data can still be on the level of a single entry
- could be there are jumps to places that are not the
beginning of a chain. This can only occur in chains that
are not accessible from any base chains, so we don't care. */
/* used to know what we need to clean up if something goes wrong */
i = 0;
ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt);
if (ret != 0) {
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, &i);
}
vfree(cl_s);
return ret;
}
/* called under write_lock */
static void get_counters(const struct ebt_counter *oldcounters,
struct ebt_counter *counters, unsigned int nentries)
{
int i, cpu;
struct ebt_counter *counter_base;
/* counters of cpu 0 */
memcpy(counters, oldcounters,
sizeof(struct ebt_counter) * nentries);
/* add other counters to those of cpu 0 */
for_each_possible_cpu(cpu) {
if (cpu == 0)
continue;
counter_base = COUNTER_BASE(oldcounters, nentries, cpu);
for (i = 0; i < nentries; i++) {
counters[i].pcnt += counter_base[i].pcnt;
counters[i].bcnt += counter_base[i].bcnt;
}
}
}
static int do_replace_finish(struct net *net, struct ebt_replace *repl,
struct ebt_table_info *newinfo)
{
int ret, i;
struct ebt_counter *counterstmp = NULL;
/* used to be able to unlock earlier */
struct ebt_table_info *table;
struct ebt_table *t;
/* the user wants counters back
the check on the size is done later, when we have the lock */
if (repl->num_counters) {
unsigned long size = repl->num_counters * sizeof(*counterstmp);
counterstmp = vmalloc(size);
if (!counterstmp)
return -ENOMEM;
}
newinfo->chainstack = NULL;
ret = ebt_verify_pointers(repl, newinfo);
if (ret != 0)
goto free_counterstmp;
ret = translate_table(net, repl->name, newinfo);
if (ret != 0)
goto free_counterstmp;
t = find_table_lock(net, repl->name, &ret, &ebt_mutex);
if (!t) {
ret = -ENOENT;
goto free_iterate;
}
/* the table doesn't like it */
if (t->check && (ret = t->check(newinfo, repl->valid_hooks)))
goto free_unlock;
if (repl->num_counters && repl->num_counters != t->private->nentries) {
BUGPRINT("Wrong nr. of counters requested\n");
ret = -EINVAL;
goto free_unlock;
}
/* we have the mutex lock, so no danger in reading this pointer */
table = t->private;
/* make sure the table can only be rmmod'ed if it contains no rules */
if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) {
ret = -ENOENT;
goto free_unlock;
} else if (table->nentries && !newinfo->nentries)
module_put(t->me);
/* we need an atomic snapshot of the counters */
write_lock_bh(&t->lock);
if (repl->num_counters)
get_counters(t->private->counters, counterstmp,
t->private->nentries);
t->private = newinfo;
write_unlock_bh(&t->lock);
mutex_unlock(&ebt_mutex);
/* so, a user can change the chains while having messed up her counter
allocation. Only reason why this is done is because this way the lock
is held only once, while this doesn't bring the kernel into a
dangerous state. */
if (repl->num_counters &&
copy_to_user(repl->counters, counterstmp,
repl->num_counters * sizeof(struct ebt_counter))) {
ret = -EFAULT;
}
else
ret = 0;
/* decrease module count and free resources */
EBT_ENTRY_ITERATE(table->entries, table->entries_size,
ebt_cleanup_entry, net, NULL);
vfree(table->entries);
if (table->chainstack) {
for_each_possible_cpu(i)
vfree(table->chainstack[i]);
vfree(table->chainstack);
}
vfree(table);
vfree(counterstmp);
return ret;
free_unlock:
mutex_unlock(&ebt_mutex);
free_iterate:
EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size,
ebt_cleanup_entry, net, NULL);
free_counterstmp:
vfree(counterstmp);
/* can be initialized in translate_table() */
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
return ret;
}
/* replace the table */
static int do_replace(struct net *net, const void __user *user,
unsigned int len)
{
int ret, countersize;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
if (copy_from_user(&tmp, user, sizeof(tmp)) != 0)
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size) {
BUGPRINT("Wrong len argument\n");
return -EINVAL;
}
if (tmp.entries_size == 0) {
BUGPRINT("Entries_size never zero\n");
return -EINVAL;
}
/* overflow check */
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
BUGPRINT("Couldn't copy entries from userspace\n");
ret = -EFAULT;
goto free_entries;
}
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
}
struct ebt_table *
ebt_register_table(struct net *net, const struct ebt_table *input_table)
{
struct ebt_table_info *newinfo;
struct ebt_table *t, *table;
struct ebt_replace_kernel *repl;
int ret, i, countersize;
void *p;
if (input_table == NULL || (repl = input_table->table) == NULL ||
repl->entries == NULL || repl->entries_size == 0 ||
repl->counters != NULL || input_table->private != NULL) {
BUGPRINT("Bad table data for ebt_register_table!!!\n");
return ERR_PTR(-EINVAL);
}
/* Don't add one table to multiple lists. */
table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL);
if (!table) {
ret = -ENOMEM;
goto out;
}
countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
ret = -ENOMEM;
if (!newinfo)
goto free_table;
p = vmalloc(repl->entries_size);
if (!p)
goto free_newinfo;
memcpy(p, repl->entries, repl->entries_size);
newinfo->entries = p;
newinfo->entries_size = repl->entries_size;
newinfo->nentries = repl->nentries;
if (countersize)
memset(newinfo->counters, 0, countersize);
/* fill in newinfo and parse the entries */
newinfo->chainstack = NULL;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
if ((repl->valid_hooks & (1 << i)) == 0)
newinfo->hook_entry[i] = NULL;
else
newinfo->hook_entry[i] = p +
((char *)repl->hook_entry[i] - repl->entries);
}
ret = translate_table(net, repl->name, newinfo);
if (ret != 0) {
BUGPRINT("Translate_table failed\n");
goto free_chainstack;
}
if (table->check && table->check(newinfo, table->valid_hooks)) {
BUGPRINT("The table doesn't like its own initial data, lol\n");
return ERR_PTR(-EINVAL);
}
table->private = newinfo;
rwlock_init(&table->lock);
ret = mutex_lock_interruptible(&ebt_mutex);
if (ret != 0)
goto free_chainstack;
list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) {
if (strcmp(t->name, table->name) == 0) {
ret = -EEXIST;
BUGPRINT("Table name already exists\n");
goto free_unlock;
}
}
/* Hold a reference count if the chains aren't empty */
if (newinfo->nentries && !try_module_get(table->me)) {
ret = -ENOENT;
goto free_unlock;
}
list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]);
mutex_unlock(&ebt_mutex);
return table;
free_unlock:
mutex_unlock(&ebt_mutex);
free_chainstack:
if (newinfo->chainstack) {
for_each_possible_cpu(i)
vfree(newinfo->chainstack[i]);
vfree(newinfo->chainstack);
}
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
free_table:
kfree(table);
out:
return ERR_PTR(ret);
}
void ebt_unregister_table(struct net *net, struct ebt_table *table)
{
int i;
if (!table) {
BUGPRINT("Request to unregister NULL table!!!\n");
return;
}
mutex_lock(&ebt_mutex);
list_del(&table->list);
mutex_unlock(&ebt_mutex);
EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size,
ebt_cleanup_entry, net, NULL);
if (table->private->nentries)
module_put(table->me);
vfree(table->private->entries);
if (table->private->chainstack) {
for_each_possible_cpu(i)
vfree(table->private->chainstack[i]);
vfree(table->private->chainstack);
}
vfree(table->private);
kfree(table);
}
/* userspace just supplied us with counters */
static int do_update_counters(struct net *net, const char *name,
struct ebt_counter __user *counters,
unsigned int num_counters,
const void __user *user, unsigned int len)
{
int i, ret;
struct ebt_counter *tmp;
struct ebt_table *t;
if (num_counters == 0)
return -EINVAL;
tmp = vmalloc(num_counters * sizeof(*tmp));
if (!tmp)
return -ENOMEM;
t = find_table_lock(net, name, &ret, &ebt_mutex);
if (!t)
goto free_tmp;
if (num_counters != t->private->nentries) {
BUGPRINT("Wrong nr of counters\n");
ret = -EINVAL;
goto unlock_mutex;
}
if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) {
ret = -EFAULT;
goto unlock_mutex;
}
/* we want an atomic add of the counters */
write_lock_bh(&t->lock);
/* we add to the counters of the first cpu */
for (i = 0; i < num_counters; i++) {
t->private->counters[i].pcnt += tmp[i].pcnt;
t->private->counters[i].bcnt += tmp[i].bcnt;
}
write_unlock_bh(&t->lock);
ret = 0;
unlock_mutex:
mutex_unlock(&ebt_mutex);
free_tmp:
vfree(tmp);
return ret;
}
static int update_counters(struct net *net, const void __user *user,
unsigned int len)
{
struct ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return -EINVAL;
return do_update_counters(net, hlp.name, hlp.counters,
hlp.num_counters, user, len);
}
static inline int ebt_make_matchname(const struct ebt_entry_match *m,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)m - base);
if (copy_to_user(hlp, m->u.match->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int ebt_make_watchername(const struct ebt_entry_watcher *w,
const char *base, char __user *ubase)
{
char __user *hlp = ubase + ((char *)w - base);
if (copy_to_user(hlp , w->u.watcher->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static inline int
ebt_make_names(struct ebt_entry *e, const char *base, char __user *ubase)
{
int ret;
char __user *hlp;
const struct ebt_entry_target *t;
if (e->bitmask == 0)
return 0;
hlp = ubase + (((char *)e + e->target_offset) - base);
t = (struct ebt_entry_target *)(((char *)e) + e->target_offset);
ret = EBT_MATCH_ITERATE(e, ebt_make_matchname, base, ubase);
if (ret != 0)
return ret;
ret = EBT_WATCHER_ITERATE(e, ebt_make_watchername, base, ubase);
if (ret != 0)
return ret;
if (copy_to_user(hlp, t->u.target->name, EBT_FUNCTION_MAXNAMELEN))
return -EFAULT;
return 0;
}
static int copy_counters_to_user(struct ebt_table *t,
const struct ebt_counter *oldcounters,
void __user *user, unsigned int num_counters,
unsigned int nentries)
{
struct ebt_counter *counterstmp;
int ret = 0;
/* userspace might not need the counters */
if (num_counters == 0)
return 0;
if (num_counters != nentries) {
BUGPRINT("Num_counters wrong\n");
return -EINVAL;
}
counterstmp = vmalloc(nentries * sizeof(*counterstmp));
if (!counterstmp)
return -ENOMEM;
write_lock_bh(&t->lock);
get_counters(oldcounters, counterstmp, nentries);
write_unlock_bh(&t->lock);
if (copy_to_user(user, counterstmp,
nentries * sizeof(struct ebt_counter)))
ret = -EFAULT;
vfree(counterstmp);
return ret;
}
/* called with ebt_mutex locked */
static int copy_everything_to_user(struct ebt_table *t, void __user *user,
const int *len, int cmd)
{
struct ebt_replace tmp;
const struct ebt_counter *oldcounters;
unsigned int entries_size, nentries;
int ret;
char *entries;
if (cmd == EBT_SO_GET_ENTRIES) {
entries_size = t->private->entries_size;
nentries = t->private->nentries;
entries = t->private->entries;
oldcounters = t->private->counters;
} else {
entries_size = t->table->entries_size;
nentries = t->table->nentries;
entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (*len != sizeof(struct ebt_replace) + entries_size +
(tmp.num_counters? nentries * sizeof(struct ebt_counter): 0))
return -EINVAL;
if (tmp.nentries != nentries) {
BUGPRINT("Nentries wrong\n");
return -EINVAL;
}
if (tmp.entries_size != entries_size) {
BUGPRINT("Wrong size\n");
return -EINVAL;
}
ret = copy_counters_to_user(t, oldcounters, tmp.counters,
tmp.num_counters, nentries);
if (ret)
return ret;
if (copy_to_user(tmp.entries, entries, entries_size)) {
BUGPRINT("Couldn't copy entries to userspace\n");
return -EFAULT;
}
/* set the match/watcher/target names right */
return EBT_ENTRY_ITERATE(entries, entries_size,
ebt_make_names, entries, tmp.entries);
}
static int do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch(cmd) {
case EBT_SO_SET_ENTRIES:
ret = do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
int ret;
struct ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
switch(cmd) {
case EBT_SO_GET_INFO:
case EBT_SO_GET_INIT_INFO:
if (*len != sizeof(struct ebt_replace)){
ret = -EINVAL;
mutex_unlock(&ebt_mutex);
break;
}
if (cmd == EBT_SO_GET_INFO) {
tmp.nentries = t->private->nentries;
tmp.entries_size = t->private->entries_size;
tmp.valid_hooks = t->valid_hooks;
} else {
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
}
mutex_unlock(&ebt_mutex);
if (copy_to_user(user, &tmp, *len) != 0){
BUGPRINT("c2u Didn't work\n");
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
ret = copy_everything_to_user(t, user, len, cmd);
mutex_unlock(&ebt_mutex);
break;
default:
mutex_unlock(&ebt_mutex);
ret = -EINVAL;
}
return ret;
}
#ifdef CONFIG_COMPAT
/* 32 bit-userspace compatibility definitions. */
struct compat_ebt_replace {
char name[EBT_TABLE_MAXNAMELEN];
compat_uint_t valid_hooks;
compat_uint_t nentries;
compat_uint_t entries_size;
/* start of the chains */
compat_uptr_t hook_entry[NF_BR_NUMHOOKS];
/* nr of counters userspace expects back */
compat_uint_t num_counters;
/* where the kernel will put the old counters. */
compat_uptr_t counters;
compat_uptr_t entries;
};
/* struct ebt_entry_match, _target and _watcher have same layout */
struct compat_ebt_entry_mwt {
union {
char name[EBT_FUNCTION_MAXNAMELEN];
compat_uptr_t ptr;
} u;
compat_uint_t match_size;
compat_uint_t data[0];
};
/* account for possible padding between match_size and ->data */
static int ebt_compat_entry_padsize(void)
{
BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) <
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)));
return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) -
COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt));
}
static int ebt_compat_match_offset(const struct xt_match *match,
unsigned int userlen)
{
/*
* ebt_among needs special handling. The kernel .matchsize is
* set to -1 at registration time; at runtime an EBT_ALIGN()ed
* value is expected.
* Example: userspace sends 4500, ebt_among.c wants 4504.
*/
if (unlikely(match->matchsize == -1))
return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen);
return xt_compat_match_offset(match);
}
static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr,
unsigned int *size)
{
const struct xt_match *match = m->u.match;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = ebt_compat_match_offset(match, m->match_size);
compat_uint_t msize = m->match_size - off;
BUG_ON(off >= m->match_size);
if (copy_to_user(cm->u.name, match->name,
strlen(match->name) + 1) || put_user(msize, &cm->match_size))
return -EFAULT;
if (match->compat_to_user) {
if (match->compat_to_user(cm->data, m->data))
return -EFAULT;
} else if (copy_to_user(cm->data, m->data, msize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += msize;
return 0;
}
static int compat_target_to_user(struct ebt_entry_target *t,
void __user **dstptr,
unsigned int *size)
{
const struct xt_target *target = t->u.target;
struct compat_ebt_entry_mwt __user *cm = *dstptr;
int off = xt_compat_target_offset(target);
compat_uint_t tsize = t->target_size - off;
BUG_ON(off >= t->target_size);
if (copy_to_user(cm->u.name, target->name,
strlen(target->name) + 1) || put_user(tsize, &cm->match_size))
return -EFAULT;
if (target->compat_to_user) {
if (target->compat_to_user(cm->data, t->data))
return -EFAULT;
} else if (copy_to_user(cm->data, t->data, tsize))
return -EFAULT;
*size -= ebt_compat_entry_padsize() + off;
*dstptr = cm->data;
*dstptr += tsize;
return 0;
}
static int compat_watcher_to_user(struct ebt_entry_watcher *w,
void __user **dstptr,
unsigned int *size)
{
return compat_target_to_user((struct ebt_entry_target *)w,
dstptr, size);
}
static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr,
unsigned int *size)
{
struct ebt_entry_target *t;
struct ebt_entry __user *ce;
u32 watchers_offset, target_offset, next_offset;
compat_uint_t origsize;
int ret;
if (e->bitmask == 0) {
if (*size < sizeof(struct ebt_entries))
return -EINVAL;
if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries)))
return -EFAULT;
*dstptr += sizeof(struct ebt_entries);
*size -= sizeof(struct ebt_entries);
return 0;
}
if (*size < sizeof(*ce))
return -EINVAL;
ce = (struct ebt_entry __user *)*dstptr;
if (copy_to_user(ce, e, sizeof(*ce)))
return -EFAULT;
origsize = *size;
*dstptr += sizeof(*ce);
ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size);
if (ret)
return ret;
watchers_offset = e->watchers_offset - (origsize - *size);
ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size);
if (ret)
return ret;
target_offset = e->target_offset - (origsize - *size);
t = (struct ebt_entry_target *) ((char *) e + e->target_offset);
ret = compat_target_to_user(t, dstptr, size);
if (ret)
return ret;
next_offset = e->next_offset - (origsize - *size);
if (put_user(watchers_offset, &ce->watchers_offset) ||
put_user(target_offset, &ce->target_offset) ||
put_user(next_offset, &ce->next_offset))
return -EFAULT;
*size -= sizeof(*ce);
return 0;
}
static int compat_calc_match(struct ebt_entry_match *m, int *off)
{
*off += ebt_compat_match_offset(m->u.match, m->match_size);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off)
{
*off += xt_compat_target_offset(w->u.watcher);
*off += ebt_compat_entry_padsize();
return 0;
}
static int compat_calc_entry(const struct ebt_entry *e,
const struct ebt_table_info *info,
const void *base,
struct compat_ebt_replace *newinfo)
{
const struct ebt_entry_target *t;
unsigned int entry_offset;
int off, ret, i;
if (e->bitmask == 0)
return 0;
off = 0;
entry_offset = (void *)e - base;
EBT_MATCH_ITERATE(e, compat_calc_match, &off);
EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off);
t = (const struct ebt_entry_target *) ((char *) e + e->target_offset);
off += xt_compat_target_offset(t->u.target);
off += ebt_compat_entry_padsize();
newinfo->entries_size -= off;
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off);
if (ret)
return ret;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
const void *hookptr = info->hook_entry[i];
if (info->hook_entry[i] &&
(e < (struct ebt_entry *)(base - hookptr))) {
newinfo->hook_entry[i] -= off;
pr_debug("0x%08X -> 0x%08X\n",
newinfo->hook_entry[i] + off,
newinfo->hook_entry[i]);
}
}
return 0;
}
static int compat_table_info(const struct ebt_table_info *info,
struct compat_ebt_replace *newinfo)
{
unsigned int size = info->entries_size;
const void *entries = info->entries;
newinfo->entries_size = size;
xt_compat_init_offsets(AF_INET, info->nentries);
return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info,
entries, newinfo);
}
static int compat_copy_everything_to_user(struct ebt_table *t,
void __user *user, int *len, int cmd)
{
struct compat_ebt_replace repl, tmp;
struct ebt_counter *oldcounters;
struct ebt_table_info tinfo;
int ret;
void __user *pos;
memset(&tinfo, 0, sizeof(tinfo));
if (cmd == EBT_SO_GET_ENTRIES) {
tinfo.entries_size = t->private->entries_size;
tinfo.nentries = t->private->nentries;
tinfo.entries = t->private->entries;
oldcounters = t->private->counters;
} else {
tinfo.entries_size = t->table->entries_size;
tinfo.nentries = t->table->nentries;
tinfo.entries = t->table->entries;
oldcounters = t->table->counters;
}
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (tmp.nentries != tinfo.nentries ||
(tmp.num_counters && tmp.num_counters != tinfo.nentries))
return -EINVAL;
memcpy(&repl, &tmp, sizeof(repl));
if (cmd == EBT_SO_GET_ENTRIES)
ret = compat_table_info(t->private, &repl);
else
ret = compat_table_info(&tinfo, &repl);
if (ret)
return ret;
if (*len != sizeof(tmp) + repl.entries_size +
(tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) {
pr_err("wrong size: *len %d, entries_size %u, replsz %d\n",
*len, tinfo.entries_size, repl.entries_size);
return -EINVAL;
}
/* userspace might not need the counters */
ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters),
tmp.num_counters, tinfo.nentries);
if (ret)
return ret;
pos = compat_ptr(tmp.entries);
return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size,
compat_copy_entry_to_user, &pos, &tmp.entries_size);
}
struct ebt_entries_buf_state {
char *buf_kern_start; /* kernel buffer to copy (translated) data to */
u32 buf_kern_len; /* total size of kernel buffer */
u32 buf_kern_offset; /* amount of data copied so far */
u32 buf_user_offset; /* read position in userspace buffer */
};
static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz)
{
state->buf_kern_offset += sz;
return state->buf_kern_offset >= sz ? 0 : -EINVAL;
}
static int ebt_buf_add(struct ebt_entries_buf_state *state,
void *data, unsigned int sz)
{
if (state->buf_kern_start == NULL)
goto count_only;
BUG_ON(state->buf_kern_offset + sz > state->buf_kern_len);
memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz);
count_only:
state->buf_user_offset += sz;
return ebt_buf_count(state, sz);
}
static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz)
{
char *b = state->buf_kern_start;
BUG_ON(b && state->buf_kern_offset > state->buf_kern_len);
if (b != NULL && sz > 0)
memset(b + state->buf_kern_offset, 0, sz);
/* do not adjust ->buf_user_offset here, we added kernel-side padding */
return ebt_buf_count(state, sz);
}
enum compat_mwt {
EBT_COMPAT_MATCH,
EBT_COMPAT_WATCHER,
EBT_COMPAT_TARGET,
};
static int compat_mtw_from_user(struct compat_ebt_entry_mwt *mwt,
enum compat_mwt compat_mwt,
struct ebt_entries_buf_state *state,
const unsigned char *base)
{
char name[EBT_FUNCTION_MAXNAMELEN];
struct xt_match *match;
struct xt_target *wt;
void *dst = NULL;
int off, pad = 0, ret = 0;
unsigned int size_kern, entry_offset, match_size = mwt->match_size;
strlcpy(name, mwt->u.name, sizeof(name));
if (state->buf_kern_start)
dst = state->buf_kern_start + state->buf_kern_offset;
entry_offset = (unsigned char *) mwt - base;
switch (compat_mwt) {
case EBT_COMPAT_MATCH:
match = try_then_request_module(xt_find_match(NFPROTO_BRIDGE,
name, 0), "ebt_%s", name);
if (match == NULL)
return -ENOENT;
if (IS_ERR(match))
return PTR_ERR(match);
off = ebt_compat_match_offset(match, match_size);
if (dst) {
if (match->compat_from_user)
match->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = match->matchsize;
if (unlikely(size_kern == -1))
size_kern = match_size;
module_put(match->me);
break;
case EBT_COMPAT_WATCHER: /* fallthrough */
case EBT_COMPAT_TARGET:
wt = try_then_request_module(xt_find_target(NFPROTO_BRIDGE,
name, 0), "ebt_%s", name);
if (wt == NULL)
return -ENOENT;
if (IS_ERR(wt))
return PTR_ERR(wt);
off = xt_compat_target_offset(wt);
if (dst) {
if (wt->compat_from_user)
wt->compat_from_user(dst, mwt->data);
else
memcpy(dst, mwt->data, match_size);
}
size_kern = wt->targetsize;
module_put(wt->me);
break;
}
if (!dst) {
ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset,
off + ebt_compat_entry_padsize());
if (ret < 0)
return ret;
}
state->buf_kern_offset += match_size + off;
state->buf_user_offset += match_size;
pad = XT_ALIGN(size_kern) - size_kern;
if (pad > 0 && dst) {
BUG_ON(state->buf_kern_len <= pad);
BUG_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad);
memset(dst + size_kern, 0, pad);
}
return off + match_size;
}
/*
* return size of all matches, watchers or target, including necessary
* alignment and padding.
*/
static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32,
unsigned int size_left, enum compat_mwt type,
struct ebt_entries_buf_state *state, const void *base)
{
int growth = 0;
char *buf;
if (size_left == 0)
return 0;
buf = (char *) match32;
while (size_left >= sizeof(*match32)) {
struct ebt_entry_match *match_kern;
int ret;
match_kern = (struct ebt_entry_match *) state->buf_kern_start;
if (match_kern) {
char *tmp;
tmp = state->buf_kern_start + state->buf_kern_offset;
match_kern = (struct ebt_entry_match *) tmp;
}
ret = ebt_buf_add(state, buf, sizeof(*match32));
if (ret < 0)
return ret;
size_left -= sizeof(*match32);
/* add padding before match->data (if any) */
ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize());
if (ret < 0)
return ret;
if (match32->match_size > size_left)
return -EINVAL;
size_left -= match32->match_size;
ret = compat_mtw_from_user(match32, type, state, base);
if (ret < 0)
return ret;
BUG_ON(ret < match32->match_size);
growth += ret - match32->match_size;
growth += ebt_compat_entry_padsize();
buf += sizeof(*match32);
buf += match32->match_size;
if (match_kern)
match_kern->match_size = ret;
WARN_ON(type == EBT_COMPAT_TARGET && size_left);
match32 = (struct compat_ebt_entry_mwt *) buf;
}
return growth;
}
#define EBT_COMPAT_WATCHER_ITERATE(e, fn, args...) \
({ \
unsigned int __i; \
int __ret = 0; \
struct compat_ebt_entry_mwt *__watcher; \
\
for (__i = e->watchers_offset; \
__i < (e)->target_offset; \
__i += __watcher->watcher_size + \
sizeof(struct compat_ebt_entry_mwt)) { \
__watcher = (void *)(e) + __i; \
__ret = fn(__watcher , ## args); \
if (__ret != 0) \
break; \
} \
if (__ret == 0) { \
if (__i != (e)->target_offset) \
__ret = -EINVAL; \
} \
__ret; \
})
#define EBT_COMPAT_MATCH_ITERATE(e, fn, args...) \
({ \
unsigned int __i; \
int __ret = 0; \
struct compat_ebt_entry_mwt *__match; \
\
for (__i = sizeof(struct ebt_entry); \
__i < (e)->watchers_offset; \
__i += __match->match_size + \
sizeof(struct compat_ebt_entry_mwt)) { \
__match = (void *)(e) + __i; \
__ret = fn(__match , ## args); \
if (__ret != 0) \
break; \
} \
if (__ret == 0) { \
if (__i != (e)->watchers_offset) \
__ret = -EINVAL; \
} \
__ret; \
})
/* called for all ebt_entry structures. */
static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base,
unsigned int *total,
struct ebt_entries_buf_state *state)
{
unsigned int i, j, startoff, new_offset = 0;
/* stores match/watchers/targets & offset of next struct ebt_entry: */
unsigned int offsets[4];
unsigned int *offsets_update = NULL;
int ret;
char *buf_start;
if (*total < sizeof(struct ebt_entries))
return -EINVAL;
if (!entry->bitmask) {
*total -= sizeof(struct ebt_entries);
return ebt_buf_add(state, entry, sizeof(struct ebt_entries));
}
if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry))
return -EINVAL;
startoff = state->buf_user_offset;
/* pull in most part of ebt_entry, it does not need to be changed. */
ret = ebt_buf_add(state, entry,
offsetof(struct ebt_entry, watchers_offset));
if (ret < 0)
return ret;
offsets[0] = sizeof(struct ebt_entry); /* matches come first */
memcpy(&offsets[1], &entry->watchers_offset,
sizeof(offsets) - sizeof(offsets[0]));
if (state->buf_kern_start) {
buf_start = state->buf_kern_start + state->buf_kern_offset;
offsets_update = (unsigned int *) buf_start;
}
ret = ebt_buf_add(state, &offsets[1],
sizeof(offsets) - sizeof(offsets[0]));
if (ret < 0)
return ret;
buf_start = (char *) entry;
/*
* 0: matches offset, always follows ebt_entry.
* 1: watchers offset, from ebt_entry structure
* 2: target offset, from ebt_entry structure
* 3: next ebt_entry offset, from ebt_entry structure
*
* offsets are relative to beginning of struct ebt_entry (i.e., 0).
*/
for (i = 0, j = 1 ; j < 4 ; j++, i++) {
struct compat_ebt_entry_mwt *match32;
unsigned int size;
char *buf = buf_start;
buf = buf_start + offsets[i];
if (offsets[i] > offsets[j])
return -EINVAL;
match32 = (struct compat_ebt_entry_mwt *) buf;
size = offsets[j] - offsets[i];
ret = ebt_size_mwt(match32, size, i, state, base);
if (ret < 0)
return ret;
new_offset += ret;
if (offsets_update && new_offset) {
pr_debug("change offset %d to %d\n",
offsets_update[i], offsets[j] + new_offset);
offsets_update[i] = offsets[j] + new_offset;
}
}
startoff = state->buf_user_offset - startoff;
BUG_ON(*total < startoff);
*total -= startoff;
return 0;
}
/*
* repl->entries_size is the size of the ebt_entry blob in userspace.
* It might need more memory when copied to a 64 bit kernel in case
* userspace is 32-bit. So, first task: find out how much memory is needed.
*
* Called before validation is performed.
*/
static int compat_copy_entries(unsigned char *data, unsigned int size_user,
struct ebt_entries_buf_state *state)
{
unsigned int size_remaining = size_user;
int ret;
ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data,
&size_remaining, state);
if (ret < 0)
return ret;
WARN_ON(size_remaining);
return state->buf_kern_offset;
}
static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl,
void __user *user, unsigned int len)
{
struct compat_ebt_replace tmp;
int i;
if (len < sizeof(tmp))
return -EINVAL;
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
if (len != sizeof(tmp) + tmp.entries_size)
return -EINVAL;
if (tmp.entries_size == 0)
return -EINVAL;
if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) /
NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter))
return -ENOMEM;
if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter))
return -ENOMEM;
memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry));
/* starting with hook_entry, 32 vs. 64 bit structures are different */
for (i = 0; i < NF_BR_NUMHOOKS; i++)
repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]);
repl->num_counters = tmp.num_counters;
repl->counters = compat_ptr(tmp.counters);
repl->entries = compat_ptr(tmp.entries);
return 0;
}
static int compat_do_replace(struct net *net, void __user *user,
unsigned int len)
{
int ret, i, countersize, size64;
struct ebt_table_info *newinfo;
struct ebt_replace tmp;
struct ebt_entries_buf_state state;
void *entries_tmp;
ret = compat_copy_ebt_replace_from_user(&tmp, user, len);
if (ret) {
/* try real handler in case userland supplied needed padding */
if (ret == -EINVAL && do_replace(net, user, len) == 0)
ret = 0;
return ret;
}
countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids;
newinfo = vmalloc(sizeof(*newinfo) + countersize);
if (!newinfo)
return -ENOMEM;
if (countersize)
memset(newinfo->counters, 0, countersize);
memset(&state, 0, sizeof(state));
newinfo->entries = vmalloc(tmp.entries_size);
if (!newinfo->entries) {
ret = -ENOMEM;
goto free_newinfo;
}
if (copy_from_user(
newinfo->entries, tmp.entries, tmp.entries_size) != 0) {
ret = -EFAULT;
goto free_entries;
}
entries_tmp = newinfo->entries;
xt_compat_lock(NFPROTO_BRIDGE);
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
if (ret < 0)
goto out_unlock;
pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n",
tmp.entries_size, state.buf_kern_offset, state.buf_user_offset,
xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size));
size64 = ret;
newinfo->entries = vmalloc(size64);
if (!newinfo->entries) {
vfree(entries_tmp);
ret = -ENOMEM;
goto out_unlock;
}
memset(&state, 0, sizeof(state));
state.buf_kern_start = newinfo->entries;
state.buf_kern_len = size64;
ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state);
BUG_ON(ret < 0); /* parses same data again */
vfree(entries_tmp);
tmp.entries_size = size64;
for (i = 0; i < NF_BR_NUMHOOKS; i++) {
char __user *usrptr;
if (tmp.hook_entry[i]) {
unsigned int delta;
usrptr = (char __user *) tmp.hook_entry[i];
delta = usrptr - tmp.entries;
usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta);
tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr;
}
}
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
ret = do_replace_finish(net, &tmp, newinfo);
if (ret == 0)
return ret;
free_entries:
vfree(newinfo->entries);
free_newinfo:
vfree(newinfo);
return ret;
out_unlock:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
goto free_entries;
}
static int compat_update_counters(struct net *net, void __user *user,
unsigned int len)
{
struct compat_ebt_replace hlp;
if (copy_from_user(&hlp, user, sizeof(hlp)))
return -EFAULT;
/* try real handler in case userland supplied needed padding */
if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter))
return update_counters(net, user, len);
return do_update_counters(net, hlp.name, compat_ptr(hlp.counters),
hlp.num_counters, user, len);
}
static int compat_do_ebt_set_ctl(struct sock *sk,
int cmd, void __user *user, unsigned int len)
{
int ret;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (cmd) {
case EBT_SO_SET_ENTRIES:
ret = compat_do_replace(sock_net(sk), user, len);
break;
case EBT_SO_SET_COUNTERS:
ret = compat_update_counters(sock_net(sk), user, len);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int compat_do_ebt_get_ctl(struct sock *sk, int cmd,
void __user *user, int *len)
{
int ret;
struct compat_ebt_replace tmp;
struct ebt_table *t;
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* try real handler in case userland supplied needed padding */
if ((cmd == EBT_SO_GET_INFO ||
cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp))
return do_ebt_get_ctl(sk, cmd, user, len);
if (copy_from_user(&tmp, user, sizeof(tmp)))
return -EFAULT;
t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex);
if (!t)
return ret;
xt_compat_lock(NFPROTO_BRIDGE);
switch (cmd) {
case EBT_SO_GET_INFO:
tmp.nentries = t->private->nentries;
ret = compat_table_info(t->private, &tmp);
if (ret)
goto out;
tmp.valid_hooks = t->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_INIT_INFO:
tmp.nentries = t->table->nentries;
tmp.entries_size = t->table->entries_size;
tmp.valid_hooks = t->table->valid_hooks;
if (copy_to_user(user, &tmp, *len) != 0) {
ret = -EFAULT;
break;
}
ret = 0;
break;
case EBT_SO_GET_ENTRIES:
case EBT_SO_GET_INIT_ENTRIES:
/*
* try real handler first in case of userland-side padding.
* in case we are dealing with an 'ordinary' 32 bit binary
* without 64bit compatibility padding, this will fail right
* after copy_from_user when the *len argument is validated.
*
* the compat_ variant needs to do one pass over the kernel
* data set to adjust for size differences before it the check.
*/
if (copy_everything_to_user(t, user, len, cmd) == 0)
ret = 0;
else
ret = compat_copy_everything_to_user(t, user, len, cmd);
break;
default:
ret = -EINVAL;
}
out:
xt_compat_flush_offsets(NFPROTO_BRIDGE);
xt_compat_unlock(NFPROTO_BRIDGE);
mutex_unlock(&ebt_mutex);
return ret;
}
#endif
static struct nf_sockopt_ops ebt_sockopts =
{
.pf = PF_INET,
.set_optmin = EBT_BASE_CTL,
.set_optmax = EBT_SO_SET_MAX + 1,
.set = do_ebt_set_ctl,
#ifdef CONFIG_COMPAT
.compat_set = compat_do_ebt_set_ctl,
#endif
.get_optmin = EBT_BASE_CTL,
.get_optmax = EBT_SO_GET_MAX + 1,
.get = do_ebt_get_ctl,
#ifdef CONFIG_COMPAT
.compat_get = compat_do_ebt_get_ctl,
#endif
.owner = THIS_MODULE,
};
static int __init ebtables_init(void)
{
int ret;
ret = xt_register_target(&ebt_standard_target);
if (ret < 0)
return ret;
ret = nf_register_sockopt(&ebt_sockopts);
if (ret < 0) {
xt_unregister_target(&ebt_standard_target);
return ret;
}
printk(KERN_INFO "Ebtables v2.0 registered\n");
return 0;
}
static void __exit ebtables_fini(void)
{
nf_unregister_sockopt(&ebt_sockopts);
xt_unregister_target(&ebt_standard_target);
printk(KERN_INFO "Ebtables v2.0 unregistered\n");
}
EXPORT_SYMBOL(ebt_register_table);
EXPORT_SYMBOL(ebt_unregister_table);
EXPORT_SYMBOL(ebt_do_table);
module_init(ebtables_init);
module_exit(ebtables_fini);
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3443_0 |
crossvul-cpp_data_bad_5844_4 | /*
* RAW sockets for IPv6
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Adapted from linux/net/ipv4/raw.c
*
* Fixes:
* Hideaki YOSHIFUJI : sin6_scope_id support
* YOSHIFUJI,H.@USAGI : raw checksum (RFC2292(bis) compliance)
* Kazunori MIYAZAWA @USAGI: change process style to use ip6_append_data
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/slab.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in6.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/icmpv6.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <linux/skbuff.h>
#include <linux/compat.h>
#include <asm/uaccess.h>
#include <asm/ioctls.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/ip6_checksum.h>
#include <net/addrconf.h>
#include <net/transp_v6.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/tcp_states.h>
#if IS_ENABLED(CONFIG_IPV6_MIP6)
#include <net/mip6.h>
#endif
#include <linux/mroute6.h>
#include <net/raw.h>
#include <net/rawv6.h>
#include <net/xfrm.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/export.h>
#define ICMPV6_HDRLEN 4 /* ICMPv6 header, RFC 4443 Section 2.1 */
static struct raw_hashinfo raw_v6_hashinfo = {
.lock = __RW_LOCK_UNLOCKED(raw_v6_hashinfo.lock),
};
static struct sock *__raw_v6_lookup(struct net *net, struct sock *sk,
unsigned short num, const struct in6_addr *loc_addr,
const struct in6_addr *rmt_addr, int dif)
{
bool is_multicast = ipv6_addr_is_multicast(loc_addr);
sk_for_each_from(sk)
if (inet_sk(sk)->inet_num == num) {
if (!net_eq(sock_net(sk), net))
continue;
if (!ipv6_addr_any(&sk->sk_v6_daddr) &&
!ipv6_addr_equal(&sk->sk_v6_daddr, rmt_addr))
continue;
if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)
continue;
if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr)) {
if (ipv6_addr_equal(&sk->sk_v6_rcv_saddr, loc_addr))
goto found;
if (is_multicast &&
inet6_mc_check(sk, loc_addr, rmt_addr))
goto found;
continue;
}
goto found;
}
sk = NULL;
found:
return sk;
}
/*
* 0 - deliver
* 1 - block
*/
static int icmpv6_filter(const struct sock *sk, const struct sk_buff *skb)
{
struct icmp6hdr _hdr;
const struct icmp6hdr *hdr;
/* We require only the four bytes of the ICMPv6 header, not any
* additional bytes of message body in "struct icmp6hdr".
*/
hdr = skb_header_pointer(skb, skb_transport_offset(skb),
ICMPV6_HDRLEN, &_hdr);
if (hdr) {
const __u32 *data = &raw6_sk(sk)->filter.data[0];
unsigned int type = hdr->icmp6_type;
return (data[type >> 5] & (1U << (type & 31))) != 0;
}
return 1;
}
#if IS_ENABLED(CONFIG_IPV6_MIP6)
typedef int mh_filter_t(struct sock *sock, struct sk_buff *skb);
static mh_filter_t __rcu *mh_filter __read_mostly;
int rawv6_mh_filter_register(mh_filter_t filter)
{
rcu_assign_pointer(mh_filter, filter);
return 0;
}
EXPORT_SYMBOL(rawv6_mh_filter_register);
int rawv6_mh_filter_unregister(mh_filter_t filter)
{
RCU_INIT_POINTER(mh_filter, NULL);
synchronize_rcu();
return 0;
}
EXPORT_SYMBOL(rawv6_mh_filter_unregister);
#endif
/*
* demultiplex raw sockets.
* (should consider queueing the skb in the sock receive_queue
* without calling rawv6.c)
*
* Caller owns SKB so we must make clones.
*/
static bool ipv6_raw_deliver(struct sk_buff *skb, int nexthdr)
{
const struct in6_addr *saddr;
const struct in6_addr *daddr;
struct sock *sk;
bool delivered = false;
__u8 hash;
struct net *net;
saddr = &ipv6_hdr(skb)->saddr;
daddr = saddr + 1;
hash = nexthdr & (RAW_HTABLE_SIZE - 1);
read_lock(&raw_v6_hashinfo.lock);
sk = sk_head(&raw_v6_hashinfo.ht[hash]);
if (sk == NULL)
goto out;
net = dev_net(skb->dev);
sk = __raw_v6_lookup(net, sk, nexthdr, daddr, saddr, IP6CB(skb)->iif);
while (sk) {
int filtered;
delivered = true;
switch (nexthdr) {
case IPPROTO_ICMPV6:
filtered = icmpv6_filter(sk, skb);
break;
#if IS_ENABLED(CONFIG_IPV6_MIP6)
case IPPROTO_MH:
{
/* XXX: To validate MH only once for each packet,
* this is placed here. It should be after checking
* xfrm policy, however it doesn't. The checking xfrm
* policy is placed in rawv6_rcv() because it is
* required for each socket.
*/
mh_filter_t *filter;
filter = rcu_dereference(mh_filter);
filtered = filter ? (*filter)(sk, skb) : 0;
break;
}
#endif
default:
filtered = 0;
break;
}
if (filtered < 0)
break;
if (filtered == 0) {
struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
/* Not releasing hash table! */
if (clone) {
nf_reset(clone);
rawv6_rcv(sk, clone);
}
}
sk = __raw_v6_lookup(net, sk_next(sk), nexthdr, daddr, saddr,
IP6CB(skb)->iif);
}
out:
read_unlock(&raw_v6_hashinfo.lock);
return delivered;
}
bool raw6_local_deliver(struct sk_buff *skb, int nexthdr)
{
struct sock *raw_sk;
raw_sk = sk_head(&raw_v6_hashinfo.ht[nexthdr & (RAW_HTABLE_SIZE - 1)]);
if (raw_sk && !ipv6_raw_deliver(skb, nexthdr))
raw_sk = NULL;
return raw_sk != NULL;
}
/* This cleans up af_inet6 a bit. -DaveM */
static int rawv6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_in6 *addr = (struct sockaddr_in6 *) uaddr;
__be32 v4addr = 0;
int addr_type;
int err;
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
addr_type = ipv6_addr_type(&addr->sin6_addr);
/* Raw sockets are IPv6 only */
if (addr_type == IPV6_ADDR_MAPPED)
return -EADDRNOTAVAIL;
lock_sock(sk);
err = -EINVAL;
if (sk->sk_state != TCP_CLOSE)
goto out;
rcu_read_lock();
/* Check if the address belongs to the host. */
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
if (__ipv6_addr_needs_scope_id(addr_type)) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
addr->sin6_scope_id) {
/* Override any existing binding, if another
* one is supplied by user.
*/
sk->sk_bound_dev_if = addr->sin6_scope_id;
}
/* Binding to link-local address requires an interface */
if (!sk->sk_bound_dev_if)
goto out_unlock;
err = -ENODEV;
dev = dev_get_by_index_rcu(sock_net(sk),
sk->sk_bound_dev_if);
if (!dev)
goto out_unlock;
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
if (!(addr_type & IPV6_ADDR_MULTICAST)) {
err = -EADDRNOTAVAIL;
if (!ipv6_chk_addr(sock_net(sk), &addr->sin6_addr,
dev, 0)) {
goto out_unlock;
}
}
}
inet->inet_rcv_saddr = inet->inet_saddr = v4addr;
sk->sk_v6_rcv_saddr = addr->sin6_addr;
if (!(addr_type & IPV6_ADDR_MULTICAST))
np->saddr = addr->sin6_addr;
err = 0;
out_unlock:
rcu_read_unlock();
out:
release_sock(sk);
return err;
}
static void rawv6_err(struct sock *sk, struct sk_buff *skb,
struct inet6_skb_parm *opt,
u8 type, u8 code, int offset, __be32 info)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
int err;
int harderr;
/* Report error on raw socket, if:
1. User requested recverr.
2. Socket is connected (otherwise the error indication
is useless without recverr and error is hard.
*/
if (!np->recverr && sk->sk_state != TCP_ESTABLISHED)
return;
harderr = icmpv6_err_convert(type, code, &err);
if (type == ICMPV6_PKT_TOOBIG) {
ip6_sk_update_pmtu(skb, sk, info);
harderr = (np->pmtudisc == IPV6_PMTUDISC_DO);
}
if (type == NDISC_REDIRECT) {
ip6_sk_redirect(skb, sk);
return;
}
if (np->recverr) {
u8 *payload = skb->data;
if (!inet->hdrincl)
payload += offset;
ipv6_icmp_error(sk, skb, err, 0, ntohl(info), payload);
}
if (np->recverr || harderr) {
sk->sk_err = err;
sk->sk_error_report(sk);
}
}
void raw6_icmp_error(struct sk_buff *skb, int nexthdr,
u8 type, u8 code, int inner_offset, __be32 info)
{
struct sock *sk;
int hash;
const struct in6_addr *saddr, *daddr;
struct net *net;
hash = nexthdr & (RAW_HTABLE_SIZE - 1);
read_lock(&raw_v6_hashinfo.lock);
sk = sk_head(&raw_v6_hashinfo.ht[hash]);
if (sk != NULL) {
/* Note: ipv6_hdr(skb) != skb->data */
const struct ipv6hdr *ip6h = (const struct ipv6hdr *)skb->data;
saddr = &ip6h->saddr;
daddr = &ip6h->daddr;
net = dev_net(skb->dev);
while ((sk = __raw_v6_lookup(net, sk, nexthdr, saddr, daddr,
IP6CB(skb)->iif))) {
rawv6_err(sk, skb, NULL, type, code,
inner_offset, info);
sk = sk_next(sk);
}
}
read_unlock(&raw_v6_hashinfo.lock);
}
static inline int rawv6_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
if ((raw6_sk(sk)->checksum || rcu_access_pointer(sk->sk_filter)) &&
skb_checksum_complete(skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb(skb);
return NET_RX_DROP;
}
/* Charge it to the socket. */
skb_dst_drop(skb);
if (sock_queue_rcv_skb(sk, skb) < 0) {
kfree_skb(skb);
return NET_RX_DROP;
}
return 0;
}
/*
* This is next to useless...
* if we demultiplex in network layer we don't need the extra call
* just to queue the skb...
* maybe we could have the network decide upon a hint if it
* should call raw_rcv for demultiplexing
*/
int rawv6_rcv(struct sock *sk, struct sk_buff *skb)
{
struct inet_sock *inet = inet_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb(skb);
return NET_RX_DROP;
}
if (!rp->checksum)
skb->ip_summed = CHECKSUM_UNNECESSARY;
if (skb->ip_summed == CHECKSUM_COMPLETE) {
skb_postpull_rcsum(skb, skb_network_header(skb),
skb_network_header_len(skb));
if (!csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
skb->len, inet->inet_num, skb->csum))
skb->ip_summed = CHECKSUM_UNNECESSARY;
}
if (!skb_csum_unnecessary(skb))
skb->csum = ~csum_unfold(csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
skb->len,
inet->inet_num, 0));
if (inet->hdrincl) {
if (skb_checksum_complete(skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb(skb);
return NET_RX_DROP;
}
}
rawv6_rcv_skb(sk, skb);
return 0;
}
/*
* This should be easy, if there is something there
* we return it, otherwise we block.
*/
static int rawv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name;
struct sk_buff *skb;
size_t copied;
int err;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
if (addr_len)
*addr_len=sizeof(*sin6);
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
if (skb_csum_unnecessary(skb)) {
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
} else if (msg->msg_flags&MSG_TRUNC) {
if (__skb_checksum_complete(skb))
goto csum_copy_err;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
} else {
err = skb_copy_and_csum_datagram_iovec(skb, 0, msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (err)
goto out_free;
/* Copy the address. */
if (sin6) {
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_flowinfo = 0;
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
}
sock_recv_ts_and_drops(msg, sk, skb);
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = skb->len;
out_free:
skb_free_datagram(sk, skb);
out:
return err;
csum_copy_err:
skb_kill_datagram(sk, skb, flags);
/* Error for blocking case is chosen to masquerade
as some normal condition.
*/
err = (flags&MSG_DONTWAIT) ? -EAGAIN : -EHOSTUNREACH;
goto out;
}
static int rawv6_push_pending_frames(struct sock *sk, struct flowi6 *fl6,
struct raw6_sock *rp)
{
struct sk_buff *skb;
int err = 0;
int offset;
int len;
int total_len;
__wsum tmp_csum;
__sum16 csum;
if (!rp->checksum)
goto send;
if ((skb = skb_peek(&sk->sk_write_queue)) == NULL)
goto out;
offset = rp->offset;
total_len = inet_sk(sk)->cork.base.length;
if (offset >= total_len - 1) {
err = -EINVAL;
ip6_flush_pending_frames(sk);
goto out;
}
/* should be check HW csum miyazawa */
if (skb_queue_len(&sk->sk_write_queue) == 1) {
/*
* Only one fragment on the socket.
*/
tmp_csum = skb->csum;
} else {
struct sk_buff *csum_skb = NULL;
tmp_csum = 0;
skb_queue_walk(&sk->sk_write_queue, skb) {
tmp_csum = csum_add(tmp_csum, skb->csum);
if (csum_skb)
continue;
len = skb->len - skb_transport_offset(skb);
if (offset >= len) {
offset -= len;
continue;
}
csum_skb = skb;
}
skb = csum_skb;
}
offset += skb_transport_offset(skb);
if (skb_copy_bits(skb, offset, &csum, 2))
BUG();
/* in case cksum was not initialized */
if (unlikely(csum))
tmp_csum = csum_sub(tmp_csum, csum_unfold(csum));
csum = csum_ipv6_magic(&fl6->saddr, &fl6->daddr,
total_len, fl6->flowi6_proto, tmp_csum);
if (csum == 0 && fl6->flowi6_proto == IPPROTO_UDP)
csum = CSUM_MANGLED_0;
if (skb_store_bits(skb, offset, &csum, 2))
BUG();
send:
err = ip6_push_pending_frames(sk);
out:
return err;
}
static int rawv6_send_hdrinc(struct sock *sk, void *from, int length,
struct flowi6 *fl6, struct dst_entry **dstp,
unsigned int flags)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6hdr *iph;
struct sk_buff *skb;
int err;
struct rt6_info *rt = (struct rt6_info *)*dstp;
int hlen = LL_RESERVED_SPACE(rt->dst.dev);
int tlen = rt->dst.dev->needed_tailroom;
if (length > rt->dst.dev->mtu) {
ipv6_local_error(sk, EMSGSIZE, fl6, rt->dst.dev->mtu);
return -EMSGSIZE;
}
if (flags&MSG_PROBE)
goto out;
skb = sock_alloc_send_skb(sk,
length + hlen + tlen + 15,
flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto error;
skb_reserve(skb, hlen);
skb->protocol = htons(ETH_P_IPV6);
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, &rt->dst);
*dstp = NULL;
skb_put(skb, length);
skb_reset_network_header(skb);
iph = ipv6_hdr(skb);
skb->ip_summed = CHECKSUM_NONE;
skb->transport_header = skb->network_header;
err = memcpy_fromiovecend((void *)iph, from, 0, length);
if (err)
goto error_fault;
IP6_UPD_PO_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len);
err = NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL,
rt->dst.dev, dst_output);
if (err > 0)
err = net_xmit_errno(err);
if (err)
goto error;
out:
return 0;
error_fault:
err = -EFAULT;
kfree_skb(skb);
error:
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
if (err == -ENOBUFS && !np->recverr)
err = 0;
return err;
}
static int rawv6_probe_proto_opt(struct flowi6 *fl6, struct msghdr *msg)
{
struct iovec *iov;
u8 __user *type = NULL;
u8 __user *code = NULL;
u8 len = 0;
int probed = 0;
int i;
if (!msg->msg_iov)
return 0;
for (i = 0; i < msg->msg_iovlen; i++) {
iov = &msg->msg_iov[i];
if (!iov)
continue;
switch (fl6->flowi6_proto) {
case IPPROTO_ICMPV6:
/* check if one-byte field is readable or not. */
if (iov->iov_base && iov->iov_len < 1)
break;
if (!type) {
type = iov->iov_base;
/* check if code field is readable or not. */
if (iov->iov_len > 1)
code = type + 1;
} else if (!code)
code = iov->iov_base;
if (type && code) {
if (get_user(fl6->fl6_icmp_type, type) ||
get_user(fl6->fl6_icmp_code, code))
return -EFAULT;
probed = 1;
}
break;
case IPPROTO_MH:
if (iov->iov_base && iov->iov_len < 1)
break;
/* check if type field is readable or not. */
if (iov->iov_len > 2 - len) {
u8 __user *p = iov->iov_base;
if (get_user(fl6->fl6_mh_type, &p[2 - len]))
return -EFAULT;
probed = 1;
} else
len += iov->iov_len;
break;
default:
probed = 1;
break;
}
if (probed)
break;
}
return 0;
}
static int rawv6_sendmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
struct sockaddr_in6 * sin6 = (struct sockaddr_in6 *) msg->msg_name;
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
daddr = &flowlabel->dst;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (opt == NULL)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
err = rawv6_probe_proto_opt(&fl6, msg);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p, true);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0) {
if (ipv6_addr_is_multicast(&fl6.daddr))
hlimit = np->mcast_hops;
else
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
}
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg->msg_iov, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info*)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err<0?err:len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
static int rawv6_seticmpfilter(struct sock *sk, int level, int optname,
char __user *optval, int optlen)
{
switch (optname) {
case ICMPV6_FILTER:
if (optlen > sizeof(struct icmp6_filter))
optlen = sizeof(struct icmp6_filter);
if (copy_from_user(&raw6_sk(sk)->filter, optval, optlen))
return -EFAULT;
return 0;
default:
return -ENOPROTOOPT;
}
return 0;
}
static int rawv6_geticmpfilter(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
int len;
switch (optname) {
case ICMPV6_FILTER:
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
if (len > sizeof(struct icmp6_filter))
len = sizeof(struct icmp6_filter);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, &raw6_sk(sk)->filter, len))
return -EFAULT;
return 0;
default:
return -ENOPROTOOPT;
}
return 0;
}
static int do_rawv6_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct raw6_sock *rp = raw6_sk(sk);
int val;
if (get_user(val, (int __user *)optval))
return -EFAULT;
switch (optname) {
case IPV6_CHECKSUM:
if (inet_sk(sk)->inet_num == IPPROTO_ICMPV6 &&
level == IPPROTO_IPV6) {
/*
* RFC3542 tells that IPV6_CHECKSUM socket
* option in the IPPROTO_IPV6 level is not
* allowed on ICMPv6 sockets.
* If you want to set it, use IPPROTO_RAW
* level IPV6_CHECKSUM socket option
* (Linux extension).
*/
return -EINVAL;
}
/* You may get strange result with a positive odd offset;
RFC2292bis agrees with me. */
if (val > 0 && (val&1))
return -EINVAL;
if (val < 0) {
rp->checksum = 0;
} else {
rp->checksum = 1;
rp->offset = val;
}
return 0;
default:
return -ENOPROTOOPT;
}
}
static int rawv6_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
switch (level) {
case SOL_RAW:
break;
case SOL_ICMPV6:
if (inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
return rawv6_seticmpfilter(sk, level, optname, optval, optlen);
case SOL_IPV6:
if (optname == IPV6_CHECKSUM)
break;
default:
return ipv6_setsockopt(sk, level, optname, optval, optlen);
}
return do_rawv6_setsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
static int compat_rawv6_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
switch (level) {
case SOL_RAW:
break;
case SOL_ICMPV6:
if (inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
return rawv6_seticmpfilter(sk, level, optname, optval, optlen);
case SOL_IPV6:
if (optname == IPV6_CHECKSUM)
break;
default:
return compat_ipv6_setsockopt(sk, level, optname,
optval, optlen);
}
return do_rawv6_setsockopt(sk, level, optname, optval, optlen);
}
#endif
static int do_rawv6_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
struct raw6_sock *rp = raw6_sk(sk);
int val, len;
if (get_user(len,optlen))
return -EFAULT;
switch (optname) {
case IPV6_CHECKSUM:
/*
* We allow getsockopt() for IPPROTO_IPV6-level
* IPV6_CHECKSUM socket option on ICMPv6 sockets
* since RFC3542 is silent about it.
*/
if (rp->checksum == 0)
val = -1;
else
val = rp->offset;
break;
default:
return -ENOPROTOOPT;
}
len = min_t(unsigned int, sizeof(int), len);
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval,&val,len))
return -EFAULT;
return 0;
}
static int rawv6_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
switch (level) {
case SOL_RAW:
break;
case SOL_ICMPV6:
if (inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
return rawv6_geticmpfilter(sk, level, optname, optval, optlen);
case SOL_IPV6:
if (optname == IPV6_CHECKSUM)
break;
default:
return ipv6_getsockopt(sk, level, optname, optval, optlen);
}
return do_rawv6_getsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
static int compat_rawv6_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
switch (level) {
case SOL_RAW:
break;
case SOL_ICMPV6:
if (inet_sk(sk)->inet_num != IPPROTO_ICMPV6)
return -EOPNOTSUPP;
return rawv6_geticmpfilter(sk, level, optname, optval, optlen);
case SOL_IPV6:
if (optname == IPV6_CHECKSUM)
break;
default:
return compat_ipv6_getsockopt(sk, level, optname,
optval, optlen);
}
return do_rawv6_getsockopt(sk, level, optname, optval, optlen);
}
#endif
static int rawv6_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ: {
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ: {
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL)
amount = skb_tail_pointer(skb) -
skb_transport_header(skb);
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
default:
#ifdef CONFIG_IPV6_MROUTE
return ip6mr_ioctl(sk, cmd, (void __user *)arg);
#else
return -ENOIOCTLCMD;
#endif
}
}
#ifdef CONFIG_COMPAT
static int compat_rawv6_ioctl(struct sock *sk, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
case SIOCINQ:
return -ENOIOCTLCMD;
default:
#ifdef CONFIG_IPV6_MROUTE
return ip6mr_compat_ioctl(sk, cmd, compat_ptr(arg));
#else
return -ENOIOCTLCMD;
#endif
}
}
#endif
static void rawv6_close(struct sock *sk, long timeout)
{
if (inet_sk(sk)->inet_num == IPPROTO_RAW)
ip6_ra_control(sk, -1);
ip6mr_sk_done(sk);
sk_common_release(sk);
}
static void raw6_destroy(struct sock *sk)
{
lock_sock(sk);
ip6_flush_pending_frames(sk);
release_sock(sk);
inet6_destroy_sock(sk);
}
static int rawv6_init_sk(struct sock *sk)
{
struct raw6_sock *rp = raw6_sk(sk);
switch (inet_sk(sk)->inet_num) {
case IPPROTO_ICMPV6:
rp->checksum = 1;
rp->offset = 2;
break;
case IPPROTO_MH:
rp->checksum = 1;
rp->offset = 4;
break;
default:
break;
}
return 0;
}
struct proto rawv6_prot = {
.name = "RAWv6",
.owner = THIS_MODULE,
.close = rawv6_close,
.destroy = raw6_destroy,
.connect = ip6_datagram_connect,
.disconnect = udp_disconnect,
.ioctl = rawv6_ioctl,
.init = rawv6_init_sk,
.setsockopt = rawv6_setsockopt,
.getsockopt = rawv6_getsockopt,
.sendmsg = rawv6_sendmsg,
.recvmsg = rawv6_recvmsg,
.bind = rawv6_bind,
.backlog_rcv = rawv6_rcv_skb,
.hash = raw_hash_sk,
.unhash = raw_unhash_sk,
.obj_size = sizeof(struct raw6_sock),
.h.raw_hash = &raw_v6_hashinfo,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_rawv6_setsockopt,
.compat_getsockopt = compat_rawv6_getsockopt,
.compat_ioctl = compat_rawv6_ioctl,
#endif
};
#ifdef CONFIG_PROC_FS
static int raw6_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN) {
seq_puts(seq, IPV6_SEQ_DGRAM_HEADER);
} else {
struct sock *sp = v;
__u16 srcp = inet_sk(sp)->inet_num;
ip6_dgram_sock_seq_show(seq, v, srcp, 0,
raw_seq_private(seq)->bucket);
}
return 0;
}
static const struct seq_operations raw6_seq_ops = {
.start = raw_seq_start,
.next = raw_seq_next,
.stop = raw_seq_stop,
.show = raw6_seq_show,
};
static int raw6_seq_open(struct inode *inode, struct file *file)
{
return raw_seq_open(inode, file, &raw_v6_hashinfo, &raw6_seq_ops);
}
static const struct file_operations raw6_seq_fops = {
.owner = THIS_MODULE,
.open = raw6_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static int __net_init raw6_init_net(struct net *net)
{
if (!proc_create("raw6", S_IRUGO, net->proc_net, &raw6_seq_fops))
return -ENOMEM;
return 0;
}
static void __net_exit raw6_exit_net(struct net *net)
{
remove_proc_entry("raw6", net->proc_net);
}
static struct pernet_operations raw6_net_ops = {
.init = raw6_init_net,
.exit = raw6_exit_net,
};
int __init raw6_proc_init(void)
{
return register_pernet_subsys(&raw6_net_ops);
}
void raw6_proc_exit(void)
{
unregister_pernet_subsys(&raw6_net_ops);
}
#endif /* CONFIG_PROC_FS */
/* Same as inet6_dgram_ops, sans udp_poll. */
static const struct proto_ops inet6_sockraw_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = inet_dgram_connect, /* ok */
.socketpair = sock_no_socketpair, /* a do nothing */
.accept = sock_no_accept, /* a do nothing */
.getname = inet6_getname,
.poll = datagram_poll, /* ok */
.ioctl = inet6_ioctl, /* must change */
.listen = sock_no_listen, /* ok */
.shutdown = inet_shutdown, /* ok */
.setsockopt = sock_common_setsockopt, /* ok */
.getsockopt = sock_common_getsockopt, /* ok */
.sendmsg = inet_sendmsg, /* ok */
.recvmsg = sock_common_recvmsg, /* ok */
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};
static struct inet_protosw rawv6_protosw = {
.type = SOCK_RAW,
.protocol = IPPROTO_IP, /* wild card */
.prot = &rawv6_prot,
.ops = &inet6_sockraw_ops,
.no_check = UDP_CSUM_DEFAULT,
.flags = INET_PROTOSW_REUSE,
};
int __init rawv6_init(void)
{
int ret;
ret = inet6_register_protosw(&rawv6_protosw);
if (ret)
goto out;
out:
return ret;
}
void rawv6_exit(void)
{
inet6_unregister_protosw(&rawv6_protosw);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5844_4 |
crossvul-cpp_data_good_2035_0 | /*
* linux/fs/namei.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* Some corrections by tytso.
*/
/* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname
* lookup logic.
*/
/* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/namei.h>
#include <linux/quotaops.h>
#include <linux/pagemap.h>
#include <linux/fsnotify.h>
#include <linux/personality.h>
#include <linux/security.h>
#include <linux/ima.h>
#include <linux/syscalls.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fcntl.h>
#include <linux/device_cgroup.h>
#include <linux/fs_struct.h>
#include <asm/uaccess.h>
#include "internal.h"
/* [Feb-1997 T. Schoebel-Theuer]
* Fundamental changes in the pathname lookup mechanisms (namei)
* were necessary because of omirr. The reason is that omirr needs
* to know the _real_ pathname, not the user-supplied one, in case
* of symlinks (and also when transname replacements occur).
*
* The new code replaces the old recursive symlink resolution with
* an iterative one (in case of non-nested symlink chains). It does
* this with calls to <fs>_follow_link().
* As a side effect, dir_namei(), _namei() and follow_link() are now
* replaced with a single function lookup_dentry() that can handle all
* the special cases of the former code.
*
* With the new dcache, the pathname is stored at each inode, at least as
* long as the refcount of the inode is positive. As a side effect, the
* size of the dcache depends on the inode cache and thus is dynamic.
*
* [29-Apr-1998 C. Scott Ananian] Updated above description of symlink
* resolution to correspond with current state of the code.
*
* Note that the symlink resolution is not *completely* iterative.
* There is still a significant amount of tail- and mid- recursion in
* the algorithm. Also, note that <fs>_readlink() is not used in
* lookup_dentry(): lookup_dentry() on the result of <fs>_readlink()
* may return different results than <fs>_follow_link(). Many virtual
* filesystems (including /proc) exhibit this behavior.
*/
/* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation:
* New symlink semantics: when open() is called with flags O_CREAT | O_EXCL
* and the name already exists in form of a symlink, try to create the new
* name indicated by the symlink. The old code always complained that the
* name already exists, due to not following the symlink even if its target
* is nonexistent. The new semantics affects also mknod() and link() when
* the name is a symlink pointing to a non-existant name.
*
* I don't know which semantics is the right one, since I have no access
* to standards. But I found by trial that HP-UX 9.0 has the full "new"
* semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the
* "old" one. Personally, I think the new semantics is much more logical.
* Note that "ln old new" where "new" is a symlink pointing to a non-existing
* file does succeed in both HP-UX and SunOs, but not in Solaris
* and in the old Linux semantics.
*/
/* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink
* semantics. See the comments in "open_namei" and "do_link" below.
*
* [10-Sep-98 Alan Modra] Another symlink change.
*/
/* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks:
* inside the path - always follow.
* in the last component in creation/removal/renaming - never follow.
* if LOOKUP_FOLLOW passed - follow.
* if the pathname has trailing slashes - follow.
* otherwise - don't follow.
* (applied in that order).
*
* [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT
* restored for 2.4. This is the last surviving part of old 4.2BSD bug.
* During the 2.4 we need to fix the userland stuff depending on it -
* hopefully we will be able to get rid of that wart in 2.5. So far only
* XEmacs seems to be relying on it...
*/
/*
* [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland)
* implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives
* any extra contention...
*/
/* In order to reduce some races, while at the same time doing additional
* checking and hopefully speeding things up, we copy filenames to the
* kernel data space before using them..
*
* POSIX.1 2.4: an empty pathname is invalid (ENOENT).
* PATH_MAX includes the nul terminator --RR.
*/
static int do_getname(const char __user *filename, char *page)
{
int retval;
unsigned long len = PATH_MAX;
if (!segment_eq(get_fs(), KERNEL_DS)) {
if ((unsigned long) filename >= TASK_SIZE)
return -EFAULT;
if (TASK_SIZE - (unsigned long) filename < PATH_MAX)
len = TASK_SIZE - (unsigned long) filename;
}
retval = strncpy_from_user(page, filename, len);
if (retval > 0) {
if (retval < len)
return 0;
return -ENAMETOOLONG;
} else if (!retval)
retval = -ENOENT;
return retval;
}
char * getname(const char __user * filename)
{
char *tmp, *result;
result = ERR_PTR(-ENOMEM);
tmp = __getname();
if (tmp) {
int retval = do_getname(filename, tmp);
result = tmp;
if (retval < 0) {
__putname(tmp);
result = ERR_PTR(retval);
}
}
audit_getname(result);
return result;
}
#ifdef CONFIG_AUDITSYSCALL
void putname(const char *name)
{
if (unlikely(!audit_dummy_context()))
audit_putname(name);
else
__putname(name);
}
EXPORT_SYMBOL(putname);
#endif
/*
* This does basic POSIX ACL permission checking
*/
static int acl_permission_check(struct inode *inode, int mask,
int (*check_acl)(struct inode *inode, int mask))
{
umode_t mode = inode->i_mode;
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (current_fsuid() == inode->i_uid)
mode >>= 6;
else {
if (IS_POSIXACL(inode) && (mode & S_IRWXG) && check_acl) {
int error = check_acl(inode, mask);
if (error != -EAGAIN)
return error;
}
if (in_group_p(inode->i_gid))
mode >>= 3;
}
/*
* If the DACs are ok we don't need any capability check.
*/
if ((mask & ~mode) == 0)
return 0;
return -EACCES;
}
/**
* generic_permission - check for access rights on a Posix-like filesystem
* @inode: inode to check access rights for
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
* @check_acl: optional callback to check for Posix ACLs
*
* Used to check for read/write/execute permissions on a file.
* We use "fsuid" for this, letting us set arbitrary permissions
* for filesystem access without changing the "normal" uids which
* are used for other things..
*/
int generic_permission(struct inode *inode, int mask,
int (*check_acl)(struct inode *inode, int mask))
{
int ret;
/*
* Do the basic POSIX ACL permission checks.
*/
ret = acl_permission_check(inode, mask, check_acl);
if (ret != -EACCES)
return ret;
/*
* Read/write DACs are always overridable.
* Executable DACs are overridable if at least one exec bit is set.
*/
if (!(mask & MAY_EXEC) || execute_ok(inode))
if (capable(CAP_DAC_OVERRIDE))
return 0;
/*
* Searching includes executable on directories, else just read.
*/
mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
if (mask == MAY_READ || (S_ISDIR(inode->i_mode) && !(mask & MAY_WRITE)))
if (capable(CAP_DAC_READ_SEARCH))
return 0;
return -EACCES;
}
/**
* inode_permission - check for access rights to a given inode
* @inode: inode to check permission on
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
*
* Used to check for read/write/execute permissions on an inode.
* We use "fsuid" for this, letting us set arbitrary permissions
* for filesystem access without changing the "normal" uids which
* are used for other things.
*/
int inode_permission(struct inode *inode, int mask)
{
int retval;
if (mask & MAY_WRITE) {
umode_t mode = inode->i_mode;
/*
* Nobody gets write access to a read-only fs.
*/
if (IS_RDONLY(inode) &&
(S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode)))
return -EROFS;
/*
* Nobody gets write access to an immutable file.
*/
if (IS_IMMUTABLE(inode))
return -EACCES;
}
if (inode->i_op->permission)
retval = inode->i_op->permission(inode, mask);
else
retval = generic_permission(inode, mask, inode->i_op->check_acl);
if (retval)
return retval;
retval = devcgroup_inode_permission(inode, mask);
if (retval)
return retval;
return security_inode_permission(inode,
mask & (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND));
}
/**
* file_permission - check for additional access rights to a given file
* @file: file to check access rights for
* @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC)
*
* Used to check for read/write/execute permissions on an already opened
* file.
*
* Note:
* Do not use this function in new code. All access checks should
* be done using inode_permission().
*/
int file_permission(struct file *file, int mask)
{
return inode_permission(file->f_path.dentry->d_inode, mask);
}
/*
* get_write_access() gets write permission for a file.
* put_write_access() releases this write permission.
* This is used for regular files.
* We cannot support write (and maybe mmap read-write shared) accesses and
* MAP_DENYWRITE mmappings simultaneously. The i_writecount field of an inode
* can have the following values:
* 0: no writers, no VM_DENYWRITE mappings
* < 0: (-i_writecount) vm_area_structs with VM_DENYWRITE set exist
* > 0: (i_writecount) users are writing to the file.
*
* Normally we operate on that counter with atomic_{inc,dec} and it's safe
* except for the cases where we don't hold i_writecount yet. Then we need to
* use {get,deny}_write_access() - these functions check the sign and refuse
* to do the change if sign is wrong. Exclusion between them is provided by
* the inode->i_lock spinlock.
*/
int get_write_access(struct inode * inode)
{
spin_lock(&inode->i_lock);
if (atomic_read(&inode->i_writecount) < 0) {
spin_unlock(&inode->i_lock);
return -ETXTBSY;
}
atomic_inc(&inode->i_writecount);
spin_unlock(&inode->i_lock);
return 0;
}
int deny_write_access(struct file * file)
{
struct inode *inode = file->f_path.dentry->d_inode;
spin_lock(&inode->i_lock);
if (atomic_read(&inode->i_writecount) > 0) {
spin_unlock(&inode->i_lock);
return -ETXTBSY;
}
atomic_dec(&inode->i_writecount);
spin_unlock(&inode->i_lock);
return 0;
}
/**
* path_get - get a reference to a path
* @path: path to get the reference to
*
* Given a path increment the reference count to the dentry and the vfsmount.
*/
void path_get(struct path *path)
{
mntget(path->mnt);
dget(path->dentry);
}
EXPORT_SYMBOL(path_get);
/**
* path_put - put a reference to a path
* @path: path to put the reference to
*
* Given a path decrement the reference count to the dentry and the vfsmount.
*/
void path_put(struct path *path)
{
dput(path->dentry);
mntput(path->mnt);
}
EXPORT_SYMBOL(path_put);
/**
* release_open_intent - free up open intent resources
* @nd: pointer to nameidata
*/
void release_open_intent(struct nameidata *nd)
{
if (nd->intent.open.file->f_path.dentry == NULL)
put_filp(nd->intent.open.file);
else
fput(nd->intent.open.file);
}
static inline struct dentry *
do_revalidate(struct dentry *dentry, struct nameidata *nd)
{
int status = dentry->d_op->d_revalidate(dentry, nd);
if (unlikely(status <= 0)) {
/*
* The dentry failed validation.
* If d_revalidate returned 0 attempt to invalidate
* the dentry otherwise d_revalidate is asking us
* to return a fail status.
*/
if (!status) {
if (!d_invalidate(dentry)) {
dput(dentry);
dentry = NULL;
}
} else {
dput(dentry);
dentry = ERR_PTR(status);
}
}
return dentry;
}
/*
* force_reval_path - force revalidation of a dentry
*
* In some situations the path walking code will trust dentries without
* revalidating them. This causes problems for filesystems that depend on
* d_revalidate to handle file opens (e.g. NFSv4). When FS_REVAL_DOT is set
* (which indicates that it's possible for the dentry to go stale), force
* a d_revalidate call before proceeding.
*
* Returns 0 if the revalidation was successful. If the revalidation fails,
* either return the error returned by d_revalidate or -ESTALE if the
* revalidation it just returned 0. If d_revalidate returns 0, we attempt to
* invalidate the dentry. It's up to the caller to handle putting references
* to the path if necessary.
*/
static int
force_reval_path(struct path *path, struct nameidata *nd)
{
int status;
struct dentry *dentry = path->dentry;
/*
* only check on filesystems where it's possible for the dentry to
* become stale. It's assumed that if this flag is set then the
* d_revalidate op will also be defined.
*/
if (!(dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT))
return 0;
status = dentry->d_op->d_revalidate(dentry, nd);
if (status > 0)
return 0;
if (!status) {
d_invalidate(dentry);
status = -ESTALE;
}
return status;
}
/*
* Short-cut version of permission(), for calling on directories
* during pathname resolution. Combines parts of permission()
* and generic_permission(), and tests ONLY for MAY_EXEC permission.
*
* If appropriate, check DAC only. If not appropriate, or
* short-cut DAC fails, then call ->permission() to do more
* complete permission check.
*/
static int exec_permission(struct inode *inode)
{
int ret;
if (inode->i_op->permission) {
ret = inode->i_op->permission(inode, MAY_EXEC);
if (!ret)
goto ok;
return ret;
}
ret = acl_permission_check(inode, MAY_EXEC, inode->i_op->check_acl);
if (!ret)
goto ok;
if (capable(CAP_DAC_OVERRIDE) || capable(CAP_DAC_READ_SEARCH))
goto ok;
return ret;
ok:
return security_inode_permission(inode, MAY_EXEC);
}
static __always_inline void set_root(struct nameidata *nd)
{
if (!nd->root.mnt) {
struct fs_struct *fs = current->fs;
read_lock(&fs->lock);
nd->root = fs->root;
path_get(&nd->root);
read_unlock(&fs->lock);
}
}
static int link_path_walk(const char *, struct nameidata *);
static __always_inline int __vfs_follow_link(struct nameidata *nd, const char *link)
{
int res = 0;
char *name;
if (IS_ERR(link))
goto fail;
if (*link == '/') {
set_root(nd);
path_put(&nd->path);
nd->path = nd->root;
path_get(&nd->root);
}
res = link_path_walk(link, nd);
if (nd->depth || res || nd->last_type!=LAST_NORM)
return res;
/*
* If it is an iterative symlinks resolution in open_namei() we
* have to copy the last component. And all that crap because of
* bloody create() on broken symlinks. Furrfu...
*/
name = __getname();
if (unlikely(!name)) {
path_put(&nd->path);
return -ENOMEM;
}
strcpy(name, nd->last.name);
nd->last.name = name;
return 0;
fail:
path_put(&nd->path);
return PTR_ERR(link);
}
static void path_put_conditional(struct path *path, struct nameidata *nd)
{
dput(path->dentry);
if (path->mnt != nd->path.mnt)
mntput(path->mnt);
}
static inline void path_to_nameidata(struct path *path, struct nameidata *nd)
{
dput(nd->path.dentry);
if (nd->path.mnt != path->mnt)
mntput(nd->path.mnt);
nd->path.mnt = path->mnt;
nd->path.dentry = path->dentry;
}
static __always_inline int __do_follow_link(struct path *path, struct nameidata *nd)
{
int error;
void *cookie;
struct dentry *dentry = path->dentry;
touch_atime(path->mnt, dentry);
nd_set_link(nd, NULL);
if (path->mnt != nd->path.mnt) {
path_to_nameidata(path, nd);
dget(dentry);
}
mntget(path->mnt);
nd->last_type = LAST_BIND;
cookie = dentry->d_inode->i_op->follow_link(dentry, nd);
error = PTR_ERR(cookie);
if (!IS_ERR(cookie)) {
char *s = nd_get_link(nd);
error = 0;
if (s)
error = __vfs_follow_link(nd, s);
else if (nd->last_type == LAST_BIND) {
error = force_reval_path(&nd->path, nd);
if (error)
path_put(&nd->path);
}
if (dentry->d_inode->i_op->put_link)
dentry->d_inode->i_op->put_link(dentry, nd, cookie);
}
return error;
}
/*
* This limits recursive symlink follows to 8, while
* limiting consecutive symlinks to 40.
*
* Without that kind of total limit, nasty chains of consecutive
* symlinks can cause almost arbitrarily long lookups.
*/
static inline int do_follow_link(struct path *path, struct nameidata *nd)
{
int err = -ELOOP;
if (current->link_count >= MAX_NESTED_LINKS)
goto loop;
if (current->total_link_count >= 40)
goto loop;
BUG_ON(nd->depth >= MAX_NESTED_LINKS);
cond_resched();
err = security_inode_follow_link(path->dentry, nd);
if (err)
goto loop;
current->link_count++;
current->total_link_count++;
nd->depth++;
err = __do_follow_link(path, nd);
path_put(path);
current->link_count--;
nd->depth--;
return err;
loop:
path_put_conditional(path, nd);
path_put(&nd->path);
return err;
}
int follow_up(struct path *path)
{
struct vfsmount *parent;
struct dentry *mountpoint;
spin_lock(&vfsmount_lock);
parent = path->mnt->mnt_parent;
if (parent == path->mnt) {
spin_unlock(&vfsmount_lock);
return 0;
}
mntget(parent);
mountpoint = dget(path->mnt->mnt_mountpoint);
spin_unlock(&vfsmount_lock);
dput(path->dentry);
path->dentry = mountpoint;
mntput(path->mnt);
path->mnt = parent;
return 1;
}
/* no need for dcache_lock, as serialization is taken care in
* namespace.c
*/
static int __follow_mount(struct path *path)
{
int res = 0;
while (d_mountpoint(path->dentry)) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
if (res)
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
res = 1;
}
return res;
}
static void follow_mount(struct path *path)
{
while (d_mountpoint(path->dentry)) {
struct vfsmount *mounted = lookup_mnt(path);
if (!mounted)
break;
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
}
}
/* no need for dcache_lock, as serialization is taken care in
* namespace.c
*/
int follow_down(struct path *path)
{
struct vfsmount *mounted;
mounted = lookup_mnt(path);
if (mounted) {
dput(path->dentry);
mntput(path->mnt);
path->mnt = mounted;
path->dentry = dget(mounted->mnt_root);
return 1;
}
return 0;
}
static __always_inline void follow_dotdot(struct nameidata *nd)
{
set_root(nd);
while(1) {
struct vfsmount *parent;
struct dentry *old = nd->path.dentry;
if (nd->path.dentry == nd->root.dentry &&
nd->path.mnt == nd->root.mnt) {
break;
}
spin_lock(&dcache_lock);
if (nd->path.dentry != nd->path.mnt->mnt_root) {
nd->path.dentry = dget(nd->path.dentry->d_parent);
spin_unlock(&dcache_lock);
dput(old);
break;
}
spin_unlock(&dcache_lock);
spin_lock(&vfsmount_lock);
parent = nd->path.mnt->mnt_parent;
if (parent == nd->path.mnt) {
spin_unlock(&vfsmount_lock);
break;
}
mntget(parent);
nd->path.dentry = dget(nd->path.mnt->mnt_mountpoint);
spin_unlock(&vfsmount_lock);
dput(old);
mntput(nd->path.mnt);
nd->path.mnt = parent;
}
follow_mount(&nd->path);
}
/*
* It's more convoluted than I'd like it to be, but... it's still fairly
* small and for now I'd prefer to have fast path as straight as possible.
* It _is_ time-critical.
*/
static int do_lookup(struct nameidata *nd, struct qstr *name,
struct path *path)
{
struct vfsmount *mnt = nd->path.mnt;
struct dentry *dentry, *parent;
struct inode *dir;
/*
* See if the low-level filesystem might want
* to use its own hash..
*/
if (nd->path.dentry->d_op && nd->path.dentry->d_op->d_hash) {
int err = nd->path.dentry->d_op->d_hash(nd->path.dentry, name);
if (err < 0)
return err;
}
dentry = __d_lookup(nd->path.dentry, name);
if (!dentry)
goto need_lookup;
if (dentry->d_op && dentry->d_op->d_revalidate)
goto need_revalidate;
done:
path->mnt = mnt;
path->dentry = dentry;
__follow_mount(path);
return 0;
need_lookup:
parent = nd->path.dentry;
dir = parent->d_inode;
mutex_lock(&dir->i_mutex);
/*
* First re-do the cached lookup just in case it was created
* while we waited for the directory semaphore..
*
* FIXME! This could use version numbering or similar to
* avoid unnecessary cache lookups.
*
* The "dcache_lock" is purely to protect the RCU list walker
* from concurrent renames at this point (we mustn't get false
* negatives from the RCU list walk here, unlike the optimistic
* fast walk).
*
* so doing d_lookup() (with seqlock), instead of lockfree __d_lookup
*/
dentry = d_lookup(parent, name);
if (!dentry) {
struct dentry *new;
/* Don't create child dentry for a dead directory. */
dentry = ERR_PTR(-ENOENT);
if (IS_DEADDIR(dir))
goto out_unlock;
new = d_alloc(parent, name);
dentry = ERR_PTR(-ENOMEM);
if (new) {
dentry = dir->i_op->lookup(dir, new, nd);
if (dentry)
dput(new);
else
dentry = new;
}
out_unlock:
mutex_unlock(&dir->i_mutex);
if (IS_ERR(dentry))
goto fail;
goto done;
}
/*
* Uhhuh! Nasty case: the cache was re-populated while
* we waited on the semaphore. Need to revalidate.
*/
mutex_unlock(&dir->i_mutex);
if (dentry->d_op && dentry->d_op->d_revalidate) {
dentry = do_revalidate(dentry, nd);
if (!dentry)
dentry = ERR_PTR(-ENOENT);
}
if (IS_ERR(dentry))
goto fail;
goto done;
need_revalidate:
dentry = do_revalidate(dentry, nd);
if (!dentry)
goto need_lookup;
if (IS_ERR(dentry))
goto fail;
goto done;
fail:
return PTR_ERR(dentry);
}
/*
* Name resolution.
* This is the basic name resolution function, turning a pathname into
* the final dentry. We expect 'base' to be positive and a directory.
*
* Returns 0 and nd will have valid dentry and mnt on success.
* Returns error and drops reference to input namei data on failure.
*/
static int link_path_walk(const char *name, struct nameidata *nd)
{
struct path next;
struct inode *inode;
int err;
unsigned int lookup_flags = nd->flags;
while (*name=='/')
name++;
if (!*name)
goto return_reval;
inode = nd->path.dentry->d_inode;
if (nd->depth)
lookup_flags = LOOKUP_FOLLOW | (nd->flags & LOOKUP_CONTINUE);
/* At this point we know we have a real path component. */
for(;;) {
unsigned long hash;
struct qstr this;
unsigned int c;
nd->flags |= LOOKUP_CONTINUE;
err = exec_permission(inode);
if (err)
break;
this.name = name;
c = *(const unsigned char *)name;
hash = init_name_hash();
do {
name++;
hash = partial_name_hash(c, hash);
c = *(const unsigned char *)name;
} while (c && (c != '/'));
this.len = name - (const char *) this.name;
this.hash = end_name_hash(hash);
/* remove trailing slashes? */
if (!c)
goto last_component;
while (*++name == '/');
if (!*name)
goto last_with_slashes;
/*
* "." and ".." are special - ".." especially so because it has
* to be able to know about the current root directory and
* parent relationships.
*/
if (this.name[0] == '.') switch (this.len) {
default:
break;
case 2:
if (this.name[1] != '.')
break;
follow_dotdot(nd);
inode = nd->path.dentry->d_inode;
/* fallthrough */
case 1:
continue;
}
/* This does the actual lookups.. */
err = do_lookup(nd, &this, &next);
if (err)
break;
err = -ENOENT;
inode = next.dentry->d_inode;
if (!inode)
goto out_dput;
if (inode->i_op->follow_link) {
err = do_follow_link(&next, nd);
if (err)
goto return_err;
err = -ENOENT;
inode = nd->path.dentry->d_inode;
if (!inode)
break;
} else
path_to_nameidata(&next, nd);
err = -ENOTDIR;
if (!inode->i_op->lookup)
break;
continue;
/* here ends the main loop */
last_with_slashes:
lookup_flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY;
last_component:
/* Clear LOOKUP_CONTINUE iff it was previously unset */
nd->flags &= lookup_flags | ~LOOKUP_CONTINUE;
if (lookup_flags & LOOKUP_PARENT)
goto lookup_parent;
if (this.name[0] == '.') switch (this.len) {
default:
break;
case 2:
if (this.name[1] != '.')
break;
follow_dotdot(nd);
inode = nd->path.dentry->d_inode;
/* fallthrough */
case 1:
goto return_reval;
}
err = do_lookup(nd, &this, &next);
if (err)
break;
inode = next.dentry->d_inode;
if ((lookup_flags & LOOKUP_FOLLOW)
&& inode && inode->i_op->follow_link) {
err = do_follow_link(&next, nd);
if (err)
goto return_err;
inode = nd->path.dentry->d_inode;
} else
path_to_nameidata(&next, nd);
err = -ENOENT;
if (!inode)
break;
if (lookup_flags & LOOKUP_DIRECTORY) {
err = -ENOTDIR;
if (!inode->i_op->lookup)
break;
}
goto return_base;
lookup_parent:
nd->last = this;
nd->last_type = LAST_NORM;
if (this.name[0] != '.')
goto return_base;
if (this.len == 1)
nd->last_type = LAST_DOT;
else if (this.len == 2 && this.name[1] == '.')
nd->last_type = LAST_DOTDOT;
else
goto return_base;
return_reval:
/*
* We bypassed the ordinary revalidation routines.
* We may need to check the cached dentry for staleness.
*/
if (nd->path.dentry && nd->path.dentry->d_sb &&
(nd->path.dentry->d_sb->s_type->fs_flags & FS_REVAL_DOT)) {
err = -ESTALE;
/* Note: we do not d_invalidate() */
if (!nd->path.dentry->d_op->d_revalidate(
nd->path.dentry, nd))
break;
}
return_base:
return 0;
out_dput:
path_put_conditional(&next, nd);
break;
}
path_put(&nd->path);
return_err:
return err;
}
static int path_walk(const char *name, struct nameidata *nd)
{
struct path save = nd->path;
int result;
current->total_link_count = 0;
/* make sure the stuff we saved doesn't go away */
path_get(&save);
result = link_path_walk(name, nd);
if (result == -ESTALE) {
/* nd->path had been dropped */
current->total_link_count = 0;
nd->path = save;
path_get(&nd->path);
nd->flags |= LOOKUP_REVAL;
result = link_path_walk(name, nd);
}
path_put(&save);
return result;
}
static int path_init(int dfd, const char *name, unsigned int flags, struct nameidata *nd)
{
int retval = 0;
int fput_needed;
struct file *file;
nd->last_type = LAST_ROOT; /* if there are only slashes... */
nd->flags = flags;
nd->depth = 0;
nd->root.mnt = NULL;
if (*name=='/') {
set_root(nd);
nd->path = nd->root;
path_get(&nd->root);
} else if (dfd == AT_FDCWD) {
struct fs_struct *fs = current->fs;
read_lock(&fs->lock);
nd->path = fs->pwd;
path_get(&fs->pwd);
read_unlock(&fs->lock);
} else {
struct dentry *dentry;
file = fget_light(dfd, &fput_needed);
retval = -EBADF;
if (!file)
goto out_fail;
dentry = file->f_path.dentry;
retval = -ENOTDIR;
if (!S_ISDIR(dentry->d_inode->i_mode))
goto fput_fail;
retval = file_permission(file, MAY_EXEC);
if (retval)
goto fput_fail;
nd->path = file->f_path;
path_get(&file->f_path);
fput_light(file, fput_needed);
}
return 0;
fput_fail:
fput_light(file, fput_needed);
out_fail:
return retval;
}
/* Returns 0 and nd will be valid on success; Retuns error, otherwise. */
static int do_path_lookup(int dfd, const char *name,
unsigned int flags, struct nameidata *nd)
{
int retval = path_init(dfd, name, flags, nd);
if (!retval)
retval = path_walk(name, nd);
if (unlikely(!retval && !audit_dummy_context() && nd->path.dentry &&
nd->path.dentry->d_inode))
audit_inode(name, nd->path.dentry);
if (nd->root.mnt) {
path_put(&nd->root);
nd->root.mnt = NULL;
}
return retval;
}
int path_lookup(const char *name, unsigned int flags,
struct nameidata *nd)
{
return do_path_lookup(AT_FDCWD, name, flags, nd);
}
int kern_path(const char *name, unsigned int flags, struct path *path)
{
struct nameidata nd;
int res = do_path_lookup(AT_FDCWD, name, flags, &nd);
if (!res)
*path = nd.path;
return res;
}
/**
* vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair
* @dentry: pointer to dentry of the base directory
* @mnt: pointer to vfs mount of the base directory
* @name: pointer to file name
* @flags: lookup flags
* @nd: pointer to nameidata
*/
int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt,
const char *name, unsigned int flags,
struct nameidata *nd)
{
int retval;
/* same as do_path_lookup */
nd->last_type = LAST_ROOT;
nd->flags = flags;
nd->depth = 0;
nd->path.dentry = dentry;
nd->path.mnt = mnt;
path_get(&nd->path);
nd->root = nd->path;
path_get(&nd->root);
retval = path_walk(name, nd);
if (unlikely(!retval && !audit_dummy_context() && nd->path.dentry &&
nd->path.dentry->d_inode))
audit_inode(name, nd->path.dentry);
path_put(&nd->root);
nd->root.mnt = NULL;
return retval;
}
static struct dentry *__lookup_hash(struct qstr *name,
struct dentry *base, struct nameidata *nd)
{
struct dentry *dentry;
struct inode *inode;
int err;
inode = base->d_inode;
/*
* See if the low-level filesystem might want
* to use its own hash..
*/
if (base->d_op && base->d_op->d_hash) {
err = base->d_op->d_hash(base, name);
dentry = ERR_PTR(err);
if (err < 0)
goto out;
}
dentry = __d_lookup(base, name);
/* lockess __d_lookup may fail due to concurrent d_move()
* in some unrelated directory, so try with d_lookup
*/
if (!dentry)
dentry = d_lookup(base, name);
if (dentry && dentry->d_op && dentry->d_op->d_revalidate)
dentry = do_revalidate(dentry, nd);
if (!dentry) {
struct dentry *new;
/* Don't create child dentry for a dead directory. */
dentry = ERR_PTR(-ENOENT);
if (IS_DEADDIR(inode))
goto out;
new = d_alloc(base, name);
dentry = ERR_PTR(-ENOMEM);
if (!new)
goto out;
dentry = inode->i_op->lookup(inode, new, nd);
if (!dentry)
dentry = new;
else
dput(new);
}
out:
return dentry;
}
/*
* Restricted form of lookup. Doesn't follow links, single-component only,
* needs parent already locked. Doesn't follow mounts.
* SMP-safe.
*/
static struct dentry *lookup_hash(struct nameidata *nd)
{
int err;
err = exec_permission(nd->path.dentry->d_inode);
if (err)
return ERR_PTR(err);
return __lookup_hash(&nd->last, nd->path.dentry, nd);
}
static int __lookup_one_len(const char *name, struct qstr *this,
struct dentry *base, int len)
{
unsigned long hash;
unsigned int c;
this->name = name;
this->len = len;
if (!len)
return -EACCES;
hash = init_name_hash();
while (len--) {
c = *(const unsigned char *)name++;
if (c == '/' || c == '\0')
return -EACCES;
hash = partial_name_hash(c, hash);
}
this->hash = end_name_hash(hash);
return 0;
}
/**
* lookup_one_len - filesystem helper to lookup single pathname component
* @name: pathname component to lookup
* @base: base directory to lookup from
* @len: maximum length @len should be interpreted to
*
* Note that this routine is purely a helper for filesystem usage and should
* not be called by generic code. Also note that by using this function the
* nameidata argument is passed to the filesystem methods and a filesystem
* using this helper needs to be prepared for that.
*/
struct dentry *lookup_one_len(const char *name, struct dentry *base, int len)
{
int err;
struct qstr this;
WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex));
err = __lookup_one_len(name, &this, base, len);
if (err)
return ERR_PTR(err);
err = exec_permission(base->d_inode);
if (err)
return ERR_PTR(err);
return __lookup_hash(&this, base, NULL);
}
int user_path_at(int dfd, const char __user *name, unsigned flags,
struct path *path)
{
struct nameidata nd;
char *tmp = getname(name);
int err = PTR_ERR(tmp);
if (!IS_ERR(tmp)) {
BUG_ON(flags & LOOKUP_PARENT);
err = do_path_lookup(dfd, tmp, flags, &nd);
putname(tmp);
if (!err)
*path = nd.path;
}
return err;
}
static int user_path_parent(int dfd, const char __user *path,
struct nameidata *nd, char **name)
{
char *s = getname(path);
int error;
if (IS_ERR(s))
return PTR_ERR(s);
error = do_path_lookup(dfd, s, LOOKUP_PARENT, nd);
if (error)
putname(s);
else
*name = s;
return error;
}
/*
* It's inline, so penalty for filesystems that don't use sticky bit is
* minimal.
*/
static inline int check_sticky(struct inode *dir, struct inode *inode)
{
uid_t fsuid = current_fsuid();
if (!(dir->i_mode & S_ISVTX))
return 0;
if (inode->i_uid == fsuid)
return 0;
if (dir->i_uid == fsuid)
return 0;
return !capable(CAP_FOWNER);
}
/*
* Check whether we can remove a link victim from directory dir, check
* whether the type of victim is right.
* 1. We can't do it if dir is read-only (done in permission())
* 2. We should have write and exec permissions on dir
* 3. We can't remove anything from append-only dir
* 4. We can't do anything with immutable dir (done in permission())
* 5. If the sticky bit on dir is set we should either
* a. be owner of dir, or
* b. be owner of victim, or
* c. have CAP_FOWNER capability
* 6. If the victim is append-only or immutable we can't do antyhing with
* links pointing to it.
* 7. If we were asked to remove a directory and victim isn't one - ENOTDIR.
* 8. If we were asked to remove a non-directory and victim isn't one - EISDIR.
* 9. We can't remove a root or mountpoint.
* 10. We don't allow removal of NFS sillyrenamed files; it's handled by
* nfs_async_unlink().
*/
static int may_delete(struct inode *dir,struct dentry *victim,int isdir)
{
int error;
if (!victim->d_inode)
return -ENOENT;
BUG_ON(victim->d_parent->d_inode != dir);
audit_inode_child(victim->d_name.name, victim, dir);
error = inode_permission(dir, MAY_WRITE | MAY_EXEC);
if (error)
return error;
if (IS_APPEND(dir))
return -EPERM;
if (check_sticky(dir, victim->d_inode)||IS_APPEND(victim->d_inode)||
IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode))
return -EPERM;
if (isdir) {
if (!S_ISDIR(victim->d_inode->i_mode))
return -ENOTDIR;
if (IS_ROOT(victim))
return -EBUSY;
} else if (S_ISDIR(victim->d_inode->i_mode))
return -EISDIR;
if (IS_DEADDIR(dir))
return -ENOENT;
if (victim->d_flags & DCACHE_NFSFS_RENAMED)
return -EBUSY;
return 0;
}
/* Check whether we can create an object with dentry child in directory
* dir.
* 1. We can't do it if child already exists (open has special treatment for
* this case, but since we are inlined it's OK)
* 2. We can't do it if dir is read-only (done in permission())
* 3. We should have write and exec permissions on dir
* 4. We can't do it if dir is immutable (done in permission())
*/
static inline int may_create(struct inode *dir, struct dentry *child)
{
if (child->d_inode)
return -EEXIST;
if (IS_DEADDIR(dir))
return -ENOENT;
return inode_permission(dir, MAY_WRITE | MAY_EXEC);
}
/*
* O_DIRECTORY translates into forcing a directory lookup.
*/
static inline int lookup_flags(unsigned int f)
{
unsigned long retval = LOOKUP_FOLLOW;
if (f & O_NOFOLLOW)
retval &= ~LOOKUP_FOLLOW;
if (f & O_DIRECTORY)
retval |= LOOKUP_DIRECTORY;
return retval;
}
/*
* p1 and p2 should be directories on the same fs.
*/
struct dentry *lock_rename(struct dentry *p1, struct dentry *p2)
{
struct dentry *p;
if (p1 == p2) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
return NULL;
}
mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
p = d_ancestor(p2, p1);
if (p) {
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
p = d_ancestor(p1, p2);
if (p) {
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
return p;
}
mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT);
mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD);
return NULL;
}
void unlock_rename(struct dentry *p1, struct dentry *p2)
{
mutex_unlock(&p1->d_inode->i_mutex);
if (p1 != p2) {
mutex_unlock(&p2->d_inode->i_mutex);
mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex);
}
}
int vfs_create(struct inode *dir, struct dentry *dentry, int mode,
struct nameidata *nd)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->create)
return -EACCES; /* shouldn't it be ENOSYS? */
mode &= S_IALLUGO;
mode |= S_IFREG;
error = security_inode_create(dir, dentry, mode);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->create(dir, dentry, mode, nd);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
int may_open(struct path *path, int acc_mode, int flag)
{
struct dentry *dentry = path->dentry;
struct inode *inode = dentry->d_inode;
int error;
if (!inode)
return -ENOENT;
switch (inode->i_mode & S_IFMT) {
case S_IFLNK:
return -ELOOP;
case S_IFDIR:
if (acc_mode & MAY_WRITE)
return -EISDIR;
break;
case S_IFBLK:
case S_IFCHR:
if (path->mnt->mnt_flags & MNT_NODEV)
return -EACCES;
/*FALLTHRU*/
case S_IFIFO:
case S_IFSOCK:
flag &= ~O_TRUNC;
break;
}
error = inode_permission(inode, acc_mode);
if (error)
return error;
/*
* An append-only file must be opened in append mode for writing.
*/
if (IS_APPEND(inode)) {
if ((flag & FMODE_WRITE) && !(flag & O_APPEND))
return -EPERM;
if (flag & O_TRUNC)
return -EPERM;
}
/* O_NOATIME can only be set by the owner or superuser */
if (flag & O_NOATIME && !is_owner_or_cap(inode))
return -EPERM;
/*
* Ensure there are no outstanding leases on the file.
*/
return break_lease(inode, flag);
}
static int handle_truncate(struct path *path)
{
struct inode *inode = path->dentry->d_inode;
int error = get_write_access(inode);
if (error)
return error;
/*
* Refuse to truncate files with mandatory locks held on them.
*/
error = locks_verify_locked(inode);
if (!error)
error = security_path_truncate(path, 0,
ATTR_MTIME|ATTR_CTIME|ATTR_OPEN);
if (!error) {
error = do_truncate(path->dentry, 0,
ATTR_MTIME|ATTR_CTIME|ATTR_OPEN,
NULL);
}
put_write_access(inode);
return error;
}
/*
* Be careful about ever adding any more callers of this
* function. Its flags must be in the namei format, not
* what get passed to sys_open().
*/
static int __open_namei_create(struct nameidata *nd, struct path *path,
int flag, int mode)
{
int error;
struct dentry *dir = nd->path.dentry;
if (!IS_POSIXACL(dir->d_inode))
mode &= ~current_umask();
error = security_path_mknod(&nd->path, path->dentry, mode, 0);
if (error)
goto out_unlock;
error = vfs_create(dir->d_inode, path->dentry, mode, nd);
out_unlock:
mutex_unlock(&dir->d_inode->i_mutex);
dput(nd->path.dentry);
nd->path.dentry = path->dentry;
if (error)
return error;
/* Don't check for write permission, don't truncate */
return may_open(&nd->path, 0, flag & ~O_TRUNC);
}
/*
* Note that while the flag value (low two bits) for sys_open means:
* 00 - read-only
* 01 - write-only
* 10 - read-write
* 11 - special
* it is changed into
* 00 - no permissions needed
* 01 - read-permission
* 10 - write-permission
* 11 - read-write
* for the internal routines (ie open_namei()/follow_link() etc)
* This is more logical, and also allows the 00 "no perm needed"
* to be used for symlinks (where the permissions are checked
* later).
*
*/
static inline int open_to_namei_flags(int flag)
{
if ((flag+1) & O_ACCMODE)
flag++;
return flag;
}
static int open_will_truncate(int flag, struct inode *inode)
{
/*
* We'll never write to the fs underlying
* a device file.
*/
if (special_file(inode->i_mode))
return 0;
return (flag & O_TRUNC);
}
/*
* Note that the low bits of the passed in "open_flag"
* are not the same as in the local variable "flag". See
* open_to_namei_flags() for more details.
*/
struct file *do_filp_open(int dfd, const char *pathname,
int open_flag, int mode, int acc_mode)
{
struct file *filp;
struct nameidata nd;
int error;
struct path path, save;
struct dentry *dir;
int count = 0;
int will_truncate;
int flag = open_to_namei_flags(open_flag);
/*
* O_SYNC is implemented as __O_SYNC|O_DSYNC. As many places only
* check for O_DSYNC if the need any syncing at all we enforce it's
* always set instead of having to deal with possibly weird behaviour
* for malicious applications setting only __O_SYNC.
*/
if (open_flag & __O_SYNC)
open_flag |= O_DSYNC;
if (!acc_mode)
acc_mode = MAY_OPEN | ACC_MODE(flag);
/* O_TRUNC implies we need access checks for write permissions */
if (flag & O_TRUNC)
acc_mode |= MAY_WRITE;
/* Allow the LSM permission hook to distinguish append
access from general write access. */
if (flag & O_APPEND)
acc_mode |= MAY_APPEND;
/*
* The simplest case - just a plain lookup.
*/
if (!(flag & O_CREAT)) {
filp = get_empty_filp();
if (filp == NULL)
return ERR_PTR(-ENFILE);
nd.intent.open.file = filp;
filp->f_flags = open_flag;
nd.intent.open.flags = flag;
nd.intent.open.create_mode = 0;
error = do_path_lookup(dfd, pathname,
lookup_flags(flag)|LOOKUP_OPEN, &nd);
if (IS_ERR(nd.intent.open.file)) {
if (error == 0) {
error = PTR_ERR(nd.intent.open.file);
path_put(&nd.path);
}
} else if (error)
release_open_intent(&nd);
if (error)
return ERR_PTR(error);
goto ok;
}
/*
* Create - we need to know the parent.
*/
error = path_init(dfd, pathname, LOOKUP_PARENT, &nd);
if (error)
return ERR_PTR(error);
error = path_walk(pathname, &nd);
if (error) {
if (nd.root.mnt)
path_put(&nd.root);
return ERR_PTR(error);
}
if (unlikely(!audit_dummy_context()))
audit_inode(pathname, nd.path.dentry);
/*
* We have the parent and last component. First of all, check
* that we are not asked to creat(2) an obvious directory - that
* will not do.
*/
error = -EISDIR;
if (nd.last_type != LAST_NORM || nd.last.name[nd.last.len])
goto exit_parent;
error = -ENFILE;
filp = get_empty_filp();
if (filp == NULL)
goto exit_parent;
nd.intent.open.file = filp;
filp->f_flags = open_flag;
nd.intent.open.flags = flag;
nd.intent.open.create_mode = mode;
dir = nd.path.dentry;
nd.flags &= ~LOOKUP_PARENT;
nd.flags |= LOOKUP_CREATE | LOOKUP_OPEN;
if (flag & O_EXCL)
nd.flags |= LOOKUP_EXCL;
mutex_lock(&dir->d_inode->i_mutex);
path.dentry = lookup_hash(&nd);
path.mnt = nd.path.mnt;
do_last:
error = PTR_ERR(path.dentry);
if (IS_ERR(path.dentry)) {
mutex_unlock(&dir->d_inode->i_mutex);
goto exit;
}
if (IS_ERR(nd.intent.open.file)) {
error = PTR_ERR(nd.intent.open.file);
goto exit_mutex_unlock;
}
/* Negative dentry, just create the file */
if (!path.dentry->d_inode) {
/*
* This write is needed to ensure that a
* ro->rw transition does not occur between
* the time when the file is created and when
* a permanent write count is taken through
* the 'struct file' in nameidata_to_filp().
*/
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit_mutex_unlock;
error = __open_namei_create(&nd, &path, flag, mode);
if (error) {
mnt_drop_write(nd.path.mnt);
goto exit;
}
filp = nameidata_to_filp(&nd);
mnt_drop_write(nd.path.mnt);
if (nd.root.mnt)
path_put(&nd.root);
if (!IS_ERR(filp)) {
error = ima_path_check(&filp->f_path, filp->f_mode &
(MAY_READ | MAY_WRITE | MAY_EXEC));
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
return filp;
}
/*
* It already exists.
*/
mutex_unlock(&dir->d_inode->i_mutex);
audit_inode(pathname, path.dentry);
error = -EEXIST;
if (flag & O_EXCL)
goto exit_dput;
if (__follow_mount(&path)) {
error = -ELOOP;
if (flag & O_NOFOLLOW)
goto exit_dput;
}
error = -ENOENT;
if (!path.dentry->d_inode)
goto exit_dput;
if (path.dentry->d_inode->i_op->follow_link)
goto do_link;
path_to_nameidata(&path, &nd);
error = -EISDIR;
if (S_ISDIR(path.dentry->d_inode->i_mode))
goto exit;
ok:
/*
* Consider:
* 1. may_open() truncates a file
* 2. a rw->ro mount transition occurs
* 3. nameidata_to_filp() fails due to
* the ro mount.
* That would be inconsistent, and should
* be avoided. Taking this mnt write here
* ensures that (2) can not occur.
*/
will_truncate = open_will_truncate(flag, nd.path.dentry->d_inode);
if (will_truncate) {
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit;
}
error = may_open(&nd.path, acc_mode, flag);
if (error) {
if (will_truncate)
mnt_drop_write(nd.path.mnt);
goto exit;
}
filp = nameidata_to_filp(&nd);
if (!IS_ERR(filp)) {
error = ima_path_check(&filp->f_path, filp->f_mode &
(MAY_READ | MAY_WRITE | MAY_EXEC));
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
if (!IS_ERR(filp)) {
if (acc_mode & MAY_WRITE)
vfs_dq_init(nd.path.dentry->d_inode);
if (will_truncate) {
error = handle_truncate(&nd.path);
if (error) {
fput(filp);
filp = ERR_PTR(error);
}
}
}
/*
* It is now safe to drop the mnt write
* because the filp has had a write taken
* on its behalf.
*/
if (will_truncate)
mnt_drop_write(nd.path.mnt);
if (nd.root.mnt)
path_put(&nd.root);
return filp;
exit_mutex_unlock:
mutex_unlock(&dir->d_inode->i_mutex);
exit_dput:
path_put_conditional(&path, &nd);
exit:
if (!IS_ERR(nd.intent.open.file))
release_open_intent(&nd);
exit_parent:
if (nd.root.mnt)
path_put(&nd.root);
path_put(&nd.path);
return ERR_PTR(error);
do_link:
error = -ELOOP;
if (flag & O_NOFOLLOW)
goto exit_dput;
/*
* This is subtle. Instead of calling do_follow_link() we do the
* thing by hands. The reason is that this way we have zero link_count
* and path_walk() (called from ->follow_link) honoring LOOKUP_PARENT.
* After that we have the parent and last component, i.e.
* we are in the same situation as after the first path_walk().
* Well, almost - if the last component is normal we get its copy
* stored in nd->last.name and we will have to putname() it when we
* are done. Procfs-like symlinks just set LAST_BIND.
*/
nd.flags |= LOOKUP_PARENT;
error = security_inode_follow_link(path.dentry, &nd);
if (error)
goto exit_dput;
save = nd.path;
path_get(&save);
error = __do_follow_link(&path, &nd);
if (error == -ESTALE) {
/* nd.path had been dropped */
nd.path = save;
path_get(&nd.path);
nd.flags |= LOOKUP_REVAL;
error = __do_follow_link(&path, &nd);
}
path_put(&save);
path_put(&path);
if (error) {
/* Does someone understand code flow here? Or it is only
* me so stupid? Anathema to whoever designed this non-sense
* with "intent.open".
*/
release_open_intent(&nd);
if (nd.root.mnt)
path_put(&nd.root);
return ERR_PTR(error);
}
nd.flags &= ~LOOKUP_PARENT;
if (nd.last_type == LAST_BIND)
goto ok;
error = -EISDIR;
if (nd.last_type != LAST_NORM)
goto exit;
if (nd.last.name[nd.last.len]) {
__putname(nd.last.name);
goto exit;
}
error = -ELOOP;
if (count++==32) {
__putname(nd.last.name);
goto exit;
}
dir = nd.path.dentry;
mutex_lock(&dir->d_inode->i_mutex);
path.dentry = lookup_hash(&nd);
path.mnt = nd.path.mnt;
__putname(nd.last.name);
goto do_last;
}
/**
* filp_open - open file and return file pointer
*
* @filename: path to open
* @flags: open flags as per the open(2) second argument
* @mode: mode for the new file if O_CREAT is set, else ignored
*
* This is the helper to open a file from kernelspace if you really
* have to. But in generally you should not do this, so please move
* along, nothing to see here..
*/
struct file *filp_open(const char *filename, int flags, int mode)
{
return do_filp_open(AT_FDCWD, filename, flags, mode, 0);
}
EXPORT_SYMBOL(filp_open);
/**
* lookup_create - lookup a dentry, creating it if it doesn't exist
* @nd: nameidata info
* @is_dir: directory flag
*
* Simple function to lookup and return a dentry and create it
* if it doesn't exist. Is SMP-safe.
*
* Returns with nd->path.dentry->d_inode->i_mutex locked.
*/
struct dentry *lookup_create(struct nameidata *nd, int is_dir)
{
struct dentry *dentry = ERR_PTR(-EEXIST);
mutex_lock_nested(&nd->path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
/*
* Yucky last component or no last component at all?
* (foo/., foo/.., /////)
*/
if (nd->last_type != LAST_NORM)
goto fail;
nd->flags &= ~LOOKUP_PARENT;
nd->flags |= LOOKUP_CREATE | LOOKUP_EXCL;
nd->intent.open.flags = O_EXCL;
/*
* Do the final lookup.
*/
dentry = lookup_hash(nd);
if (IS_ERR(dentry))
goto fail;
if (dentry->d_inode)
goto eexist;
/*
* Special case - lookup gave negative, but... we had foo/bar/
* From the vfs_mknod() POV we just have a negative dentry -
* all is fine. Let's be bastards - you had / on the end, you've
* been asking for (non-existent) directory. -ENOENT for you.
*/
if (unlikely(!is_dir && nd->last.name[nd->last.len])) {
dput(dentry);
dentry = ERR_PTR(-ENOENT);
}
return dentry;
eexist:
dput(dentry);
dentry = ERR_PTR(-EEXIST);
fail:
return dentry;
}
EXPORT_SYMBOL_GPL(lookup_create);
int vfs_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
{
int error = may_create(dir, dentry);
if (error)
return error;
if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD))
return -EPERM;
if (!dir->i_op->mknod)
return -EPERM;
error = devcgroup_inode_mknod(mode, dev);
if (error)
return error;
error = security_inode_mknod(dir, dentry, mode, dev);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->mknod(dir, dentry, mode, dev);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
static int may_mknod(mode_t mode)
{
switch (mode & S_IFMT) {
case S_IFREG:
case S_IFCHR:
case S_IFBLK:
case S_IFIFO:
case S_IFSOCK:
case 0: /* zero mode translates to S_IFREG */
return 0;
case S_IFDIR:
return -EPERM;
default:
return -EINVAL;
}
}
SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, int, mode,
unsigned, dev)
{
int error;
char *tmp;
struct dentry *dentry;
struct nameidata nd;
if (S_ISDIR(mode))
return -EPERM;
error = user_path_parent(dfd, filename, &nd, &tmp);
if (error)
return error;
dentry = lookup_create(&nd, 0);
if (IS_ERR(dentry)) {
error = PTR_ERR(dentry);
goto out_unlock;
}
if (!IS_POSIXACL(nd.path.dentry->d_inode))
mode &= ~current_umask();
error = may_mknod(mode);
if (error)
goto out_dput;
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_mknod(&nd.path, dentry, mode, dev);
if (error)
goto out_drop_write;
switch (mode & S_IFMT) {
case 0: case S_IFREG:
error = vfs_create(nd.path.dentry->d_inode,dentry,mode,&nd);
break;
case S_IFCHR: case S_IFBLK:
error = vfs_mknod(nd.path.dentry->d_inode,dentry,mode,
new_decode_dev(dev));
break;
case S_IFIFO: case S_IFSOCK:
error = vfs_mknod(nd.path.dentry->d_inode,dentry,mode,0);
break;
}
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
putname(tmp);
return error;
}
SYSCALL_DEFINE3(mknod, const char __user *, filename, int, mode, unsigned, dev)
{
return sys_mknodat(AT_FDCWD, filename, mode, dev);
}
int vfs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->mkdir)
return -EPERM;
mode &= (S_IRWXUGO|S_ISVTX);
error = security_inode_mkdir(dir, dentry, mode);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->mkdir(dir, dentry, mode);
if (!error)
fsnotify_mkdir(dir, dentry);
return error;
}
SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, int, mode)
{
int error = 0;
char * tmp;
struct dentry *dentry;
struct nameidata nd;
error = user_path_parent(dfd, pathname, &nd, &tmp);
if (error)
goto out_err;
dentry = lookup_create(&nd, 1);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
if (!IS_POSIXACL(nd.path.dentry->d_inode))
mode &= ~current_umask();
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_mkdir(&nd.path, dentry, mode);
if (error)
goto out_drop_write;
error = vfs_mkdir(nd.path.dentry->d_inode, dentry, mode);
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
putname(tmp);
out_err:
return error;
}
SYSCALL_DEFINE2(mkdir, const char __user *, pathname, int, mode)
{
return sys_mkdirat(AT_FDCWD, pathname, mode);
}
/*
* We try to drop the dentry early: we should have
* a usage count of 2 if we're the only user of this
* dentry, and if that is true (possibly after pruning
* the dcache), then we drop the dentry now.
*
* A low-level filesystem can, if it choses, legally
* do a
*
* if (!d_unhashed(dentry))
* return -EBUSY;
*
* if it cannot handle the case of removing a directory
* that is still in use by something else..
*/
void dentry_unhash(struct dentry *dentry)
{
dget(dentry);
shrink_dcache_parent(dentry);
spin_lock(&dcache_lock);
spin_lock(&dentry->d_lock);
if (atomic_read(&dentry->d_count) == 2)
__d_drop(dentry);
spin_unlock(&dentry->d_lock);
spin_unlock(&dcache_lock);
}
int vfs_rmdir(struct inode *dir, struct dentry *dentry)
{
int error = may_delete(dir, dentry, 1);
if (error)
return error;
if (!dir->i_op->rmdir)
return -EPERM;
vfs_dq_init(dir);
mutex_lock(&dentry->d_inode->i_mutex);
dentry_unhash(dentry);
if (d_mountpoint(dentry))
error = -EBUSY;
else {
error = security_inode_rmdir(dir, dentry);
if (!error) {
error = dir->i_op->rmdir(dir, dentry);
if (!error)
dentry->d_inode->i_flags |= S_DEAD;
}
}
mutex_unlock(&dentry->d_inode->i_mutex);
if (!error) {
d_delete(dentry);
}
dput(dentry);
return error;
}
static long do_rmdir(int dfd, const char __user *pathname)
{
int error = 0;
char * name;
struct dentry *dentry;
struct nameidata nd;
error = user_path_parent(dfd, pathname, &nd, &name);
if (error)
return error;
switch(nd.last_type) {
case LAST_DOTDOT:
error = -ENOTEMPTY;
goto exit1;
case LAST_DOT:
error = -EINVAL;
goto exit1;
case LAST_ROOT:
error = -EBUSY;
goto exit1;
}
nd.flags &= ~LOOKUP_PARENT;
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto exit2;
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit3;
error = security_path_rmdir(&nd.path, dentry);
if (error)
goto exit4;
error = vfs_rmdir(nd.path.dentry->d_inode, dentry);
exit4:
mnt_drop_write(nd.path.mnt);
exit3:
dput(dentry);
exit2:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
exit1:
path_put(&nd.path);
putname(name);
return error;
}
SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
{
return do_rmdir(AT_FDCWD, pathname);
}
int vfs_unlink(struct inode *dir, struct dentry *dentry)
{
int error = may_delete(dir, dentry, 0);
if (error)
return error;
if (!dir->i_op->unlink)
return -EPERM;
vfs_dq_init(dir);
mutex_lock(&dentry->d_inode->i_mutex);
if (d_mountpoint(dentry))
error = -EBUSY;
else {
error = security_inode_unlink(dir, dentry);
if (!error)
error = dir->i_op->unlink(dir, dentry);
}
mutex_unlock(&dentry->d_inode->i_mutex);
/* We don't d_delete() NFS sillyrenamed files--they still exist. */
if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) {
fsnotify_link_count(dentry->d_inode);
d_delete(dentry);
}
return error;
}
/*
* Make sure that the actual truncation of the file will occur outside its
* directory's i_mutex. Truncate can take a long time if there is a lot of
* writeout happening, and we don't want to prevent access to the directory
* while waiting on the I/O.
*/
static long do_unlinkat(int dfd, const char __user *pathname)
{
int error;
char *name;
struct dentry *dentry;
struct nameidata nd;
struct inode *inode = NULL;
error = user_path_parent(dfd, pathname, &nd, &name);
if (error)
return error;
error = -EISDIR;
if (nd.last_type != LAST_NORM)
goto exit1;
nd.flags &= ~LOOKUP_PARENT;
mutex_lock_nested(&nd.path.dentry->d_inode->i_mutex, I_MUTEX_PARENT);
dentry = lookup_hash(&nd);
error = PTR_ERR(dentry);
if (!IS_ERR(dentry)) {
/* Why not before? Because we want correct error value */
if (nd.last.name[nd.last.len])
goto slashes;
inode = dentry->d_inode;
if (inode)
atomic_inc(&inode->i_count);
error = mnt_want_write(nd.path.mnt);
if (error)
goto exit2;
error = security_path_unlink(&nd.path, dentry);
if (error)
goto exit3;
error = vfs_unlink(nd.path.dentry->d_inode, dentry);
exit3:
mnt_drop_write(nd.path.mnt);
exit2:
dput(dentry);
}
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
if (inode)
iput(inode); /* truncate the inode here */
exit1:
path_put(&nd.path);
putname(name);
return error;
slashes:
error = !dentry->d_inode ? -ENOENT :
S_ISDIR(dentry->d_inode->i_mode) ? -EISDIR : -ENOTDIR;
goto exit2;
}
SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag)
{
if ((flag & ~AT_REMOVEDIR) != 0)
return -EINVAL;
if (flag & AT_REMOVEDIR)
return do_rmdir(dfd, pathname);
return do_unlinkat(dfd, pathname);
}
SYSCALL_DEFINE1(unlink, const char __user *, pathname)
{
return do_unlinkat(AT_FDCWD, pathname);
}
int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname)
{
int error = may_create(dir, dentry);
if (error)
return error;
if (!dir->i_op->symlink)
return -EPERM;
error = security_inode_symlink(dir, dentry, oldname);
if (error)
return error;
vfs_dq_init(dir);
error = dir->i_op->symlink(dir, dentry, oldname);
if (!error)
fsnotify_create(dir, dentry);
return error;
}
SYSCALL_DEFINE3(symlinkat, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
int error;
char *from;
char *to;
struct dentry *dentry;
struct nameidata nd;
from = getname(oldname);
if (IS_ERR(from))
return PTR_ERR(from);
error = user_path_parent(newdfd, newname, &nd, &to);
if (error)
goto out_putname;
dentry = lookup_create(&nd, 0);
error = PTR_ERR(dentry);
if (IS_ERR(dentry))
goto out_unlock;
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_symlink(&nd.path, dentry, from);
if (error)
goto out_drop_write;
error = vfs_symlink(nd.path.dentry->d_inode, dentry, from);
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
path_put(&nd.path);
putname(to);
out_putname:
putname(from);
return error;
}
SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname)
{
return sys_symlinkat(oldname, AT_FDCWD, newname);
}
int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
{
struct inode *inode = old_dentry->d_inode;
int error;
if (!inode)
return -ENOENT;
error = may_create(dir, new_dentry);
if (error)
return error;
if (dir->i_sb != inode->i_sb)
return -EXDEV;
/*
* A link to an append-only or immutable file cannot be created.
*/
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
if (!dir->i_op->link)
return -EPERM;
if (S_ISDIR(inode->i_mode))
return -EPERM;
error = security_inode_link(old_dentry, dir, new_dentry);
if (error)
return error;
mutex_lock(&inode->i_mutex);
vfs_dq_init(dir);
error = dir->i_op->link(old_dentry, dir, new_dentry);
mutex_unlock(&inode->i_mutex);
if (!error)
fsnotify_link(dir, inode, new_dentry);
return error;
}
/*
* Hardlinks are often used in delicate situations. We avoid
* security-related surprises by not following symlinks on the
* newname. --KAB
*
* We don't follow them on the oldname either to be compatible
* with linux 2.0, and to avoid hard-linking to directories
* and other special files. --ADM
*/
SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname, int, flags)
{
struct dentry *new_dentry;
struct nameidata nd;
struct path old_path;
int error;
char *to;
if ((flags & ~AT_SYMLINK_FOLLOW) != 0)
return -EINVAL;
error = user_path_at(olddfd, oldname,
flags & AT_SYMLINK_FOLLOW ? LOOKUP_FOLLOW : 0,
&old_path);
if (error)
return error;
error = user_path_parent(newdfd, newname, &nd, &to);
if (error)
goto out;
error = -EXDEV;
if (old_path.mnt != nd.path.mnt)
goto out_release;
new_dentry = lookup_create(&nd, 0);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto out_unlock;
error = mnt_want_write(nd.path.mnt);
if (error)
goto out_dput;
error = security_path_link(old_path.dentry, &nd.path, new_dentry);
if (error)
goto out_drop_write;
error = vfs_link(old_path.dentry, nd.path.dentry->d_inode, new_dentry);
out_drop_write:
mnt_drop_write(nd.path.mnt);
out_dput:
dput(new_dentry);
out_unlock:
mutex_unlock(&nd.path.dentry->d_inode->i_mutex);
out_release:
path_put(&nd.path);
putname(to);
out:
path_put(&old_path);
return error;
}
SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname)
{
return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0);
}
/*
* The worst of all namespace operations - renaming directory. "Perverted"
* doesn't even start to describe it. Somebody in UCB had a heck of a trip...
* Problems:
* a) we can get into loop creation. Check is done in is_subdir().
* b) race potential - two innocent renames can create a loop together.
* That's where 4.4 screws up. Current fix: serialization on
* sb->s_vfs_rename_mutex. We might be more accurate, but that's another
* story.
* c) we have to lock _three_ objects - parents and victim (if it exists).
* And that - after we got ->i_mutex on parents (until then we don't know
* whether the target exists). Solution: try to be smart with locking
* order for inodes. We rely on the fact that tree topology may change
* only under ->s_vfs_rename_mutex _and_ that parent of the object we
* move will be locked. Thus we can rank directories by the tree
* (ancestors first) and rank all non-directories after them.
* That works since everybody except rename does "lock parent, lookup,
* lock child" and rename is under ->s_vfs_rename_mutex.
* HOWEVER, it relies on the assumption that any object with ->lookup()
* has no more than 1 dentry. If "hybrid" objects will ever appear,
* we'd better make sure that there's no link(2) for them.
* d) some filesystems don't support opened-but-unlinked directories,
* either because of layout or because they are not ready to deal with
* all cases correctly. The latter will be fixed (taking this sort of
* stuff into VFS), but the former is not going away. Solution: the same
* trick as in rmdir().
* e) conversion from fhandle to dentry may come in the wrong moment - when
* we are removing the target. Solution: we will have to grab ->i_mutex
* in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on
* ->i_mutex on parents, which works but leads to some truely excessive
* locking].
*/
static int vfs_rename_dir(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int error = 0;
struct inode *target;
/*
* If we are going to change the parent - check write permissions,
* we'll need to flip '..'.
*/
if (new_dir != old_dir) {
error = inode_permission(old_dentry->d_inode, MAY_WRITE);
if (error)
return error;
}
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
return error;
target = new_dentry->d_inode;
if (target) {
mutex_lock(&target->i_mutex);
dentry_unhash(new_dentry);
}
if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
error = -EBUSY;
else
error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
if (target) {
if (!error)
target->i_flags |= S_DEAD;
mutex_unlock(&target->i_mutex);
if (d_unhashed(new_dentry))
d_rehash(new_dentry);
dput(new_dentry);
}
if (!error)
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
d_move(old_dentry,new_dentry);
return error;
}
static int vfs_rename_other(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
struct inode *target;
int error;
error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry);
if (error)
return error;
dget(new_dentry);
target = new_dentry->d_inode;
if (target)
mutex_lock(&target->i_mutex);
if (d_mountpoint(old_dentry)||d_mountpoint(new_dentry))
error = -EBUSY;
else
error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry);
if (!error) {
if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE))
d_move(old_dentry, new_dentry);
}
if (target)
mutex_unlock(&target->i_mutex);
dput(new_dentry);
return error;
}
int vfs_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry)
{
int error;
int is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
const char *old_name;
if (old_dentry->d_inode == new_dentry->d_inode)
return 0;
error = may_delete(old_dir, old_dentry, is_dir);
if (error)
return error;
if (!new_dentry->d_inode)
error = may_create(new_dir, new_dentry);
else
error = may_delete(new_dir, new_dentry, is_dir);
if (error)
return error;
if (!old_dir->i_op->rename)
return -EPERM;
vfs_dq_init(old_dir);
vfs_dq_init(new_dir);
old_name = fsnotify_oldname_init(old_dentry->d_name.name);
if (is_dir)
error = vfs_rename_dir(old_dir,old_dentry,new_dir,new_dentry);
else
error = vfs_rename_other(old_dir,old_dentry,new_dir,new_dentry);
if (!error) {
const char *new_name = old_dentry->d_name.name;
fsnotify_move(old_dir, new_dir, old_name, new_name, is_dir,
new_dentry->d_inode, old_dentry);
}
fsnotify_oldname_free(old_name);
return error;
}
SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname,
int, newdfd, const char __user *, newname)
{
struct dentry *old_dir, *new_dir;
struct dentry *old_dentry, *new_dentry;
struct dentry *trap;
struct nameidata oldnd, newnd;
char *from;
char *to;
int error;
error = user_path_parent(olddfd, oldname, &oldnd, &from);
if (error)
goto exit;
error = user_path_parent(newdfd, newname, &newnd, &to);
if (error)
goto exit1;
error = -EXDEV;
if (oldnd.path.mnt != newnd.path.mnt)
goto exit2;
old_dir = oldnd.path.dentry;
error = -EBUSY;
if (oldnd.last_type != LAST_NORM)
goto exit2;
new_dir = newnd.path.dentry;
if (newnd.last_type != LAST_NORM)
goto exit2;
oldnd.flags &= ~LOOKUP_PARENT;
newnd.flags &= ~LOOKUP_PARENT;
newnd.flags |= LOOKUP_RENAME_TARGET;
trap = lock_rename(new_dir, old_dir);
old_dentry = lookup_hash(&oldnd);
error = PTR_ERR(old_dentry);
if (IS_ERR(old_dentry))
goto exit3;
/* source must exist */
error = -ENOENT;
if (!old_dentry->d_inode)
goto exit4;
/* unless the source is a directory trailing slashes give -ENOTDIR */
if (!S_ISDIR(old_dentry->d_inode->i_mode)) {
error = -ENOTDIR;
if (oldnd.last.name[oldnd.last.len])
goto exit4;
if (newnd.last.name[newnd.last.len])
goto exit4;
}
/* source should not be ancestor of target */
error = -EINVAL;
if (old_dentry == trap)
goto exit4;
new_dentry = lookup_hash(&newnd);
error = PTR_ERR(new_dentry);
if (IS_ERR(new_dentry))
goto exit4;
/* target should not be an ancestor of source */
error = -ENOTEMPTY;
if (new_dentry == trap)
goto exit5;
error = mnt_want_write(oldnd.path.mnt);
if (error)
goto exit5;
error = security_path_rename(&oldnd.path, old_dentry,
&newnd.path, new_dentry);
if (error)
goto exit6;
error = vfs_rename(old_dir->d_inode, old_dentry,
new_dir->d_inode, new_dentry);
exit6:
mnt_drop_write(oldnd.path.mnt);
exit5:
dput(new_dentry);
exit4:
dput(old_dentry);
exit3:
unlock_rename(new_dir, old_dir);
exit2:
path_put(&newnd.path);
putname(to);
exit1:
path_put(&oldnd.path);
putname(from);
exit:
return error;
}
SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname)
{
return sys_renameat(AT_FDCWD, oldname, AT_FDCWD, newname);
}
int vfs_readlink(struct dentry *dentry, char __user *buffer, int buflen, const char *link)
{
int len;
len = PTR_ERR(link);
if (IS_ERR(link))
goto out;
len = strlen(link);
if (len > (unsigned) buflen)
len = buflen;
if (copy_to_user(buffer, link, len))
len = -EFAULT;
out:
return len;
}
/*
* A helper for ->readlink(). This should be used *ONLY* for symlinks that
* have ->follow_link() touching nd only in nd_set_link(). Using (or not
* using) it for any given inode is up to filesystem.
*/
int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct nameidata nd;
void *cookie;
int res;
nd.depth = 0;
cookie = dentry->d_inode->i_op->follow_link(dentry, &nd);
if (IS_ERR(cookie))
return PTR_ERR(cookie);
res = vfs_readlink(dentry, buffer, buflen, nd_get_link(&nd));
if (dentry->d_inode->i_op->put_link)
dentry->d_inode->i_op->put_link(dentry, &nd, cookie);
return res;
}
int vfs_follow_link(struct nameidata *nd, const char *link)
{
return __vfs_follow_link(nd, link);
}
/* get the link contents into pagecache */
static char *page_getlink(struct dentry * dentry, struct page **ppage)
{
char *kaddr;
struct page *page;
struct address_space *mapping = dentry->d_inode->i_mapping;
page = read_mapping_page(mapping, 0, NULL);
if (IS_ERR(page))
return (char*)page;
*ppage = page;
kaddr = kmap(page);
nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1);
return kaddr;
}
int page_readlink(struct dentry *dentry, char __user *buffer, int buflen)
{
struct page *page = NULL;
char *s = page_getlink(dentry, &page);
int res = vfs_readlink(dentry,buffer,buflen,s);
if (page) {
kunmap(page);
page_cache_release(page);
}
return res;
}
void *page_follow_link_light(struct dentry *dentry, struct nameidata *nd)
{
struct page *page = NULL;
nd_set_link(nd, page_getlink(dentry, &page));
return page;
}
void page_put_link(struct dentry *dentry, struct nameidata *nd, void *cookie)
{
struct page *page = cookie;
if (page) {
kunmap(page);
page_cache_release(page);
}
}
/*
* The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS
*/
int __page_symlink(struct inode *inode, const char *symname, int len, int nofs)
{
struct address_space *mapping = inode->i_mapping;
struct page *page;
void *fsdata;
int err;
char *kaddr;
unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE;
if (nofs)
flags |= AOP_FLAG_NOFS;
retry:
err = pagecache_write_begin(NULL, mapping, 0, len-1,
flags, &page, &fsdata);
if (err)
goto fail;
kaddr = kmap_atomic(page, KM_USER0);
memcpy(kaddr, symname, len-1);
kunmap_atomic(kaddr, KM_USER0);
err = pagecache_write_end(NULL, mapping, 0, len-1, len-1,
page, fsdata);
if (err < 0)
goto fail;
if (err < len-1)
goto retry;
mark_inode_dirty(inode);
return 0;
fail:
return err;
}
int page_symlink(struct inode *inode, const char *symname, int len)
{
return __page_symlink(inode, symname, len,
!(mapping_gfp_mask(inode->i_mapping) & __GFP_FS));
}
const struct inode_operations page_symlink_inode_operations = {
.readlink = generic_readlink,
.follow_link = page_follow_link_light,
.put_link = page_put_link,
};
EXPORT_SYMBOL(user_path_at);
EXPORT_SYMBOL(follow_down);
EXPORT_SYMBOL(follow_up);
EXPORT_SYMBOL(get_write_access); /* binfmt_aout */
EXPORT_SYMBOL(getname);
EXPORT_SYMBOL(lock_rename);
EXPORT_SYMBOL(lookup_one_len);
EXPORT_SYMBOL(page_follow_link_light);
EXPORT_SYMBOL(page_put_link);
EXPORT_SYMBOL(page_readlink);
EXPORT_SYMBOL(__page_symlink);
EXPORT_SYMBOL(page_symlink);
EXPORT_SYMBOL(page_symlink_inode_operations);
EXPORT_SYMBOL(path_lookup);
EXPORT_SYMBOL(kern_path);
EXPORT_SYMBOL(vfs_path_lookup);
EXPORT_SYMBOL(inode_permission);
EXPORT_SYMBOL(file_permission);
EXPORT_SYMBOL(unlock_rename);
EXPORT_SYMBOL(vfs_create);
EXPORT_SYMBOL(vfs_follow_link);
EXPORT_SYMBOL(vfs_link);
EXPORT_SYMBOL(vfs_mkdir);
EXPORT_SYMBOL(vfs_mknod);
EXPORT_SYMBOL(generic_permission);
EXPORT_SYMBOL(vfs_readlink);
EXPORT_SYMBOL(vfs_rename);
EXPORT_SYMBOL(vfs_rmdir);
EXPORT_SYMBOL(vfs_symlink);
EXPORT_SYMBOL(vfs_unlink);
EXPORT_SYMBOL(dentry_unhash);
EXPORT_SYMBOL(generic_readlink);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2035_0 |
crossvul-cpp_data_bad_2802_5 | /* nautilus-mime-actions.c - uri-specific versions of mime action functions
*
* Copyright (C) 2000, 2001 Eazel, Inc.
*
* The Gnome Library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* The Gnome Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with the Gnome Library; see the file COPYING.LIB. If not,
* see <http://www.gnu.org/licenses/>.
*
* Authors: Maciej Stachowiak <mjs@eazel.com>
*/
#include <config.h>
#include "nautilus-mime-actions.h"
#include "nautilus-window-slot.h"
#include "nautilus-application.h"
#include <eel/eel-glib-extensions.h>
#include <eel/eel-stock-dialogs.h>
#include <eel/eel-string.h>
#include <glib.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>
#include <string.h>
#include <gdk/gdkx.h>
#include "nautilus-file-attributes.h"
#include "nautilus-file.h"
#include "nautilus-file-operations.h"
#include "nautilus-metadata.h"
#include "nautilus-program-choosing.h"
#include "nautilus-global-preferences.h"
#include "nautilus-signaller.h"
#define DEBUG_FLAG NAUTILUS_DEBUG_MIME
#include "nautilus-debug.h"
typedef enum
{
ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE,
ACTIVATION_ACTION_ASK,
ACTIVATION_ACTION_LAUNCH,
ACTIVATION_ACTION_LAUNCH_IN_TERMINAL,
ACTIVATION_ACTION_OPEN_IN_VIEW,
ACTIVATION_ACTION_OPEN_IN_APPLICATION,
ACTIVATION_ACTION_EXTRACT,
ACTIVATION_ACTION_DO_NOTHING,
} ActivationAction;
typedef struct
{
NautilusFile *file;
char *uri;
} LaunchLocation;
typedef struct
{
GAppInfo *application;
GList *uris;
} ApplicationLaunchParameters;
typedef struct
{
NautilusWindowSlot *slot;
gpointer window;
GtkWindow *parent_window;
GCancellable *cancellable;
GList *locations;
GList *mountables;
GList *start_mountables;
GList *not_mounted;
NautilusWindowOpenFlags flags;
char *timed_wait_prompt;
gboolean timed_wait_active;
NautilusFileListHandle *files_handle;
gboolean tried_mounting;
char *activation_directory;
gboolean user_confirmation;
} ActivateParameters;
struct
{
char *name;
char *mimetypes[20];
} mimetype_groups[] =
{
{
N_("Anything"),
{ NULL }
},
{
N_("Files"),
{ "application/octet-stream",
"text/plain",
NULL}
},
{
N_("Folders"),
{ "inode/directory",
NULL}
},
{ N_("Documents"),
{ "application/rtf",
"application/msword",
"application/vnd.sun.xml.writer",
"application/vnd.sun.xml.writer.global",
"application/vnd.sun.xml.writer.template",
"application/vnd.oasis.opendocument.text",
"application/vnd.oasis.opendocument.text-template",
"application/x-abiword",
"application/x-applix-word",
"application/x-mswrite",
"application/docbook+xml",
"application/x-kword",
"application/x-kword-crypt",
"application/x-lyx",
NULL}},
{ N_("Illustration"),
{ "application/illustrator",
"application/vnd.corel-draw",
"application/vnd.stardivision.draw",
"application/vnd.oasis.opendocument.graphics",
"application/x-dia-diagram",
"application/x-karbon",
"application/x-killustrator",
"application/x-kivio",
"application/x-kontour",
"application/x-wpg",
NULL}},
{ N_("Music"),
{ "application/ogg",
"audio/x-vorbis+ogg",
"audio/ac3",
"audio/basic",
"audio/midi",
"audio/x-flac",
"audio/mp4",
"audio/mpeg",
"audio/x-mpeg",
"audio/x-ms-asx",
"audio/x-pn-realaudio",
NULL}},
{ N_("PDF / PostScript"),
{ "application/pdf",
"application/postscript",
"application/x-dvi",
"image/x-eps",
NULL}},
{ N_("Picture"),
{ "application/vnd.oasis.opendocument.image",
"application/x-krita",
"image/bmp",
"image/cgm",
"image/gif",
"image/jpeg",
"image/jpeg2000",
"image/png",
"image/svg+xml",
"image/tiff",
"image/x-compressed-xcf",
"image/x-pcx",
"image/x-photo-cd",
"image/x-psd",
"image/x-tga",
"image/x-xcf",
NULL}},
{ N_("Presentation"),
{ "application/vnd.ms-powerpoint",
"application/vnd.sun.xml.impress",
"application/vnd.oasis.opendocument.presentation",
"application/x-magicpoint",
"application/x-kpresenter",
NULL}},
{ N_("Spreadsheet"),
{ "application/vnd.lotus-1-2-3",
"application/vnd.ms-excel",
"application/vnd.stardivision.calc",
"application/vnd.sun.xml.calc",
"application/vnd.oasis.opendocument.spreadsheet",
"application/x-applix-spreadsheet",
"application/x-gnumeric",
"application/x-kspread",
"application/x-kspread-crypt",
"application/x-quattropro",
"application/x-sc",
"application/x-siag",
NULL}},
{ N_("Text File"),
{ "text/plain",
NULL}},
{ N_("Video"),
{ "video/mp4",
"video/3gpp",
"video/mpeg",
"video/quicktime",
"video/vivo",
"video/x-avi",
"video/x-mng",
"video/x-ms-asf",
"video/x-ms-wmv",
"video/x-msvideo",
"video/x-nsv",
"video/x-real-video",
NULL}}
};
/* Number of seconds until cancel dialog shows up */
#define DELAY_UNTIL_CANCEL_MSECS 5000
#define RESPONSE_RUN 1000
#define RESPONSE_DISPLAY 1001
#define RESPONSE_RUN_IN_TERMINAL 1002
#define RESPONSE_MARK_TRUSTED 1003
#define SILENT_WINDOW_OPEN_LIMIT 5
#define SILENT_OPEN_LIMIT 5
/* This number controls a maximum character count for a URL that is
* displayed as part of a dialog. It's fairly arbitrary -- big enough
* to allow most "normal" URIs to display in full, but small enough to
* prevent the dialog from getting insanely wide.
*/
#define MAX_URI_IN_DIALOG_LENGTH 60
static void cancel_activate_callback (gpointer callback_data);
static void activate_activation_uris_ready_callback (GList *files,
gpointer callback_data);
static void activation_mount_mountables (ActivateParameters *parameters);
static void activation_start_mountables (ActivateParameters *parameters);
static void activate_callback (GList *files,
gpointer callback_data);
static void activation_mount_not_mounted (ActivateParameters *parameters);
static void
launch_location_free (LaunchLocation *location)
{
nautilus_file_unref (location->file);
g_free (location->uri);
g_free (location);
}
static void
launch_location_list_free (GList *list)
{
g_list_foreach (list, (GFunc) launch_location_free, NULL);
g_list_free (list);
}
static GList *
get_file_list_for_launch_locations (GList *locations)
{
GList *files, *l;
LaunchLocation *location;
files = NULL;
for (l = locations; l != NULL; l = l->next)
{
location = l->data;
files = g_list_prepend (files,
nautilus_file_ref (location->file));
}
return g_list_reverse (files);
}
static LaunchLocation *
launch_location_from_file (NautilusFile *file)
{
LaunchLocation *location;
location = g_new (LaunchLocation, 1);
location->file = nautilus_file_ref (file);
location->uri = nautilus_file_get_uri (file);
return location;
}
static void
launch_location_update_from_file (LaunchLocation *location,
NautilusFile *file)
{
nautilus_file_unref (location->file);
g_free (location->uri);
location->file = nautilus_file_ref (file);
location->uri = nautilus_file_get_uri (file);
}
static void
launch_location_update_from_uri (LaunchLocation *location,
const char *uri)
{
nautilus_file_unref (location->file);
g_free (location->uri);
location->file = nautilus_file_get_by_uri (uri);
location->uri = g_strdup (uri);
}
static LaunchLocation *
find_launch_location_for_file (GList *list,
NautilusFile *file)
{
LaunchLocation *location;
GList *l;
for (l = list; l != NULL; l = l->next)
{
location = l->data;
if (location->file == file)
{
return location;
}
}
return NULL;
}
static GList *
launch_locations_from_file_list (GList *list)
{
GList *new;
new = NULL;
while (list)
{
new = g_list_prepend (new,
launch_location_from_file (list->data));
list = list->next;
}
new = g_list_reverse (new);
return new;
}
static ApplicationLaunchParameters *
application_launch_parameters_new (GAppInfo *application,
GList *uris)
{
ApplicationLaunchParameters *result;
result = g_new0 (ApplicationLaunchParameters, 1);
result->application = g_object_ref (application);
result->uris = g_list_copy_deep (uris, (GCopyFunc) g_strdup, NULL);
return result;
}
static void
application_launch_parameters_free (ApplicationLaunchParameters *parameters)
{
g_object_unref (parameters->application);
g_list_free_full (parameters->uris, g_free);
g_free (parameters);
}
static gboolean
nautilus_mime_actions_check_if_required_attributes_ready (NautilusFile *file)
{
NautilusFileAttributes attributes;
gboolean ready;
attributes = nautilus_mime_actions_get_required_file_attributes ();
ready = nautilus_file_check_if_ready (file, attributes);
return ready;
}
NautilusFileAttributes
nautilus_mime_actions_get_required_file_attributes (void)
{
return NAUTILUS_FILE_ATTRIBUTE_INFO |
NAUTILUS_FILE_ATTRIBUTE_LINK_INFO;
}
GAppInfo *
nautilus_mime_get_default_application_for_file (NautilusFile *file)
{
GAppInfo *app;
char *mime_type;
char *uri_scheme;
if (!nautilus_mime_actions_check_if_required_attributes_ready (file))
{
return NULL;
}
mime_type = nautilus_file_get_mime_type (file);
app = g_app_info_get_default_for_type (mime_type,
!nautilus_file_is_local_or_fuse (file));
g_free (mime_type);
if (app == NULL)
{
uri_scheme = nautilus_file_get_uri_scheme (file);
if (uri_scheme != NULL)
{
app = g_app_info_get_default_for_uri_scheme (uri_scheme);
g_free (uri_scheme);
}
}
return app;
}
static int
file_compare_by_mime_type (NautilusFile *file_a,
NautilusFile *file_b)
{
char *mime_type_a, *mime_type_b;
int ret;
mime_type_a = nautilus_file_get_mime_type (file_a);
mime_type_b = nautilus_file_get_mime_type (file_b);
ret = strcmp (mime_type_a, mime_type_b);
g_free (mime_type_a);
g_free (mime_type_b);
return ret;
}
static int
file_compare_by_parent_uri (NautilusFile *file_a,
NautilusFile *file_b)
{
char *parent_uri_a, *parent_uri_b;
int ret;
parent_uri_a = nautilus_file_get_parent_uri (file_a);
parent_uri_b = nautilus_file_get_parent_uri (file_b);
ret = strcmp (parent_uri_a, parent_uri_b);
g_free (parent_uri_a);
g_free (parent_uri_b);
return ret;
}
GAppInfo *
nautilus_mime_get_default_application_for_files (GList *files)
{
GList *l, *sorted_files;
NautilusFile *file;
GAppInfo *app, *one_app;
g_assert (files != NULL);
sorted_files = g_list_sort (g_list_copy (files), (GCompareFunc) file_compare_by_mime_type);
app = NULL;
for (l = sorted_files; l != NULL; l = l->next)
{
file = l->data;
if (l->prev &&
file_compare_by_mime_type (file, l->prev->data) == 0 &&
file_compare_by_parent_uri (file, l->prev->data) == 0)
{
continue;
}
one_app = nautilus_mime_get_default_application_for_file (file);
if (one_app == NULL || (app != NULL && !g_app_info_equal (app, one_app)))
{
if (app)
{
g_object_unref (app);
}
if (one_app)
{
g_object_unref (one_app);
}
app = NULL;
break;
}
if (app == NULL)
{
app = one_app;
}
else
{
g_object_unref (one_app);
}
}
g_list_free (sorted_files);
return app;
}
static void
trash_or_delete_files (GtkWindow *parent_window,
const GList *files,
gboolean delete_if_all_already_in_trash)
{
GList *locations;
const GList *node;
locations = NULL;
for (node = files; node != NULL; node = node->next)
{
locations = g_list_prepend (locations,
nautilus_file_get_location ((NautilusFile *) node->data));
}
locations = g_list_reverse (locations);
nautilus_file_operations_trash_or_delete (locations,
parent_window,
NULL, NULL);
g_list_free_full (locations, g_object_unref);
}
static void
report_broken_symbolic_link (GtkWindow *parent_window,
NautilusFile *file)
{
char *target_path;
char *display_name;
char *prompt;
char *detail;
GtkDialog *dialog;
GList file_as_list;
int response;
gboolean can_trash;
g_assert (nautilus_file_is_broken_symbolic_link (file));
display_name = nautilus_file_get_display_name (file);
can_trash = nautilus_file_can_trash (file) && !nautilus_file_is_in_trash (file);
if (can_trash)
{
prompt = g_strdup_printf (_("The link “%s” is broken. Move it to Trash?"), display_name);
}
else
{
prompt = g_strdup_printf (_("The link “%s” is broken."), display_name);
}
g_free (display_name);
target_path = nautilus_file_get_symbolic_link_target_path (file);
if (target_path == NULL)
{
detail = g_strdup (_("This link cannot be used because it has no target."));
}
else
{
detail = g_strdup_printf (_("This link cannot be used because its target "
"“%s” doesn’t exist."), target_path);
}
if (!can_trash)
{
eel_run_simple_dialog (GTK_WIDGET (parent_window), FALSE, GTK_MESSAGE_WARNING,
prompt, detail, _("_Cancel"), NULL);
goto out;
}
dialog = eel_show_yes_no_dialog (prompt, detail, _("Mo_ve to Trash"), _("_Cancel"),
parent_window);
gtk_dialog_set_default_response (dialog, GTK_RESPONSE_CANCEL);
/* Make this modal to avoid problems with reffing the view & file
* to keep them around in case the view changes, which would then
* cause the old view not to be destroyed, which would cause its
* merged Bonobo items not to be un-merged. Maybe we need to unmerge
* explicitly when disconnecting views instead of relying on the
* unmerge in Destroy. But since BonoboUIHandler is probably going
* to change wildly, I don't want to mess with this now.
*/
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
if (response == GTK_RESPONSE_YES)
{
file_as_list.data = file;
file_as_list.next = NULL;
file_as_list.prev = NULL;
trash_or_delete_files (parent_window, &file_as_list, TRUE);
}
out:
g_free (prompt);
g_free (target_path);
g_free (detail);
}
static ActivationAction
get_executable_text_file_action (GtkWindow *parent_window,
NautilusFile *file)
{
GtkDialog *dialog;
char *file_name;
char *prompt;
char *detail;
int preferences_value;
int response;
g_assert (nautilus_file_contains_text (file));
preferences_value = g_settings_get_enum (nautilus_preferences,
NAUTILUS_PREFERENCES_EXECUTABLE_TEXT_ACTIVATION);
switch (preferences_value)
{
case NAUTILUS_EXECUTABLE_TEXT_LAUNCH:
{
return ACTIVATION_ACTION_LAUNCH;
}
case NAUTILUS_EXECUTABLE_TEXT_DISPLAY:
{
return ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
case NAUTILUS_EXECUTABLE_TEXT_ASK:
{
}
break;
default:
/* Complain non-fatally, since preference data can't be trusted */
g_warning ("Unknown value %d for NAUTILUS_PREFERENCES_EXECUTABLE_TEXT_ACTIVATION",
preferences_value);
}
file_name = nautilus_file_get_display_name (file);
prompt = g_strdup_printf (_("Do you want to run “%s”, or display its contents?"),
file_name);
detail = g_strdup_printf (_("“%s” is an executable text file."),
file_name);
g_free (file_name);
dialog = eel_create_question_dialog (prompt,
detail,
_("Run in _Terminal"), RESPONSE_RUN_IN_TERMINAL,
_("_Display"), RESPONSE_DISPLAY,
parent_window);
gtk_dialog_add_button (dialog, _("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_dialog_add_button (dialog, _("_Run"), RESPONSE_RUN);
gtk_dialog_set_default_response (dialog, GTK_RESPONSE_CANCEL);
gtk_widget_show (GTK_WIDGET (dialog));
g_free (prompt);
g_free (detail);
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
switch (response)
{
case RESPONSE_RUN:
{
return ACTIVATION_ACTION_LAUNCH;
}
case RESPONSE_RUN_IN_TERMINAL:
{
return ACTIVATION_ACTION_LAUNCH_IN_TERMINAL;
}
case RESPONSE_DISPLAY:
{
return ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
default:
return ACTIVATION_ACTION_DO_NOTHING;
}
}
static ActivationAction
get_default_executable_text_file_action (void)
{
int preferences_value;
preferences_value = g_settings_get_enum (nautilus_preferences,
NAUTILUS_PREFERENCES_EXECUTABLE_TEXT_ACTIVATION);
switch (preferences_value)
{
case NAUTILUS_EXECUTABLE_TEXT_LAUNCH:
{
return ACTIVATION_ACTION_LAUNCH;
}
case NAUTILUS_EXECUTABLE_TEXT_DISPLAY:
{
return ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
case NAUTILUS_EXECUTABLE_TEXT_ASK:
default:
return ACTIVATION_ACTION_ASK;
}
}
static ActivationAction
get_activation_action (NautilusFile *file)
{
ActivationAction action;
char *activation_uri;
gboolean can_extract;
can_extract = g_settings_get_boolean (nautilus_preferences,
NAUTILUS_PREFERENCES_AUTOMATIC_DECOMPRESSION);
if (can_extract && nautilus_file_is_archive (file))
{
return ACTIVATION_ACTION_EXTRACT;
}
if (nautilus_file_is_nautilus_link (file))
{
return ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE;
}
activation_uri = nautilus_file_get_activation_uri (file);
if (activation_uri == NULL)
{
activation_uri = nautilus_file_get_uri (file);
}
action = ACTIVATION_ACTION_DO_NOTHING;
if (nautilus_file_is_launchable (file))
{
char *executable_path;
action = ACTIVATION_ACTION_LAUNCH;
executable_path = g_filename_from_uri (activation_uri, NULL, NULL);
if (!executable_path)
{
action = ACTIVATION_ACTION_DO_NOTHING;
}
else if (nautilus_file_contains_text (file))
{
action = get_default_executable_text_file_action ();
}
g_free (executable_path);
}
if (action == ACTIVATION_ACTION_DO_NOTHING)
{
if (nautilus_file_opens_in_view (file))
{
action = ACTIVATION_ACTION_OPEN_IN_VIEW;
}
else
{
action = ACTIVATION_ACTION_OPEN_IN_APPLICATION;
}
}
g_free (activation_uri);
return action;
}
gboolean
nautilus_mime_file_extracts (NautilusFile *file)
{
return get_activation_action (file) == ACTIVATION_ACTION_EXTRACT;
}
gboolean
nautilus_mime_file_launches (NautilusFile *file)
{
ActivationAction activation_action;
activation_action = get_activation_action (file);
return (activation_action == ACTIVATION_ACTION_LAUNCH);
}
gboolean
nautilus_mime_file_opens_in_external_app (NautilusFile *file)
{
ActivationAction activation_action;
activation_action = get_activation_action (file);
return (activation_action == ACTIVATION_ACTION_OPEN_IN_APPLICATION);
}
static unsigned int
mime_application_hash (GAppInfo *app)
{
const char *id;
id = g_app_info_get_id (app);
if (id == NULL)
{
return GPOINTER_TO_UINT (app);
}
return g_str_hash (id);
}
static void
list_to_parameters_foreach (GAppInfo *application,
GList *uris,
GList **ret)
{
ApplicationLaunchParameters *parameters;
uris = g_list_reverse (uris);
parameters = application_launch_parameters_new
(application, uris);
*ret = g_list_prepend (*ret, parameters);
}
/**
* make_activation_parameters
*
* Construct a list of ApplicationLaunchParameters from a list of NautilusFiles,
* where files that have the same default application are put into the same
* launch parameter, and others are put into the unhandled_files list.
*
* @files: Files to use for construction.
* @unhandled_files: Files without any default application will be put here.
*
* Return value: Newly allocated list of ApplicationLaunchParameters.
**/
static GList *
make_activation_parameters (GList *uris,
GList **unhandled_uris)
{
GList *ret, *l, *app_uris;
NautilusFile *file;
GAppInfo *app, *old_app;
GHashTable *app_table;
char *uri;
ret = NULL;
*unhandled_uris = NULL;
app_table = g_hash_table_new_full
((GHashFunc) mime_application_hash,
(GEqualFunc) g_app_info_equal,
(GDestroyNotify) g_object_unref,
(GDestroyNotify) g_list_free);
for (l = uris; l != NULL; l = l->next)
{
uri = l->data;
file = nautilus_file_get_by_uri (uri);
app = nautilus_mime_get_default_application_for_file (file);
if (app != NULL)
{
app_uris = NULL;
if (g_hash_table_lookup_extended (app_table, app,
(gpointer *) &old_app,
(gpointer *) &app_uris))
{
g_hash_table_steal (app_table, old_app);
app_uris = g_list_prepend (app_uris, uri);
g_object_unref (app);
app = old_app;
}
else
{
app_uris = g_list_prepend (NULL, uri);
}
g_hash_table_insert (app_table, app, app_uris);
}
else
{
*unhandled_uris = g_list_prepend (*unhandled_uris, uri);
}
nautilus_file_unref (file);
}
g_hash_table_foreach (app_table,
(GHFunc) list_to_parameters_foreach,
&ret);
g_hash_table_destroy (app_table);
*unhandled_uris = g_list_reverse (*unhandled_uris);
return g_list_reverse (ret);
}
static gboolean
file_was_cancelled (NautilusFile *file)
{
GError *error;
error = nautilus_file_get_file_info_error (file);
return
error != NULL &&
error->domain == G_IO_ERROR &&
error->code == G_IO_ERROR_CANCELLED;
}
static gboolean
file_was_not_mounted (NautilusFile *file)
{
GError *error;
error = nautilus_file_get_file_info_error (file);
return
error != NULL &&
error->domain == G_IO_ERROR &&
error->code == G_IO_ERROR_NOT_MOUNTED;
}
static void
activation_parameters_free (ActivateParameters *parameters)
{
if (parameters->timed_wait_active)
{
eel_timed_wait_stop (cancel_activate_callback, parameters);
}
if (parameters->slot)
{
g_object_remove_weak_pointer (G_OBJECT (parameters->slot), (gpointer *) ¶meters->slot);
}
if (parameters->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (parameters->parent_window), (gpointer *) ¶meters->parent_window);
}
g_object_unref (parameters->cancellable);
launch_location_list_free (parameters->locations);
nautilus_file_list_free (parameters->mountables);
nautilus_file_list_free (parameters->start_mountables);
nautilus_file_list_free (parameters->not_mounted);
g_free (parameters->activation_directory);
g_free (parameters->timed_wait_prompt);
g_assert (parameters->files_handle == NULL);
g_free (parameters);
}
static void
cancel_activate_callback (gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
parameters->timed_wait_active = FALSE;
g_cancellable_cancel (parameters->cancellable);
if (parameters->files_handle)
{
nautilus_file_list_cancel_call_when_ready (parameters->files_handle);
parameters->files_handle = NULL;
activation_parameters_free (parameters);
}
}
static void
activation_start_timed_cancel (ActivateParameters *parameters)
{
parameters->timed_wait_active = TRUE;
eel_timed_wait_start_with_duration
(DELAY_UNTIL_CANCEL_MSECS,
cancel_activate_callback,
parameters,
parameters->timed_wait_prompt,
parameters->parent_window);
}
static void
pause_activation_timed_cancel (ActivateParameters *parameters)
{
if (parameters->timed_wait_active)
{
eel_timed_wait_stop (cancel_activate_callback, parameters);
parameters->timed_wait_active = FALSE;
}
}
static void
unpause_activation_timed_cancel (ActivateParameters *parameters)
{
if (!parameters->timed_wait_active)
{
activation_start_timed_cancel (parameters);
}
}
static void
activate_mount_op_active (GtkMountOperation *operation,
GParamSpec *pspec,
ActivateParameters *parameters)
{
gboolean is_active;
g_object_get (operation, "is-showing", &is_active, NULL);
if (is_active)
{
pause_activation_timed_cancel (parameters);
}
else
{
unpause_activation_timed_cancel (parameters);
}
}
static gboolean
confirm_multiple_windows (GtkWindow *parent_window,
int count,
gboolean use_tabs)
{
GtkDialog *dialog;
char *prompt;
char *detail;
int response;
if (count <= SILENT_WINDOW_OPEN_LIMIT)
{
return TRUE;
}
prompt = _("Are you sure you want to open all files?");
if (use_tabs)
{
detail = g_strdup_printf (ngettext ("This will open %d separate tab.",
"This will open %d separate tabs.", count), count);
}
else
{
detail = g_strdup_printf (ngettext ("This will open %d separate window.",
"This will open %d separate windows.", count), count);
}
dialog = eel_show_yes_no_dialog (prompt, detail,
_("_OK"), _("_Cancel"),
parent_window);
g_free (detail);
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
return response == GTK_RESPONSE_YES;
}
typedef struct
{
NautilusWindowSlot *slot;
GtkWindow *parent_window;
NautilusFile *file;
GList *files;
NautilusWindowOpenFlags flags;
char *activation_directory;
gboolean user_confirmation;
char *uri;
GDBusProxy *proxy;
GtkWidget *dialog;
} ActivateParametersInstall;
static void
activate_parameters_install_free (ActivateParametersInstall *parameters_install)
{
if (parameters_install->slot)
{
g_object_remove_weak_pointer (G_OBJECT (parameters_install->slot), (gpointer *) ¶meters_install->slot);
}
if (parameters_install->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (parameters_install->parent_window), (gpointer *) ¶meters_install->parent_window);
}
if (parameters_install->proxy != NULL)
{
g_object_unref (parameters_install->proxy);
}
nautilus_file_unref (parameters_install->file);
nautilus_file_list_free (parameters_install->files);
g_free (parameters_install->activation_directory);
g_free (parameters_install->uri);
g_free (parameters_install);
}
static char *
get_application_no_mime_type_handler_message (NautilusFile *file,
char *uri)
{
char *uri_for_display;
char *name;
char *error_message;
name = nautilus_file_get_display_name (file);
/* Truncate the URI so it doesn't get insanely wide. Note that even
* though the dialog uses wrapped text, if the URI doesn't contain
* white space then the text-wrapping code is too stupid to wrap it.
*/
uri_for_display = eel_str_middle_truncate (name, MAX_URI_IN_DIALOG_LENGTH);
error_message = g_strdup_printf (_("Could not display “%s”."), uri_for_display);
g_free (uri_for_display);
g_free (name);
return error_message;
}
static void
open_with_response_cb (GtkDialog *dialog,
gint response_id,
gpointer user_data)
{
GtkWindow *parent_window;
NautilusFile *file;
GList files;
GAppInfo *info;
ActivateParametersInstall *parameters = user_data;
if (response_id != GTK_RESPONSE_OK)
{
gtk_widget_destroy (GTK_WIDGET (dialog));
return;
}
parent_window = parameters->parent_window;
file = g_object_get_data (G_OBJECT (dialog), "mime-action:file");
info = gtk_app_chooser_get_app_info (GTK_APP_CHOOSER (dialog));
gtk_widget_destroy (GTK_WIDGET (dialog));
g_signal_emit_by_name (nautilus_signaller_get_current (), "mime-data-changed");
files.next = NULL;
files.prev = NULL;
files.data = file;
nautilus_launch_application (info, &files, parent_window);
g_object_unref (info);
activate_parameters_install_free (parameters);
}
static void
choose_program (GtkDialog *message_dialog,
int response,
gpointer callback_data)
{
GtkWidget *dialog;
NautilusFile *file;
GFile *location;
ActivateParametersInstall *parameters = callback_data;
if (response != GTK_RESPONSE_ACCEPT)
{
gtk_widget_destroy (GTK_WIDGET (message_dialog));
activate_parameters_install_free (parameters);
return;
}
file = g_object_get_data (G_OBJECT (message_dialog), "mime-action:file");
g_assert (NAUTILUS_IS_FILE (file));
location = nautilus_file_get_location (file);
nautilus_file_ref (file);
/* Destroy the message dialog after ref:ing the file */
gtk_widget_destroy (GTK_WIDGET (message_dialog));
dialog = gtk_app_chooser_dialog_new (parameters->parent_window,
GTK_DIALOG_MODAL,
location);
g_object_set_data_full (G_OBJECT (dialog),
"mime-action:file",
nautilus_file_ref (file),
(GDestroyNotify) nautilus_file_unref);
gtk_widget_show (dialog);
g_signal_connect (dialog,
"response",
G_CALLBACK (open_with_response_cb),
parameters);
g_object_unref (location);
nautilus_file_unref (file);
}
static void
show_unhandled_type_error (ActivateParametersInstall *parameters)
{
GtkWidget *dialog;
char *mime_type = nautilus_file_get_mime_type (parameters->file);
char *error_message = get_application_no_mime_type_handler_message (parameters->file, parameters->uri);
if (g_content_type_is_unknown (mime_type))
{
dialog = gtk_message_dialog_new (parameters->parent_window,
GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
0,
"%s", error_message);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("The file is of an unknown type"));
}
else
{
char *text;
text = g_strdup_printf (_("There is no application installed for “%s” files"), g_content_type_get_description (mime_type));
dialog = gtk_message_dialog_new (parameters->parent_window,
GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,
GTK_MESSAGE_ERROR,
0,
"%s", error_message);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
"%s", text);
g_free (text);
}
gtk_dialog_add_button (GTK_DIALOG (dialog), _("_Select Application"), GTK_RESPONSE_ACCEPT);
gtk_dialog_add_button (GTK_DIALOG (dialog), _("_OK"), GTK_RESPONSE_OK);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK);
g_object_set_data_full (G_OBJECT (dialog),
"mime-action:file",
nautilus_file_ref (parameters->file),
(GDestroyNotify) nautilus_file_unref);
gtk_widget_show (GTK_WIDGET (dialog));
g_signal_connect (dialog, "response",
G_CALLBACK (choose_program), parameters);
g_free (error_message);
g_free (mime_type);
}
static void
search_for_application_dbus_call_notify_cb (GDBusProxy *proxy,
GAsyncResult *result,
gpointer user_data)
{
ActivateParametersInstall *parameters_install = user_data;
GVariant *variant;
GError *error = NULL;
variant = g_dbus_proxy_call_finish (proxy, result, &error);
if (variant == NULL)
{
if (!g_dbus_error_is_remote_error (error) ||
g_strcmp0 (g_dbus_error_get_remote_error (error), "org.freedesktop.PackageKit.Modify.Failed") == 0)
{
char *message;
message = g_strdup_printf ("%s\n%s",
_("There was an internal error trying to search for applications:"),
error->message);
eel_show_error_dialog (_("Unable to search for application"), message,
parameters_install->parent_window);
g_free (message);
}
else
{
g_warning ("Error while trying to search for applications: %s",
error->message);
}
g_error_free (error);
activate_parameters_install_free (parameters_install);
return;
}
g_variant_unref (variant);
/* activate the file again */
nautilus_mime_activate_files (parameters_install->parent_window,
parameters_install->slot,
parameters_install->files,
parameters_install->activation_directory,
parameters_install->flags,
parameters_install->user_confirmation);
activate_parameters_install_free (parameters_install);
}
static void
search_for_application_mime_type (ActivateParametersInstall *parameters_install,
const gchar *mime_type)
{
GdkWindow *window;
guint xid = 0;
const char *mime_types[2];
g_assert (parameters_install->proxy != NULL);
/* get XID from parent window */
window = gtk_widget_get_window (GTK_WIDGET (parameters_install->parent_window));
if (window != NULL)
{
xid = GDK_WINDOW_XID (window);
}
mime_types[0] = mime_type;
mime_types[1] = NULL;
g_dbus_proxy_call (parameters_install->proxy,
"InstallMimeTypes",
g_variant_new ("(u^ass)",
xid,
mime_types,
"hide-confirm-search"),
G_DBUS_CALL_FLAGS_NONE,
G_MAXINT /* no timeout */,
NULL /* cancellable */,
(GAsyncReadyCallback) search_for_application_dbus_call_notify_cb,
parameters_install);
DEBUG ("InstallMimeType method invoked for %s", mime_type);
}
static void
application_unhandled_file_install (GtkDialog *dialog,
gint response_id,
ActivateParametersInstall *parameters_install)
{
char *mime_type;
gtk_widget_destroy (GTK_WIDGET (dialog));
parameters_install->dialog = NULL;
if (response_id == GTK_RESPONSE_YES)
{
mime_type = nautilus_file_get_mime_type (parameters_install->file);
search_for_application_mime_type (parameters_install, mime_type);
g_free (mime_type);
}
else
{
/* free as we're not going to get the async dbus callback */
activate_parameters_install_free (parameters_install);
}
}
static gboolean
delete_cb (GtkDialog *dialog)
{
gtk_dialog_response (dialog, GTK_RESPONSE_DELETE_EVENT);
return TRUE;
}
static void
pk_proxy_appeared_cb (GObject *source,
GAsyncResult *res,
gpointer user_data)
{
ActivateParametersInstall *parameters_install = user_data;
char *mime_type, *name_owner;
char *error_message;
GtkWidget *dialog;
GDBusProxy *proxy;
GError *error = NULL;
proxy = g_dbus_proxy_new_for_bus_finish (res, &error);
name_owner = g_dbus_proxy_get_name_owner (proxy);
if (error != NULL || name_owner == NULL)
{
g_warning ("Couldn't call Modify on the PackageKit interface: %s",
error != NULL ? error->message : "no owner for PackageKit");
g_clear_error (&error);
/* show an unhelpful dialog */
show_unhandled_type_error (parameters_install);
return;
}
g_free (name_owner);
mime_type = nautilus_file_get_mime_type (parameters_install->file);
error_message = get_application_no_mime_type_handler_message (parameters_install->file,
parameters_install->uri);
/* use a custom dialog to prompt the user to install new software */
dialog = gtk_message_dialog_new (parameters_install->parent_window, 0,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_YES_NO,
"%s", error_message);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog),
_("There is no application installed for “%s” files.\n"
"Do you want to search for an application to open this file?"),
g_content_type_get_description (mime_type));
gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);
parameters_install->dialog = dialog;
parameters_install->proxy = proxy;
g_signal_connect (dialog, "response",
G_CALLBACK (application_unhandled_file_install),
parameters_install);
g_signal_connect (dialog, "delete-event",
G_CALLBACK (delete_cb), NULL);
gtk_widget_show_all (dialog);
g_free (mime_type);
}
static void
application_unhandled_uri (ActivateParameters *parameters,
char *uri)
{
gboolean show_install_mime;
char *mime_type;
NautilusFile *file;
ActivateParametersInstall *parameters_install;
file = nautilus_file_get_by_uri (uri);
mime_type = nautilus_file_get_mime_type (file);
/* copy the parts of parameters we are interested in as the orignal will be unref'd */
parameters_install = g_new0 (ActivateParametersInstall, 1);
parameters_install->slot = parameters->slot;
g_object_add_weak_pointer (G_OBJECT (parameters_install->slot), (gpointer *) ¶meters_install->slot);
if (parameters->parent_window)
{
parameters_install->parent_window = parameters->parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters_install->parent_window), (gpointer *) ¶meters_install->parent_window);
}
parameters_install->activation_directory = g_strdup (parameters->activation_directory);
parameters_install->file = file;
parameters_install->files = get_file_list_for_launch_locations (parameters->locations);
parameters_install->flags = parameters->flags;
parameters_install->user_confirmation = parameters->user_confirmation;
parameters_install->uri = g_strdup (uri);
#ifdef ENABLE_PACKAGEKIT
/* allow an admin to disable the PackageKit search functionality */
show_install_mime = g_settings_get_boolean (nautilus_preferences, NAUTILUS_PREFERENCES_INSTALL_MIME_ACTIVATION);
#else
/* we have no install functionality */
show_install_mime = FALSE;
#endif
/* There is no use trying to look for handlers of application/octet-stream */
if (g_content_type_is_unknown (mime_type))
{
show_install_mime = FALSE;
}
g_free (mime_type);
if (!show_install_mime)
{
goto out;
}
g_dbus_proxy_new_for_bus (G_BUS_TYPE_SESSION,
G_DBUS_PROXY_FLAGS_NONE,
NULL,
"org.freedesktop.PackageKit",
"/org/freedesktop/PackageKit",
"org.freedesktop.PackageKit.Modify",
NULL,
pk_proxy_appeared_cb,
parameters_install);
return;
out:
/* show an unhelpful dialog */
show_unhandled_type_error (parameters_install);
}
typedef struct
{
GtkWindow *parent_window;
NautilusFile *file;
} ActivateParametersDesktop;
static void
activate_parameters_desktop_free (ActivateParametersDesktop *parameters_desktop)
{
if (parameters_desktop->parent_window)
{
g_object_remove_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) ¶meters_desktop->parent_window);
}
nautilus_file_unref (parameters_desktop->file);
g_free (parameters_desktop);
}
static void
untrusted_launcher_response_callback (GtkDialog *dialog,
int response_id,
ActivateParametersDesktop *parameters)
{
GdkScreen *screen;
char *uri;
GFile *file;
switch (response_id)
{
case RESPONSE_RUN:
{
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
uri = nautilus_file_get_uri (parameters->file);
DEBUG ("Launching untrusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
break;
case RESPONSE_MARK_TRUSTED:
{
file = nautilus_file_get_location (parameters->file);
nautilus_file_mark_desktop_file_trusted (file,
parameters->parent_window,
TRUE,
NULL, NULL);
g_object_unref (file);
}
break;
default:
{
/* Just destroy dialog */
}
break;
}
gtk_widget_destroy (GTK_WIDGET (dialog));
activate_parameters_desktop_free (parameters);
}
static void
activate_desktop_file (ActivateParameters *parameters,
NautilusFile *file)
{
ActivateParametersDesktop *parameters_desktop;
char *primary, *secondary, *display_name;
GtkWidget *dialog;
GdkScreen *screen;
char *uri;
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
if (!nautilus_file_is_trusted_link (file))
{
/* copy the parts of parameters we are interested in as the orignal will be freed */
parameters_desktop = g_new0 (ActivateParametersDesktop, 1);
if (parameters->parent_window)
{
parameters_desktop->parent_window = parameters->parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters_desktop->parent_window), (gpointer *) ¶meters_desktop->parent_window);
}
parameters_desktop->file = nautilus_file_ref (file);
primary = _("Untrusted application launcher");
display_name = nautilus_file_get_display_name (file);
secondary =
g_strdup_printf (_("The application launcher “%s” has not been marked as trusted. "
"If you do not know the source of this file, launching it may be unsafe."
),
display_name);
dialog = gtk_message_dialog_new (parameters->parent_window,
0,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_NONE,
NULL);
g_object_set (dialog,
"text", primary,
"secondary-text", secondary,
NULL);
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Launch Anyway"), RESPONSE_RUN);
if (nautilus_file_can_set_permissions (file))
{
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("Mark as _Trusted"), RESPONSE_MARK_TRUSTED);
}
gtk_dialog_add_button (GTK_DIALOG (dialog),
_("_Cancel"), GTK_RESPONSE_CANCEL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL);
g_signal_connect (dialog, "response",
G_CALLBACK (untrusted_launcher_response_callback),
parameters_desktop);
gtk_widget_show (dialog);
g_free (display_name);
g_free (secondary);
return;
}
uri = nautilus_file_get_uri (file);
DEBUG ("Launching trusted launcher %s", uri);
nautilus_launch_desktop_file (screen, uri, NULL,
parameters->parent_window);
g_free (uri);
}
static void
activate_files (ActivateParameters *parameters)
{
NautilusFile *file;
NautilusWindow *window;
NautilusWindowOpenFlags flags;
g_autoptr (GList) open_in_app_parameters = NULL;
g_autoptr (GList) unhandled_open_in_app_uris = NULL;
ApplicationLaunchParameters *one_parameters;
int count;
g_autofree char *old_working_dir = NULL;
GdkScreen *screen;
gint num_apps;
gint num_unhandled;
gint num_files;
gboolean open_files;
gboolean closed_window;
g_autoptr (GQueue) launch_desktop_files = NULL;
g_autoptr (GQueue) launch_files = NULL;
g_autoptr (GQueue) launch_in_terminal_files = NULL;
g_autoptr (GQueue) open_in_app_uris = NULL;
g_autoptr (GQueue) open_in_view_files = NULL;
GList *l;
ActivationAction action;
LaunchLocation *location;
launch_desktop_files = g_queue_new ();
launch_files = g_queue_new ();
launch_in_terminal_files = g_queue_new ();
open_in_view_files = g_queue_new ();
open_in_app_uris = g_queue_new ();
for (l = parameters->locations; l != NULL; l = l->next)
{
location = l->data;
file = location->file;
if (file_was_cancelled (file))
{
continue;
}
action = get_activation_action (file);
if (action == ACTIVATION_ACTION_ASK)
{
/* Special case for executable text files, since it might be
* dangerous & unexpected to launch these.
*/
pause_activation_timed_cancel (parameters);
action = get_executable_text_file_action (parameters->parent_window, file);
unpause_activation_timed_cancel (parameters);
}
switch (action)
{
case ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE:
{
g_queue_push_tail (launch_desktop_files, file);
}
break;
case ACTIVATION_ACTION_LAUNCH:
{
g_queue_push_tail (launch_files, file);
}
break;
case ACTIVATION_ACTION_LAUNCH_IN_TERMINAL:
{
g_queue_push_tail (launch_in_terminal_files, file);
}
break;
case ACTIVATION_ACTION_OPEN_IN_VIEW:
{
g_queue_push_tail (open_in_view_files, file);
}
break;
case ACTIVATION_ACTION_OPEN_IN_APPLICATION:
{
g_queue_push_tail (open_in_app_uris, location->uri);
}
break;
case ACTIVATION_ACTION_DO_NOTHING:
{
}
break;
case ACTIVATION_ACTION_EXTRACT:
{
/* Extraction of files should be handled in the view */
g_assert_not_reached ();
}
break;
case ACTIVATION_ACTION_ASK:
{
g_assert_not_reached ();
}
break;
}
}
for (l = g_queue_peek_head_link (launch_desktop_files); l != NULL; l = l->next)
{
file = NAUTILUS_FILE (l->data);
activate_desktop_file (parameters, file);
}
if (parameters->activation_directory &&
(!g_queue_is_empty (launch_files) ||
!g_queue_is_empty (launch_in_terminal_files)))
{
old_working_dir = g_get_current_dir ();
g_chdir (parameters->activation_directory);
}
screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window));
for (l = g_queue_peek_head_link (launch_files); l != NULL; l = l->next)
{
g_autofree char *uri = NULL;
g_autofree char *executable_path = NULL;
g_autofree char *quoted_path = NULL;
file = NAUTILUS_FILE (l->data);
uri = nautilus_file_get_activation_uri (file);
executable_path = g_filename_from_uri (uri, NULL, NULL);
quoted_path = g_shell_quote (executable_path);
DEBUG ("Launching file path %s", quoted_path);
nautilus_launch_application_from_command (screen, quoted_path, FALSE, NULL);
}
for (l = g_queue_peek_head_link (launch_in_terminal_files); l != NULL; l = l->next)
{
g_autofree char *uri = NULL;
g_autofree char *executable_path = NULL;
g_autofree char *quoted_path = NULL;
file = NAUTILUS_FILE (l->data);
uri = nautilus_file_get_activation_uri (file);
executable_path = g_filename_from_uri (uri, NULL, NULL);
quoted_path = g_shell_quote (executable_path);
DEBUG ("Launching in terminal file quoted path %s", quoted_path);
nautilus_launch_application_from_command (screen, quoted_path, TRUE, NULL);
}
if (old_working_dir != NULL)
{
g_chdir (old_working_dir);
}
count = g_queue_get_length (open_in_view_files);
flags = parameters->flags;
if (count > 1)
{
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0)
{
/* if CLOSE_BEHIND is set and we have a directory to be activated, we
* will first have to open a new window and after that we can open the
* rest of files in tabs */
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0)
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW;
}
else
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB;
}
}
else
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW;
}
}
else
{
/* if we want to close the window and activate a single directory, then we will need
* the NEW_WINDOW flag set */
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0)
{
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW;
}
}
if (parameters->slot != NULL &&
(!parameters->user_confirmation ||
confirm_multiple_windows (parameters->parent_window, count,
(flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0)))
{
if ((flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0 &&
g_settings_get_enum (nautilus_preferences, NAUTILUS_PREFERENCES_NEW_TAB_POSITION) ==
NAUTILUS_NEW_TAB_POSITION_AFTER_CURRENT_TAB)
{
/* When inserting N tabs after the current one,
* we first open tab N, then tab N-1, ..., then tab 0.
* Each of them is appended to the current tab, i.e.
* prepended to the list of tabs to open.
*/
g_queue_reverse (open_in_view_files);
}
closed_window = FALSE;
for (l = g_queue_peek_head_link (open_in_view_files); l != NULL; l = l->next)
{
g_autofree char *uri = NULL;
g_autoptr (GFile) location = NULL;
g_autoptr (GFile) location_with_permissions = NULL;
/* The ui should ask for navigation or object windows
* depending on what the current one is */
file = NAUTILUS_FILE (l->data);
uri = nautilus_file_get_activation_uri (file);
location = g_file_new_for_uri (uri);
if (g_file_is_native (location) &&
(nautilus_file_is_in_admin (file) ||
!nautilus_file_can_read (file) ||
!nautilus_file_can_execute (file)))
{
g_autofree gchar *file_path = NULL;
g_free (uri);
file_path = g_file_get_path (location);
uri = g_strconcat ("admin://", file_path, NULL);
}
location_with_permissions = g_file_new_for_uri (uri);
/* FIXME: we need to pass the parent_window, but we only use it for the current active window,
* which nautilus-application should take care of. However is not working and creating regressions
* in some cases. Until we figure out what's going on, continue to use the parameters->slot
* to make splicit the window we want to use for activating the files */
nautilus_application_open_location_full (NAUTILUS_APPLICATION (g_application_get_default ()),
location_with_permissions, flags, NULL, NULL, parameters->slot);
/* close only the window from which the action was launched and then open
* tabs/windows (depending on parameters->flags) */
if (!closed_window && (flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0)
{
flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND);
/* if NEW_WINDOW is set, we want all files in new windows, not in tabs */
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0)
{
flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW);
flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB;
}
closed_window = TRUE;
}
}
}
if (open_in_app_uris != NULL)
{
open_in_app_parameters = make_activation_parameters (g_queue_peek_head_link (open_in_app_uris),
&unhandled_open_in_app_uris);
}
num_apps = g_list_length (open_in_app_parameters);
num_unhandled = g_list_length (unhandled_open_in_app_uris);
num_files = g_queue_get_length (open_in_app_uris);
open_files = TRUE;
if (g_queue_is_empty (open_in_app_uris) &&
(!parameters->user_confirmation ||
num_files + num_unhandled > SILENT_OPEN_LIMIT) &&
num_apps > 1)
{
GtkDialog *dialog;
char *prompt;
g_autofree char *detail = NULL;
int response;
pause_activation_timed_cancel (parameters);
prompt = _("Are you sure you want to open all files?");
detail = g_strdup_printf (ngettext ("This will open %d separate application.",
"This will open %d separate applications.", num_apps), num_apps);
dialog = eel_show_yes_no_dialog (prompt, detail,
_("_OK"), _("_Cancel"),
parameters->parent_window);
response = gtk_dialog_run (dialog);
gtk_widget_destroy (GTK_WIDGET (dialog));
unpause_activation_timed_cancel (parameters);
if (response != GTK_RESPONSE_YES)
{
open_files = FALSE;
}
}
if (open_files)
{
for (l = open_in_app_parameters; l != NULL; l = l->next)
{
one_parameters = l->data;
nautilus_launch_application_by_uri (one_parameters->application,
one_parameters->uris,
parameters->parent_window);
application_launch_parameters_free (one_parameters);
}
for (l = unhandled_open_in_app_uris; l != NULL; l = l->next)
{
char *uri = l->data;
/* this does not block */
application_unhandled_uri (parameters, uri);
}
}
window = NULL;
if (parameters->slot != NULL)
{
window = nautilus_window_slot_get_window (parameters->slot);
}
if (open_in_app_parameters != NULL ||
unhandled_open_in_app_uris != NULL)
{
if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0 &&
window != NULL)
{
nautilus_window_close (window);
}
}
activation_parameters_free (parameters);
}
static void
activation_mount_not_mounted_callback (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
ActivateParameters *parameters = user_data;
GError *error;
NautilusFile *file;
LaunchLocation *loc;
file = parameters->not_mounted->data;
error = NULL;
if (!g_file_mount_enclosing_volume_finish (G_FILE (source_object), res, &error))
{
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_CANCELLED &&
error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED))
{
eel_show_error_dialog (_("Unable to access location"), error->message, parameters->parent_window);
}
if (error->domain != G_IO_ERROR ||
error->code != G_IO_ERROR_ALREADY_MOUNTED)
{
loc = find_launch_location_for_file (parameters->locations,
file);
if (loc)
{
parameters->locations =
g_list_remove (parameters->locations, loc);
launch_location_free (loc);
}
}
g_error_free (error);
}
parameters->not_mounted = g_list_delete_link (parameters->not_mounted,
parameters->not_mounted);
nautilus_file_unref (file);
activation_mount_not_mounted (parameters);
}
static void
activation_mount_not_mounted (ActivateParameters *parameters)
{
NautilusFile *file;
GFile *location;
LaunchLocation *loc;
GMountOperation *mount_op;
GList *l, *next, *files;
if (parameters->not_mounted != NULL)
{
file = parameters->not_mounted->data;
mount_op = gtk_mount_operation_new (parameters->parent_window);
g_mount_operation_set_password_save (mount_op, G_PASSWORD_SAVE_FOR_SESSION);
g_signal_connect (mount_op, "notify::is-showing",
G_CALLBACK (activate_mount_op_active), parameters);
location = nautilus_file_get_location (file);
g_file_mount_enclosing_volume (location, 0, mount_op, parameters->cancellable,
activation_mount_not_mounted_callback, parameters);
g_object_unref (location);
/* unref mount_op here - g_file_mount_enclosing_volume() does ref for itself */
g_object_unref (mount_op);
return;
}
parameters->tried_mounting = TRUE;
if (parameters->locations == NULL)
{
activation_parameters_free (parameters);
return;
}
/* once the mount is finished, refresh all attributes */
/* - fixes new windows not appearing after successful mount */
for (l = parameters->locations; l != NULL; l = next)
{
loc = l->data;
next = l->next;
nautilus_file_invalidate_all_attributes (loc->file);
}
files = get_file_list_for_launch_locations (parameters->locations);
nautilus_file_list_call_when_ready
(files,
nautilus_mime_actions_get_required_file_attributes (),
¶meters->files_handle,
activate_callback, parameters);
nautilus_file_list_free (files);
}
static void
activate_callback (GList *files,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
GList *l, *next;
NautilusFile *file;
LaunchLocation *location;
parameters->files_handle = NULL;
for (l = parameters->locations; l != NULL; l = next)
{
location = l->data;
file = location->file;
next = l->next;
if (file_was_cancelled (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
if (file_was_not_mounted (file))
{
if (parameters->tried_mounting)
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
}
else
{
parameters->not_mounted = g_list_prepend (parameters->not_mounted,
nautilus_file_ref (file));
}
continue;
}
}
if (parameters->not_mounted != NULL)
{
activation_mount_not_mounted (parameters);
}
else
{
activate_files (parameters);
}
}
static void
activate_activation_uris_ready_callback (GList *files_ignore,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
GList *l, *next, *files;
NautilusFile *file;
LaunchLocation *location;
parameters->files_handle = NULL;
for (l = parameters->locations; l != NULL; l = next)
{
location = l->data;
file = location->file;
next = l->next;
if (file_was_cancelled (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
if (nautilus_file_is_broken_symbolic_link (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
pause_activation_timed_cancel (parameters);
report_broken_symbolic_link (parameters->parent_window, file);
unpause_activation_timed_cancel (parameters);
continue;
}
if (nautilus_file_get_file_type (file) == G_FILE_TYPE_MOUNTABLE &&
!nautilus_file_has_activation_uri (file))
{
/* Don't launch these... There is nothing we
* can do */
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
}
if (parameters->locations == NULL)
{
activation_parameters_free (parameters);
return;
}
/* Convert the files to the actual activation uri files */
for (l = parameters->locations; l != NULL; l = l->next)
{
char *uri;
location = l->data;
/* We want the file for the activation URI since we care
* about the attributes for that, not for the original file.
*/
uri = nautilus_file_get_activation_uri (location->file);
if (uri != NULL)
{
launch_location_update_from_uri (location, uri);
}
g_free (uri);
}
/* get the parameters for the actual files */
files = get_file_list_for_launch_locations (parameters->locations);
nautilus_file_list_call_when_ready
(files,
nautilus_mime_actions_get_required_file_attributes (),
¶meters->files_handle,
activate_callback, parameters);
nautilus_file_list_free (files);
}
static void
activation_get_activation_uris (ActivateParameters *parameters)
{
GList *l, *files;
NautilusFile *file;
LaunchLocation *location;
/* link target info might be stale, re-read it */
for (l = parameters->locations; l != NULL; l = l->next)
{
location = l->data;
file = location->file;
if (file_was_cancelled (file))
{
launch_location_free (location);
parameters->locations = g_list_delete_link (parameters->locations, l);
continue;
}
}
if (parameters->locations == NULL)
{
activation_parameters_free (parameters);
return;
}
files = get_file_list_for_launch_locations (parameters->locations);
nautilus_file_list_call_when_ready
(files, nautilus_mime_actions_get_required_file_attributes (),
¶meters->files_handle,
activate_activation_uris_ready_callback, parameters);
nautilus_file_list_free (files);
}
static void
activation_mountable_mounted (NautilusFile *file,
GFile *result_location,
GError *error,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
NautilusFile *target_file;
LaunchLocation *location;
/* Remove from list of files that have to be mounted */
parameters->mountables = g_list_remove (parameters->mountables, file);
nautilus_file_unref (file);
if (error == NULL)
{
/* Replace file with the result of the mount */
target_file = nautilus_file_get (result_location);
location = find_launch_location_for_file (parameters->locations,
file);
if (location)
{
launch_location_update_from_file (location, target_file);
}
nautilus_file_unref (target_file);
}
else
{
/* Remove failed file */
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED))
{
location = find_launch_location_for_file (parameters->locations,
file);
if (location)
{
parameters->locations =
g_list_remove (parameters->locations,
location);
launch_location_free (location);
}
}
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_CANCELLED &&
error->code != G_IO_ERROR_FAILED_HANDLED &&
error->code != G_IO_ERROR_ALREADY_MOUNTED))
{
eel_show_error_dialog (_("Unable to access location"),
error->message, parameters->parent_window);
}
if (error->code == G_IO_ERROR_CANCELLED)
{
activation_parameters_free (parameters);
return;
}
}
/* Mount more mountables */
activation_mount_mountables (parameters);
}
static void
activation_mount_mountables (ActivateParameters *parameters)
{
NautilusFile *file;
GMountOperation *mount_op;
if (parameters->mountables != NULL)
{
file = parameters->mountables->data;
mount_op = gtk_mount_operation_new (parameters->parent_window);
g_mount_operation_set_password_save (mount_op, G_PASSWORD_SAVE_FOR_SESSION);
g_signal_connect (mount_op, "notify::is-showing",
G_CALLBACK (activate_mount_op_active), parameters);
nautilus_file_mount (file,
mount_op,
parameters->cancellable,
activation_mountable_mounted,
parameters);
g_object_unref (mount_op);
return;
}
if (parameters->mountables == NULL && parameters->start_mountables == NULL)
{
activation_get_activation_uris (parameters);
}
}
static void
activation_mountable_started (NautilusFile *file,
GFile *gfile_of_file,
GError *error,
gpointer callback_data)
{
ActivateParameters *parameters = callback_data;
LaunchLocation *location;
/* Remove from list of files that have to be mounted */
parameters->start_mountables = g_list_remove (parameters->start_mountables, file);
nautilus_file_unref (file);
if (error == NULL)
{
/* Remove file */
location = find_launch_location_for_file (parameters->locations, file);
if (location != NULL)
{
parameters->locations = g_list_remove (parameters->locations, location);
launch_location_free (location);
}
}
else
{
/* Remove failed file */
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_FAILED_HANDLED))
{
location = find_launch_location_for_file (parameters->locations,
file);
if (location)
{
parameters->locations =
g_list_remove (parameters->locations,
location);
launch_location_free (location);
}
}
if (error->domain != G_IO_ERROR ||
(error->code != G_IO_ERROR_CANCELLED &&
error->code != G_IO_ERROR_FAILED_HANDLED))
{
eel_show_error_dialog (_("Unable to start location"),
error->message, NULL);
}
if (error->code == G_IO_ERROR_CANCELLED)
{
activation_parameters_free (parameters);
return;
}
}
/* Start more mountables */
activation_start_mountables (parameters);
}
static void
activation_start_mountables (ActivateParameters *parameters)
{
NautilusFile *file;
GMountOperation *start_op;
if (parameters->start_mountables != NULL)
{
file = parameters->start_mountables->data;
start_op = gtk_mount_operation_new (parameters->parent_window);
g_signal_connect (start_op, "notify::is-showing",
G_CALLBACK (activate_mount_op_active), parameters);
nautilus_file_start (file,
start_op,
parameters->cancellable,
activation_mountable_started,
parameters);
g_object_unref (start_op);
return;
}
if (parameters->mountables == NULL && parameters->start_mountables == NULL)
{
activation_get_activation_uris (parameters);
}
}
/**
* nautilus_mime_activate_files:
*
* Activate a list of files. Each one might launch with an application or
* with a component. This is normally called only by subclasses.
* @view: FMDirectoryView in question.
* @files: A GList of NautilusFiles to activate.
*
**/
void
nautilus_mime_activate_files (GtkWindow *parent_window,
NautilusWindowSlot *slot,
GList *files,
const char *launch_directory,
NautilusWindowOpenFlags flags,
gboolean user_confirmation)
{
ActivateParameters *parameters;
char *file_name;
int file_count;
GList *l, *next;
NautilusFile *file;
LaunchLocation *location;
if (files == NULL)
{
return;
}
DEBUG_FILES (files, "Calling activate_files() with files:");
parameters = g_new0 (ActivateParameters, 1);
parameters->slot = slot;
g_object_add_weak_pointer (G_OBJECT (parameters->slot), (gpointer *) ¶meters->slot);
if (parent_window)
{
parameters->parent_window = parent_window;
g_object_add_weak_pointer (G_OBJECT (parameters->parent_window), (gpointer *) ¶meters->parent_window);
}
parameters->cancellable = g_cancellable_new ();
parameters->activation_directory = g_strdup (launch_directory);
parameters->locations = launch_locations_from_file_list (files);
parameters->flags = flags;
parameters->user_confirmation = user_confirmation;
file_count = g_list_length (files);
if (file_count == 1)
{
file_name = nautilus_file_get_display_name (files->data);
parameters->timed_wait_prompt = g_strdup_printf (_("Opening “%s”."), file_name);
g_free (file_name);
}
else
{
parameters->timed_wait_prompt = g_strdup_printf (ngettext ("Opening %d item.",
"Opening %d items.",
file_count),
file_count);
}
for (l = parameters->locations; l != NULL; l = next)
{
location = l->data;
file = location->file;
next = l->next;
if (nautilus_file_can_mount (file))
{
parameters->mountables = g_list_prepend (parameters->mountables,
nautilus_file_ref (file));
}
if (nautilus_file_can_start (file))
{
parameters->start_mountables = g_list_prepend (parameters->start_mountables,
nautilus_file_ref (file));
}
}
activation_start_timed_cancel (parameters);
if (parameters->mountables != NULL)
{
activation_mount_mountables (parameters);
}
if (parameters->start_mountables != NULL)
{
activation_start_mountables (parameters);
}
if (parameters->mountables == NULL && parameters->start_mountables == NULL)
{
activation_get_activation_uris (parameters);
}
}
/**
* nautilus_mime_activate_file:
*
* Activate a file in this view. This might involve switching the displayed
* location for the current window, or launching an application.
* @view: FMDirectoryView in question.
* @file: A NautilusFile representing the file in this view to activate.
* @use_new_window: Should this item be opened in a new window?
*
**/
void
nautilus_mime_activate_file (GtkWindow *parent_window,
NautilusWindowSlot *slot,
NautilusFile *file,
const char *launch_directory,
NautilusWindowOpenFlags flags)
{
GList *files;
g_return_if_fail (NAUTILUS_IS_FILE (file));
files = g_list_prepend (NULL, file);
nautilus_mime_activate_files (parent_window, slot, files, launch_directory, flags, FALSE);
g_list_free (files);
}
gint
nautilus_mime_types_get_number_of_groups (void)
{
return G_N_ELEMENTS (mimetype_groups);
}
const gchar *
nautilus_mime_types_group_get_name (gint group_index)
{
g_return_val_if_fail (group_index < G_N_ELEMENTS (mimetype_groups), NULL);
return gettext (mimetype_groups[group_index].name);
}
GList *
nautilus_mime_types_group_get_mimetypes (gint group_index)
{
GList *mimetypes;
gint i;
g_return_val_if_fail (group_index < G_N_ELEMENTS (mimetype_groups), NULL);
mimetypes = NULL;
/* Setup the new mimetypes set */
for (i = 0; mimetype_groups[group_index].mimetypes[i]; i++)
{
mimetypes = g_list_append (mimetypes, mimetype_groups[group_index].mimetypes[i]);
}
return mimetypes;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2802_5 |
crossvul-cpp_data_bad_5533_2 | /*
* Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "redis.h"
#ifdef HAVE_BACKTRACE
#include <execinfo.h>
#include <ucontext.h>
#endif /* HAVE_BACKTRACE */
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <pthread.h>
#include <sys/resource.h>
/* Our shared "common" objects */
struct sharedObjectsStruct shared;
/* Global vars that are actally used as constants. The following double
* values are used for double on-disk serialization, and are initialized
* at runtime to avoid strange compiler optimizations. */
double R_Zero, R_PosInf, R_NegInf, R_Nan;
/*================================= Globals ================================= */
/* Global vars */
struct redisServer server; /* server global state */
struct redisCommand *commandTable;
struct redisCommand readonlyCommandTable[] = {
{"get",getCommand,2,0,NULL,1,1,1},
{"set",setCommand,3,REDIS_CMD_DENYOOM,NULL,0,0,0},
{"setnx",setnxCommand,3,REDIS_CMD_DENYOOM,NULL,0,0,0},
{"setex",setexCommand,4,REDIS_CMD_DENYOOM,NULL,0,0,0},
{"append",appendCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"strlen",strlenCommand,2,0,NULL,1,1,1},
{"del",delCommand,-2,0,NULL,0,0,0},
{"exists",existsCommand,2,0,NULL,1,1,1},
{"setbit",setbitCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"getbit",getbitCommand,3,0,NULL,1,1,1},
{"setrange",setrangeCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"getrange",getrangeCommand,4,0,NULL,1,1,1},
{"substr",getrangeCommand,4,0,NULL,1,1,1},
{"incr",incrCommand,2,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"decr",decrCommand,2,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"mget",mgetCommand,-2,0,NULL,1,-1,1},
{"rpush",rpushCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"lpush",lpushCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"rpushx",rpushxCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"lpushx",lpushxCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"linsert",linsertCommand,5,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"rpop",rpopCommand,2,0,NULL,1,1,1},
{"lpop",lpopCommand,2,0,NULL,1,1,1},
{"brpop",brpopCommand,-3,0,NULL,1,1,1},
{"brpoplpush",brpoplpushCommand,4,REDIS_CMD_DENYOOM,NULL,1,2,1},
{"blpop",blpopCommand,-3,0,NULL,1,1,1},
{"llen",llenCommand,2,0,NULL,1,1,1},
{"lindex",lindexCommand,3,0,NULL,1,1,1},
{"lset",lsetCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"lrange",lrangeCommand,4,0,NULL,1,1,1},
{"ltrim",ltrimCommand,4,0,NULL,1,1,1},
{"lrem",lremCommand,4,0,NULL,1,1,1},
{"rpoplpush",rpoplpushCommand,3,REDIS_CMD_DENYOOM,NULL,1,2,1},
{"sadd",saddCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"srem",sremCommand,3,0,NULL,1,1,1},
{"smove",smoveCommand,4,0,NULL,1,2,1},
{"sismember",sismemberCommand,3,0,NULL,1,1,1},
{"scard",scardCommand,2,0,NULL,1,1,1},
{"spop",spopCommand,2,0,NULL,1,1,1},
{"srandmember",srandmemberCommand,2,0,NULL,1,1,1},
{"sinter",sinterCommand,-2,REDIS_CMD_DENYOOM,NULL,1,-1,1},
{"sinterstore",sinterstoreCommand,-3,REDIS_CMD_DENYOOM,NULL,2,-1,1},
{"sunion",sunionCommand,-2,REDIS_CMD_DENYOOM,NULL,1,-1,1},
{"sunionstore",sunionstoreCommand,-3,REDIS_CMD_DENYOOM,NULL,2,-1,1},
{"sdiff",sdiffCommand,-2,REDIS_CMD_DENYOOM,NULL,1,-1,1},
{"sdiffstore",sdiffstoreCommand,-3,REDIS_CMD_DENYOOM,NULL,2,-1,1},
{"smembers",sinterCommand,2,0,NULL,1,1,1},
{"zadd",zaddCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"zincrby",zincrbyCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"zrem",zremCommand,3,0,NULL,1,1,1},
{"zremrangebyscore",zremrangebyscoreCommand,4,0,NULL,1,1,1},
{"zremrangebyrank",zremrangebyrankCommand,4,0,NULL,1,1,1},
{"zunionstore",zunionstoreCommand,-4,REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
{"zinterstore",zinterstoreCommand,-4,REDIS_CMD_DENYOOM,zunionInterBlockClientOnSwappedKeys,0,0,0},
{"zrange",zrangeCommand,-4,0,NULL,1,1,1},
{"zrangebyscore",zrangebyscoreCommand,-4,0,NULL,1,1,1},
{"zrevrangebyscore",zrevrangebyscoreCommand,-4,0,NULL,1,1,1},
{"zcount",zcountCommand,4,0,NULL,1,1,1},
{"zrevrange",zrevrangeCommand,-4,0,NULL,1,1,1},
{"zcard",zcardCommand,2,0,NULL,1,1,1},
{"zscore",zscoreCommand,3,0,NULL,1,1,1},
{"zrank",zrankCommand,3,0,NULL,1,1,1},
{"zrevrank",zrevrankCommand,3,0,NULL,1,1,1},
{"hset",hsetCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"hsetnx",hsetnxCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"hget",hgetCommand,3,0,NULL,1,1,1},
{"hmset",hmsetCommand,-4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"hmget",hmgetCommand,-3,0,NULL,1,1,1},
{"hincrby",hincrbyCommand,4,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"hdel",hdelCommand,3,0,NULL,1,1,1},
{"hlen",hlenCommand,2,0,NULL,1,1,1},
{"hkeys",hkeysCommand,2,0,NULL,1,1,1},
{"hvals",hvalsCommand,2,0,NULL,1,1,1},
{"hgetall",hgetallCommand,2,0,NULL,1,1,1},
{"hexists",hexistsCommand,3,0,NULL,1,1,1},
{"incrby",incrbyCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"decrby",decrbyCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"getset",getsetCommand,3,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"mset",msetCommand,-3,REDIS_CMD_DENYOOM,NULL,1,-1,2},
{"msetnx",msetnxCommand,-3,REDIS_CMD_DENYOOM,NULL,1,-1,2},
{"randomkey",randomkeyCommand,1,0,NULL,0,0,0},
{"select",selectCommand,2,0,NULL,0,0,0},
{"move",moveCommand,3,0,NULL,1,1,1},
{"rename",renameCommand,3,0,NULL,1,1,1},
{"renamenx",renamenxCommand,3,0,NULL,1,1,1},
{"expire",expireCommand,3,0,NULL,0,0,0},
{"expireat",expireatCommand,3,0,NULL,0,0,0},
{"keys",keysCommand,2,0,NULL,0,0,0},
{"dbsize",dbsizeCommand,1,0,NULL,0,0,0},
{"auth",authCommand,2,0,NULL,0,0,0},
{"ping",pingCommand,1,0,NULL,0,0,0},
{"echo",echoCommand,2,0,NULL,0,0,0},
{"save",saveCommand,1,0,NULL,0,0,0},
{"bgsave",bgsaveCommand,1,0,NULL,0,0,0},
{"bgrewriteaof",bgrewriteaofCommand,1,0,NULL,0,0,0},
{"shutdown",shutdownCommand,1,0,NULL,0,0,0},
{"lastsave",lastsaveCommand,1,0,NULL,0,0,0},
{"type",typeCommand,2,0,NULL,1,1,1},
{"multi",multiCommand,1,0,NULL,0,0,0},
{"exec",execCommand,1,REDIS_CMD_DENYOOM,execBlockClientOnSwappedKeys,0,0,0},
{"discard",discardCommand,1,0,NULL,0,0,0},
{"sync",syncCommand,1,0,NULL,0,0,0},
{"flushdb",flushdbCommand,1,0,NULL,0,0,0},
{"flushall",flushallCommand,1,0,NULL,0,0,0},
{"sort",sortCommand,-2,REDIS_CMD_DENYOOM,NULL,1,1,1},
{"info",infoCommand,1,0,NULL,0,0,0},
{"monitor",monitorCommand,1,0,NULL,0,0,0},
{"ttl",ttlCommand,2,0,NULL,1,1,1},
{"persist",persistCommand,2,0,NULL,1,1,1},
{"slaveof",slaveofCommand,3,0,NULL,0,0,0},
{"debug",debugCommand,-2,0,NULL,0,0,0},
{"config",configCommand,-2,0,NULL,0,0,0},
{"subscribe",subscribeCommand,-2,0,NULL,0,0,0},
{"unsubscribe",unsubscribeCommand,-1,0,NULL,0,0,0},
{"psubscribe",psubscribeCommand,-2,0,NULL,0,0,0},
{"punsubscribe",punsubscribeCommand,-1,0,NULL,0,0,0},
{"publish",publishCommand,3,REDIS_CMD_FORCE_REPLICATION,NULL,0,0,0},
{"watch",watchCommand,-2,0,NULL,0,0,0},
{"unwatch",unwatchCommand,1,0,NULL,0,0,0}
};
/*============================ Utility functions ============================ */
void redisLog(int level, const char *fmt, ...) {
const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING };
const char *c = ".-*#";
time_t now = time(NULL);
va_list ap;
FILE *fp;
char buf[64];
char msg[REDIS_MAX_LOGMSG_LEN];
if (level < server.verbosity) return;
fp = (server.logfile == NULL) ? stdout : fopen(server.logfile,"a");
if (!fp) return;
va_start(ap, fmt);
vsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
strftime(buf,sizeof(buf),"%d %b %H:%M:%S",localtime(&now));
fprintf(fp,"[%d] %s %c %s\n",(int)getpid(),buf,c[level],msg);
fflush(fp);
if (server.logfile) fclose(fp);
if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg);
}
/* Redis generally does not try to recover from out of memory conditions
* when allocating objects or strings, it is not clear if it will be possible
* to report this condition to the client since the networking layer itself
* is based on heap allocation for send buffers, so we simply abort.
* At least the code will be simpler to read... */
void oom(const char *msg) {
redisLog(REDIS_WARNING, "%s: Out of memory\n",msg);
sleep(1);
abort();
}
/*====================== Hash table type implementation ==================== */
/* This is an hash table type that uses the SDS dynamic strings libary as
* keys and radis objects as values (objects can hold SDS strings,
* lists, sets). */
void dictVanillaFree(void *privdata, void *val)
{
DICT_NOTUSED(privdata);
zfree(val);
}
void dictListDestructor(void *privdata, void *val)
{
DICT_NOTUSED(privdata);
listRelease((list*)val);
}
int dictSdsKeyCompare(void *privdata, const void *key1,
const void *key2)
{
int l1,l2;
DICT_NOTUSED(privdata);
l1 = sdslen((sds)key1);
l2 = sdslen((sds)key2);
if (l1 != l2) return 0;
return memcmp(key1, key2, l1) == 0;
}
/* A case insensitive version used for the command lookup table. */
int dictSdsKeyCaseCompare(void *privdata, const void *key1,
const void *key2)
{
DICT_NOTUSED(privdata);
return strcasecmp(key1, key2) == 0;
}
void dictRedisObjectDestructor(void *privdata, void *val)
{
DICT_NOTUSED(privdata);
if (val == NULL) return; /* Values of swapped out keys as set to NULL */
decrRefCount(val);
}
void dictSdsDestructor(void *privdata, void *val)
{
DICT_NOTUSED(privdata);
sdsfree(val);
}
int dictObjKeyCompare(void *privdata, const void *key1,
const void *key2)
{
const robj *o1 = key1, *o2 = key2;
return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
}
unsigned int dictObjHash(const void *key) {
const robj *o = key;
return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
}
unsigned int dictSdsHash(const void *key) {
return dictGenHashFunction((unsigned char*)key, sdslen((char*)key));
}
unsigned int dictSdsCaseHash(const void *key) {
return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key));
}
int dictEncObjKeyCompare(void *privdata, const void *key1,
const void *key2)
{
robj *o1 = (robj*) key1, *o2 = (robj*) key2;
int cmp;
if (o1->encoding == REDIS_ENCODING_INT &&
o2->encoding == REDIS_ENCODING_INT)
return o1->ptr == o2->ptr;
o1 = getDecodedObject(o1);
o2 = getDecodedObject(o2);
cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr);
decrRefCount(o1);
decrRefCount(o2);
return cmp;
}
unsigned int dictEncObjHash(const void *key) {
robj *o = (robj*) key;
if (o->encoding == REDIS_ENCODING_RAW) {
return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
} else {
if (o->encoding == REDIS_ENCODING_INT) {
char buf[32];
int len;
len = ll2string(buf,32,(long)o->ptr);
return dictGenHashFunction((unsigned char*)buf, len);
} else {
unsigned int hash;
o = getDecodedObject(o);
hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr));
decrRefCount(o);
return hash;
}
}
}
/* Sets type */
dictType setDictType = {
dictEncObjHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictEncObjKeyCompare, /* key compare */
dictRedisObjectDestructor, /* key destructor */
NULL /* val destructor */
};
/* Sorted sets hash (note: a skiplist is used in addition to the hash table) */
dictType zsetDictType = {
dictEncObjHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictEncObjKeyCompare, /* key compare */
dictRedisObjectDestructor, /* key destructor */
NULL /* val destructor */
};
/* Db->dict, keys are sds strings, vals are Redis objects. */
dictType dbDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCompare, /* key compare */
dictSdsDestructor, /* key destructor */
dictRedisObjectDestructor /* val destructor */
};
/* Db->expires */
dictType keyptrDictType = {
dictSdsHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCompare, /* key compare */
NULL, /* key destructor */
NULL /* val destructor */
};
/* Command table. sds string -> command struct pointer. */
dictType commandTableDictType = {
dictSdsCaseHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictSdsKeyCaseCompare, /* key compare */
dictSdsDestructor, /* key destructor */
NULL /* val destructor */
};
/* Hash type hash table (note that small hashes are represented with zimpaps) */
dictType hashDictType = {
dictEncObjHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictEncObjKeyCompare, /* key compare */
dictRedisObjectDestructor, /* key destructor */
dictRedisObjectDestructor /* val destructor */
};
/* Keylist hash table type has unencoded redis objects as keys and
* lists as values. It's used for blocking operations (BLPOP) and to
* map swapped keys to a list of clients waiting for this keys to be loaded. */
dictType keylistDictType = {
dictObjHash, /* hash function */
NULL, /* key dup */
NULL, /* val dup */
dictObjKeyCompare, /* key compare */
dictRedisObjectDestructor, /* key destructor */
dictListDestructor /* val destructor */
};
int htNeedsResize(dict *dict) {
long long size, used;
size = dictSlots(dict);
used = dictSize(dict);
return (size && used && size > DICT_HT_INITIAL_SIZE &&
(used*100/size < REDIS_HT_MINFILL));
}
/* If the percentage of used slots in the HT reaches REDIS_HT_MINFILL
* we resize the hash table to save memory */
void tryResizeHashTables(void) {
int j;
for (j = 0; j < server.dbnum; j++) {
if (htNeedsResize(server.db[j].dict))
dictResize(server.db[j].dict);
if (htNeedsResize(server.db[j].expires))
dictResize(server.db[j].expires);
}
}
/* Our hash table implementation performs rehashing incrementally while
* we write/read from the hash table. Still if the server is idle, the hash
* table will use two tables for a long time. So we try to use 1 millisecond
* of CPU time at every serverCron() loop in order to rehash some key. */
void incrementallyRehash(void) {
int j;
for (j = 0; j < server.dbnum; j++) {
if (dictIsRehashing(server.db[j].dict)) {
dictRehashMilliseconds(server.db[j].dict,1);
break; /* already used our millisecond for this loop... */
}
}
}
/* This function is called once a background process of some kind terminates,
* as we want to avoid resizing the hash tables when there is a child in order
* to play well with copy-on-write (otherwise when a resize happens lots of
* memory pages are copied). The goal of this function is to update the ability
* for dict.c to resize the hash tables accordingly to the fact we have o not
* running childs. */
void updateDictResizePolicy(void) {
if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1)
dictEnableResize();
else
dictDisableResize();
}
/* ======================= Cron: called every 100 ms ======================== */
/* Try to expire a few timed out keys. The algorithm used is adaptive and
* will use few CPU cycles if there are few expiring keys, otherwise
* it will get more aggressive to avoid that too much memory is used by
* keys that can be removed from the keyspace. */
void activeExpireCycle(void) {
int j;
for (j = 0; j < server.dbnum; j++) {
int expired;
redisDb *db = server.db+j;
/* Continue to expire if at the end of the cycle more than 25%
* of the keys were expired. */
do {
long num = dictSize(db->expires);
time_t now = time(NULL);
expired = 0;
if (num > REDIS_EXPIRELOOKUPS_PER_CRON)
num = REDIS_EXPIRELOOKUPS_PER_CRON;
while (num--) {
dictEntry *de;
time_t t;
if ((de = dictGetRandomKey(db->expires)) == NULL) break;
t = (time_t) dictGetEntryVal(de);
if (now > t) {
sds key = dictGetEntryKey(de);
robj *keyobj = createStringObject(key,sdslen(key));
propagateExpire(db,keyobj);
dbDelete(db,keyobj);
decrRefCount(keyobj);
expired++;
server.stat_expiredkeys++;
}
}
} while (expired > REDIS_EXPIRELOOKUPS_PER_CRON/4);
}
}
void updateLRUClock(void) {
server.lruclock = (time(NULL)/REDIS_LRU_CLOCK_RESOLUTION) &
REDIS_LRU_CLOCK_MAX;
}
int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) {
int j, loops = server.cronloops++;
REDIS_NOTUSED(eventLoop);
REDIS_NOTUSED(id);
REDIS_NOTUSED(clientData);
/* We take a cached value of the unix time in the global state because
* with virtual memory and aging there is to store the current time
* in objects at every object access, and accuracy is not needed.
* To access a global var is faster than calling time(NULL) */
server.unixtime = time(NULL);
/* We have just 22 bits per object for LRU information.
* So we use an (eventually wrapping) LRU clock with 10 seconds resolution.
* 2^22 bits with 10 seconds resoluton is more or less 1.5 years.
*
* Note that even if this will wrap after 1.5 years it's not a problem,
* everything will still work but just some object will appear younger
* to Redis. But for this to happen a given object should never be touched
* for 1.5 years.
*
* Note that you can change the resolution altering the
* REDIS_LRU_CLOCK_RESOLUTION define.
*/
updateLRUClock();
/* We received a SIGTERM, shutting down here in a safe way, as it is
* not ok doing so inside the signal handler. */
if (server.shutdown_asap) {
if (prepareForShutdown() == REDIS_OK) exit(0);
redisLog(REDIS_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information");
}
/* Show some info about non-empty databases */
for (j = 0; j < server.dbnum; j++) {
long long size, used, vkeys;
size = dictSlots(server.db[j].dict);
used = dictSize(server.db[j].dict);
vkeys = dictSize(server.db[j].expires);
if (!(loops % 50) && (used || vkeys)) {
redisLog(REDIS_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size);
/* dictPrintStats(server.dict); */
}
}
/* We don't want to resize the hash tables while a bacground saving
* is in progress: the saving child is created using fork() that is
* implemented with a copy-on-write semantic in most modern systems, so
* if we resize the HT while there is the saving child at work actually
* a lot of memory movements in the parent will cause a lot of pages
* copied. */
if (server.bgsavechildpid == -1 && server.bgrewritechildpid == -1) {
if (!(loops % 10)) tryResizeHashTables();
if (server.activerehashing) incrementallyRehash();
}
/* Show information about connected clients */
if (!(loops % 50)) {
redisLog(REDIS_VERBOSE,"%d clients connected (%d slaves), %zu bytes in use",
listLength(server.clients)-listLength(server.slaves),
listLength(server.slaves),
zmalloc_used_memory());
}
/* Close connections of timedout clients */
if ((server.maxidletime && !(loops % 100)) || server.bpop_blocked_clients)
closeTimedoutClients();
/* Check if a background saving or AOF rewrite in progress terminated */
if (server.bgsavechildpid != -1 || server.bgrewritechildpid != -1) {
int statloc;
pid_t pid;
if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) {
if (pid == server.bgsavechildpid) {
backgroundSaveDoneHandler(statloc);
} else {
backgroundRewriteDoneHandler(statloc);
}
updateDictResizePolicy();
}
} else {
/* If there is not a background saving in progress check if
* we have to save now */
time_t now = time(NULL);
for (j = 0; j < server.saveparamslen; j++) {
struct saveparam *sp = server.saveparams+j;
if (server.dirty >= sp->changes &&
now-server.lastsave > sp->seconds) {
redisLog(REDIS_NOTICE,"%d changes in %d seconds. Saving...",
sp->changes, sp->seconds);
rdbSaveBackground(server.dbfilename);
break;
}
}
}
/* Expire a few keys per cycle, only if this is a master.
* On slaves we wait for DEL operations synthesized by the master
* in order to guarantee a strict consistency. */
if (server.masterhost == NULL) activeExpireCycle();
/* Swap a few keys on disk if we are over the memory limit and VM
* is enbled. Try to free objects from the free list first. */
if (vmCanSwapOut()) {
while (server.vm_enabled && zmalloc_used_memory() >
server.vm_max_memory)
{
int retval = (server.vm_max_threads == 0) ?
vmSwapOneObjectBlocking() :
vmSwapOneObjectThreaded();
if (retval == REDIS_ERR && !(loops % 300) &&
zmalloc_used_memory() >
(server.vm_max_memory+server.vm_max_memory/10))
{
redisLog(REDIS_WARNING,"WARNING: vm-max-memory limit exceeded by more than 10%% but unable to swap more objects out!");
}
/* Note that when using threade I/O we free just one object,
* because anyway when the I/O thread in charge to swap this
* object out will finish, the handler of completed jobs
* will try to swap more objects if we are still out of memory. */
if (retval == REDIS_ERR || server.vm_max_threads > 0) break;
}
}
/* Replication cron function -- used to reconnect to master and
* to detect transfer failures. */
if (!(loops % 10)) replicationCron();
return 100;
}
/* This function gets called every time Redis is entering the
* main loop of the event driven library, that is, before to sleep
* for ready file descriptors. */
void beforeSleep(struct aeEventLoop *eventLoop) {
REDIS_NOTUSED(eventLoop);
listNode *ln;
redisClient *c;
/* Awake clients that got all the swapped keys they requested */
if (server.vm_enabled && listLength(server.io_ready_clients)) {
listIter li;
listRewind(server.io_ready_clients,&li);
while((ln = listNext(&li))) {
c = ln->value;
struct redisCommand *cmd;
/* Resume the client. */
listDelNode(server.io_ready_clients,ln);
c->flags &= (~REDIS_IO_WAIT);
server.vm_blocked_clients--;
aeCreateFileEvent(server.el, c->fd, AE_READABLE,
readQueryFromClient, c);
cmd = lookupCommand(c->argv[0]->ptr);
redisAssert(cmd != NULL);
call(c,cmd);
resetClient(c);
/* There may be more data to process in the input buffer. */
if (c->querybuf && sdslen(c->querybuf) > 0)
processInputBuffer(c);
}
}
/* Try to process pending commands for clients that were just unblocked. */
while (listLength(server.unblocked_clients)) {
ln = listFirst(server.unblocked_clients);
redisAssert(ln != NULL);
c = ln->value;
listDelNode(server.unblocked_clients,ln);
/* Process remaining data in the input buffer. */
if (c->querybuf && sdslen(c->querybuf) > 0)
processInputBuffer(c);
}
/* Write the AOF buffer on disk */
flushAppendOnlyFile();
}
/* =========================== Server initialization ======================== */
void createSharedObjects(void) {
int j;
shared.crlf = createObject(REDIS_STRING,sdsnew("\r\n"));
shared.ok = createObject(REDIS_STRING,sdsnew("+OK\r\n"));
shared.err = createObject(REDIS_STRING,sdsnew("-ERR\r\n"));
shared.emptybulk = createObject(REDIS_STRING,sdsnew("$0\r\n\r\n"));
shared.czero = createObject(REDIS_STRING,sdsnew(":0\r\n"));
shared.cone = createObject(REDIS_STRING,sdsnew(":1\r\n"));
shared.cnegone = createObject(REDIS_STRING,sdsnew(":-1\r\n"));
shared.nullbulk = createObject(REDIS_STRING,sdsnew("$-1\r\n"));
shared.nullmultibulk = createObject(REDIS_STRING,sdsnew("*-1\r\n"));
shared.emptymultibulk = createObject(REDIS_STRING,sdsnew("*0\r\n"));
shared.pong = createObject(REDIS_STRING,sdsnew("+PONG\r\n"));
shared.queued = createObject(REDIS_STRING,sdsnew("+QUEUED\r\n"));
shared.wrongtypeerr = createObject(REDIS_STRING,sdsnew(
"-ERR Operation against a key holding the wrong kind of value\r\n"));
shared.nokeyerr = createObject(REDIS_STRING,sdsnew(
"-ERR no such key\r\n"));
shared.syntaxerr = createObject(REDIS_STRING,sdsnew(
"-ERR syntax error\r\n"));
shared.sameobjecterr = createObject(REDIS_STRING,sdsnew(
"-ERR source and destination objects are the same\r\n"));
shared.outofrangeerr = createObject(REDIS_STRING,sdsnew(
"-ERR index out of range\r\n"));
shared.loadingerr = createObject(REDIS_STRING,sdsnew(
"-LOADING Redis is loading the dataset in memory\r\n"));
shared.space = createObject(REDIS_STRING,sdsnew(" "));
shared.colon = createObject(REDIS_STRING,sdsnew(":"));
shared.plus = createObject(REDIS_STRING,sdsnew("+"));
shared.select0 = createStringObject("select 0\r\n",10);
shared.select1 = createStringObject("select 1\r\n",10);
shared.select2 = createStringObject("select 2\r\n",10);
shared.select3 = createStringObject("select 3\r\n",10);
shared.select4 = createStringObject("select 4\r\n",10);
shared.select5 = createStringObject("select 5\r\n",10);
shared.select6 = createStringObject("select 6\r\n",10);
shared.select7 = createStringObject("select 7\r\n",10);
shared.select8 = createStringObject("select 8\r\n",10);
shared.select9 = createStringObject("select 9\r\n",10);
shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13);
shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14);
shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15);
shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18);
shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17);
shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19);
shared.mbulk3 = createStringObject("*3\r\n",4);
shared.mbulk4 = createStringObject("*4\r\n",4);
for (j = 0; j < REDIS_SHARED_INTEGERS; j++) {
shared.integers[j] = createObject(REDIS_STRING,(void*)(long)j);
shared.integers[j]->encoding = REDIS_ENCODING_INT;
}
}
void initServerConfig() {
server.port = REDIS_SERVERPORT;
server.bindaddr = NULL;
server.unixsocket = NULL;
server.ipfd = -1;
server.sofd = -1;
server.dbnum = REDIS_DEFAULT_DBNUM;
server.verbosity = REDIS_VERBOSE;
server.maxidletime = REDIS_MAXIDLETIME;
server.saveparams = NULL;
server.loading = 0;
server.logfile = NULL; /* NULL = log on standard output */
server.syslog_enabled = 0;
server.syslog_ident = zstrdup("redis");
server.syslog_facility = LOG_LOCAL0;
server.glueoutputbuf = 1;
server.daemonize = 0;
server.appendonly = 0;
server.appendfsync = APPENDFSYNC_EVERYSEC;
server.no_appendfsync_on_rewrite = 0;
server.lastfsync = time(NULL);
server.appendfd = -1;
server.appendseldb = -1; /* Make sure the first time will not match */
server.pidfile = zstrdup("/var/run/redis.pid");
server.dbfilename = zstrdup("dump.rdb");
server.appendfilename = zstrdup("appendonly.aof");
server.requirepass = NULL;
server.rdbcompression = 1;
server.activerehashing = 1;
server.maxclients = 0;
server.bpop_blocked_clients = 0;
server.maxmemory = 0;
server.maxmemory_policy = REDIS_MAXMEMORY_VOLATILE_LRU;
server.maxmemory_samples = 3;
server.vm_enabled = 0;
server.vm_swap_file = zstrdup("/tmp/redis-%p.vm");
server.vm_page_size = 256; /* 256 bytes per page */
server.vm_pages = 1024*1024*100; /* 104 millions of pages */
server.vm_max_memory = 1024LL*1024*1024*1; /* 1 GB of RAM */
server.vm_max_threads = 4;
server.vm_blocked_clients = 0;
server.hash_max_zipmap_entries = REDIS_HASH_MAX_ZIPMAP_ENTRIES;
server.hash_max_zipmap_value = REDIS_HASH_MAX_ZIPMAP_VALUE;
server.list_max_ziplist_entries = REDIS_LIST_MAX_ZIPLIST_ENTRIES;
server.list_max_ziplist_value = REDIS_LIST_MAX_ZIPLIST_VALUE;
server.set_max_intset_entries = REDIS_SET_MAX_INTSET_ENTRIES;
server.shutdown_asap = 0;
updateLRUClock();
resetServerSaveParams();
appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */
appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */
appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */
/* Replication related */
server.isslave = 0;
server.masterauth = NULL;
server.masterhost = NULL;
server.masterport = 6379;
server.master = NULL;
server.replstate = REDIS_REPL_NONE;
server.repl_serve_stale_data = 1;
/* Double constants initialization */
R_Zero = 0.0;
R_PosInf = 1.0/R_Zero;
R_NegInf = -1.0/R_Zero;
R_Nan = R_Zero/R_Zero;
/* Command table -- we intiialize it here as it is part of the
* initial configuration, since command names may be changed via
* redis.conf using the rename-command directive. */
server.commands = dictCreate(&commandTableDictType,NULL);
populateCommandTable();
server.delCommand = lookupCommandByCString("del");
server.multiCommand = lookupCommandByCString("multi");
}
void initServer() {
int j;
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
setupSigSegvAction();
if (server.syslog_enabled) {
openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT,
server.syslog_facility);
}
server.mainthread = pthread_self();
server.clients = listCreate();
server.slaves = listCreate();
server.monitors = listCreate();
server.unblocked_clients = listCreate();
createSharedObjects();
server.el = aeCreateEventLoop();
server.db = zmalloc(sizeof(redisDb)*server.dbnum);
server.ipfd = anetTcpServer(server.neterr,server.port,server.bindaddr);
if (server.ipfd == ANET_ERR) {
redisLog(REDIS_WARNING, "Opening port: %s", server.neterr);
exit(1);
}
if (server.unixsocket != NULL) {
unlink(server.unixsocket); /* don't care if this fails */
server.sofd = anetUnixServer(server.neterr,server.unixsocket);
if (server.sofd == ANET_ERR) {
redisLog(REDIS_WARNING, "Opening socket: %s", server.neterr);
exit(1);
}
}
if (server.ipfd < 0 && server.sofd < 0) {
redisLog(REDIS_WARNING, "Configured to not listen anywhere, exiting.");
exit(1);
}
for (j = 0; j < server.dbnum; j++) {
server.db[j].dict = dictCreate(&dbDictType,NULL);
server.db[j].expires = dictCreate(&keyptrDictType,NULL);
server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL);
server.db[j].watched_keys = dictCreate(&keylistDictType,NULL);
if (server.vm_enabled)
server.db[j].io_keys = dictCreate(&keylistDictType,NULL);
server.db[j].id = j;
}
server.pubsub_channels = dictCreate(&keylistDictType,NULL);
server.pubsub_patterns = listCreate();
listSetFreeMethod(server.pubsub_patterns,freePubsubPattern);
listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern);
server.cronloops = 0;
server.bgsavechildpid = -1;
server.bgrewritechildpid = -1;
server.bgrewritebuf = sdsempty();
server.aofbuf = sdsempty();
server.lastsave = time(NULL);
server.dirty = 0;
server.stat_numcommands = 0;
server.stat_numconnections = 0;
server.stat_expiredkeys = 0;
server.stat_evictedkeys = 0;
server.stat_starttime = time(NULL);
server.stat_keyspace_misses = 0;
server.stat_keyspace_hits = 0;
server.unixtime = time(NULL);
aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL);
if (server.ipfd > 0 && aeCreateFileEvent(server.el,server.ipfd,AE_READABLE,
acceptTcpHandler,NULL) == AE_ERR) oom("creating file event");
if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE,
acceptUnixHandler,NULL) == AE_ERR) oom("creating file event");
if (server.appendonly) {
server.appendfd = open(server.appendfilename,O_WRONLY|O_APPEND|O_CREAT,0644);
if (server.appendfd == -1) {
redisLog(REDIS_WARNING, "Can't open the append-only file: %s",
strerror(errno));
exit(1);
}
}
if (server.vm_enabled) vmInit();
}
/* Populates the Redis Command Table starting from the hard coded list
* we have on top of redis.c file. */
void populateCommandTable(void) {
int j;
int numcommands = sizeof(readonlyCommandTable)/sizeof(struct redisCommand);
for (j = 0; j < numcommands; j++) {
struct redisCommand *c = readonlyCommandTable+j;
int retval;
retval = dictAdd(server.commands, sdsnew(c->name), c);
assert(retval == DICT_OK);
}
}
/* ====================== Commands lookup and execution ===================== */
struct redisCommand *lookupCommand(sds name) {
return dictFetchValue(server.commands, name);
}
struct redisCommand *lookupCommandByCString(char *s) {
struct redisCommand *cmd;
sds name = sdsnew(s);
cmd = dictFetchValue(server.commands, name);
sdsfree(name);
return cmd;
}
/* Call() is the core of Redis execution of a command */
void call(redisClient *c, struct redisCommand *cmd) {
long long dirty;
dirty = server.dirty;
cmd->proc(c);
dirty = server.dirty-dirty;
if (server.appendonly && dirty)
feedAppendOnlyFile(cmd,c->db->id,c->argv,c->argc);
if ((dirty || cmd->flags & REDIS_CMD_FORCE_REPLICATION) &&
listLength(server.slaves))
replicationFeedSlaves(server.slaves,c->db->id,c->argv,c->argc);
if (listLength(server.monitors))
replicationFeedMonitors(server.monitors,c->db->id,c->argv,c->argc);
server.stat_numcommands++;
}
/* If this function gets called we already read a whole
* command, argments are in the client argv/argc fields.
* processCommand() execute the command or prepare the
* server for a bulk read from the client.
*
* If 1 is returned the client is still alive and valid and
* and other operations can be performed by the caller. Otherwise
* if 0 is returned the client was destroied (i.e. after QUIT). */
int processCommand(redisClient *c) {
struct redisCommand *cmd;
/* The QUIT command is handled separately. Normal command procs will
* go through checking for replication and QUIT will cause trouble
* when FORCE_REPLICATION is enabled and would be implemented in
* a regular command proc. */
if (!strcasecmp(c->argv[0]->ptr,"quit")) {
addReply(c,shared.ok);
c->flags |= REDIS_CLOSE_AFTER_REPLY;
return REDIS_ERR;
}
/* Now lookup the command and check ASAP about trivial error conditions
* such wrong arity, bad command name and so forth. */
cmd = lookupCommand(c->argv[0]->ptr);
if (!cmd) {
addReplyErrorFormat(c,"unknown command '%s'",
(char*)c->argv[0]->ptr);
return REDIS_OK;
} else if ((cmd->arity > 0 && cmd->arity != c->argc) ||
(c->argc < -cmd->arity)) {
addReplyErrorFormat(c,"wrong number of arguments for '%s' command",
cmd->name);
return REDIS_OK;
}
/* Check if the user is authenticated */
if (server.requirepass && !c->authenticated && cmd->proc != authCommand) {
addReplyError(c,"operation not permitted");
return REDIS_OK;
}
/* Handle the maxmemory directive.
*
* First we try to free some memory if possible (if there are volatile
* keys in the dataset). If there are not the only thing we can do
* is returning an error. */
if (server.maxmemory) freeMemoryIfNeeded();
if (server.maxmemory && (cmd->flags & REDIS_CMD_DENYOOM) &&
zmalloc_used_memory() > server.maxmemory)
{
addReplyError(c,"command not allowed when used memory > 'maxmemory'");
return REDIS_OK;
}
/* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */
if ((dictSize(c->pubsub_channels) > 0 || listLength(c->pubsub_patterns) > 0)
&&
cmd->proc != subscribeCommand && cmd->proc != unsubscribeCommand &&
cmd->proc != psubscribeCommand && cmd->proc != punsubscribeCommand) {
addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / QUIT allowed in this context");
return REDIS_OK;
}
/* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and
* we are a slave with a broken link with master. */
if (server.masterhost && server.replstate != REDIS_REPL_CONNECTED &&
server.repl_serve_stale_data == 0 &&
cmd->proc != infoCommand && cmd->proc != slaveofCommand)
{
addReplyError(c,
"link with MASTER is down and slave-serve-stale-data is set to no");
return REDIS_OK;
}
/* Loading DB? Return an error if the command is not INFO */
if (server.loading && cmd->proc != infoCommand) {
addReply(c, shared.loadingerr);
return REDIS_OK;
}
/* Exec the command */
if (c->flags & REDIS_MULTI &&
cmd->proc != execCommand && cmd->proc != discardCommand &&
cmd->proc != multiCommand && cmd->proc != watchCommand)
{
queueMultiCommand(c,cmd);
addReply(c,shared.queued);
} else {
if (server.vm_enabled && server.vm_max_threads > 0 &&
blockClientOnSwappedKeys(c,cmd)) return REDIS_ERR;
call(c,cmd);
}
return REDIS_OK;
}
/*================================== Shutdown =============================== */
int prepareForShutdown() {
redisLog(REDIS_WARNING,"User requested shutdown, saving DB...");
/* Kill the saving child if there is a background saving in progress.
We want to avoid race conditions, for instance our saving child may
overwrite the synchronous saving did by SHUTDOWN. */
if (server.bgsavechildpid != -1) {
redisLog(REDIS_WARNING,"There is a live saving child. Killing it!");
kill(server.bgsavechildpid,SIGKILL);
rdbRemoveTempFile(server.bgsavechildpid);
}
if (server.appendonly) {
/* Append only file: fsync() the AOF and exit */
aof_fsync(server.appendfd);
if (server.vm_enabled) unlink(server.vm_swap_file);
} else if (server.saveparamslen > 0) {
/* Snapshotting. Perform a SYNC SAVE and exit */
if (rdbSave(server.dbfilename) != REDIS_OK) {
/* Ooops.. error saving! The best we can do is to continue
* operating. Note that if there was a background saving process,
* in the next cron() Redis will be notified that the background
* saving aborted, handling special stuff like slaves pending for
* synchronization... */
redisLog(REDIS_WARNING,"Error trying to save the DB, can't exit");
return REDIS_ERR;
}
} else {
redisLog(REDIS_WARNING,"Not saving DB.");
}
if (server.daemonize) unlink(server.pidfile);
redisLog(REDIS_WARNING,"Server exit now, bye bye...");
return REDIS_OK;
}
/*================================== Commands =============================== */
void authCommand(redisClient *c) {
if (!server.requirepass || !strcmp(c->argv[1]->ptr, server.requirepass)) {
c->authenticated = 1;
addReply(c,shared.ok);
} else {
c->authenticated = 0;
addReplyError(c,"invalid password");
}
}
void pingCommand(redisClient *c) {
addReply(c,shared.pong);
}
void echoCommand(redisClient *c) {
addReplyBulk(c,c->argv[1]);
}
/* Convert an amount of bytes into a human readable string in the form
* of 100B, 2G, 100M, 4K, and so forth. */
void bytesToHuman(char *s, unsigned long long n) {
double d;
if (n < 1024) {
/* Bytes */
sprintf(s,"%lluB",n);
return;
} else if (n < (1024*1024)) {
d = (double)n/(1024);
sprintf(s,"%.2fK",d);
} else if (n < (1024LL*1024*1024)) {
d = (double)n/(1024*1024);
sprintf(s,"%.2fM",d);
} else if (n < (1024LL*1024*1024*1024)) {
d = (double)n/(1024LL*1024*1024);
sprintf(s,"%.2fG",d);
}
}
/* Create the string returned by the INFO command. This is decoupled
* by the INFO command itself as we need to report the same information
* on memory corruption problems. */
sds genRedisInfoString(void) {
sds info;
time_t uptime = time(NULL)-server.stat_starttime;
int j;
char hmem[64];
struct rusage self_ru, c_ru;
getrusage(RUSAGE_SELF, &self_ru);
getrusage(RUSAGE_CHILDREN, &c_ru);
bytesToHuman(hmem,zmalloc_used_memory());
info = sdscatprintf(sdsempty(),
"redis_version:%s\r\n"
"redis_git_sha1:%s\r\n"
"redis_git_dirty:%d\r\n"
"arch_bits:%s\r\n"
"multiplexing_api:%s\r\n"
"process_id:%ld\r\n"
"uptime_in_seconds:%ld\r\n"
"uptime_in_days:%ld\r\n"
"lru_clock:%ld\r\n"
"used_cpu_sys:%.2f\r\n"
"used_cpu_user:%.2f\r\n"
"used_cpu_sys_childrens:%.2f\r\n"
"used_cpu_user_childrens:%.2f\r\n"
"connected_clients:%d\r\n"
"connected_slaves:%d\r\n"
"blocked_clients:%d\r\n"
"used_memory:%zu\r\n"
"used_memory_human:%s\r\n"
"used_memory_rss:%zu\r\n"
"mem_fragmentation_ratio:%.2f\r\n"
"use_tcmalloc:%d\r\n"
"loading:%d\r\n"
"aof_enabled:%d\r\n"
"changes_since_last_save:%lld\r\n"
"bgsave_in_progress:%d\r\n"
"last_save_time:%ld\r\n"
"bgrewriteaof_in_progress:%d\r\n"
"total_connections_received:%lld\r\n"
"total_commands_processed:%lld\r\n"
"expired_keys:%lld\r\n"
"evicted_keys:%lld\r\n"
"keyspace_hits:%lld\r\n"
"keyspace_misses:%lld\r\n"
"hash_max_zipmap_entries:%zu\r\n"
"hash_max_zipmap_value:%zu\r\n"
"pubsub_channels:%ld\r\n"
"pubsub_patterns:%u\r\n"
"vm_enabled:%d\r\n"
"role:%s\r\n"
,REDIS_VERSION,
redisGitSHA1(),
strtol(redisGitDirty(),NULL,10) > 0,
(sizeof(long) == 8) ? "64" : "32",
aeGetApiName(),
(long) getpid(),
uptime,
uptime/(3600*24),
(unsigned long) server.lruclock,
(float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000,
(float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000,
(float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000,
(float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000,
listLength(server.clients)-listLength(server.slaves),
listLength(server.slaves),
server.bpop_blocked_clients,
zmalloc_used_memory(),
hmem,
zmalloc_get_rss(),
zmalloc_get_fragmentation_ratio(),
#ifdef USE_TCMALLOC
1,
#else
0,
#endif
server.loading,
server.appendonly,
server.dirty,
server.bgsavechildpid != -1,
server.lastsave,
server.bgrewritechildpid != -1,
server.stat_numconnections,
server.stat_numcommands,
server.stat_expiredkeys,
server.stat_evictedkeys,
server.stat_keyspace_hits,
server.stat_keyspace_misses,
server.hash_max_zipmap_entries,
server.hash_max_zipmap_value,
dictSize(server.pubsub_channels),
listLength(server.pubsub_patterns),
server.vm_enabled != 0,
server.masterhost == NULL ? "master" : "slave"
);
if (server.masterhost) {
info = sdscatprintf(info,
"master_host:%s\r\n"
"master_port:%d\r\n"
"master_link_status:%s\r\n"
"master_last_io_seconds_ago:%d\r\n"
"master_sync_in_progress:%d\r\n"
,server.masterhost,
server.masterport,
(server.replstate == REDIS_REPL_CONNECTED) ?
"up" : "down",
server.master ? ((int)(time(NULL)-server.master->lastinteraction)) : -1,
server.replstate == REDIS_REPL_TRANSFER
);
if (server.replstate == REDIS_REPL_TRANSFER) {
info = sdscatprintf(info,
"master_sync_left_bytes:%ld\r\n"
"master_sync_last_io_seconds_ago:%d\r\n"
,(long)server.repl_transfer_left,
(int)(time(NULL)-server.repl_transfer_lastio)
);
}
}
if (server.vm_enabled) {
lockThreadedIO();
info = sdscatprintf(info,
"vm_conf_max_memory:%llu\r\n"
"vm_conf_page_size:%llu\r\n"
"vm_conf_pages:%llu\r\n"
"vm_stats_used_pages:%llu\r\n"
"vm_stats_swapped_objects:%llu\r\n"
"vm_stats_swappin_count:%llu\r\n"
"vm_stats_swappout_count:%llu\r\n"
"vm_stats_io_newjobs_len:%lu\r\n"
"vm_stats_io_processing_len:%lu\r\n"
"vm_stats_io_processed_len:%lu\r\n"
"vm_stats_io_active_threads:%lu\r\n"
"vm_stats_blocked_clients:%lu\r\n"
,(unsigned long long) server.vm_max_memory,
(unsigned long long) server.vm_page_size,
(unsigned long long) server.vm_pages,
(unsigned long long) server.vm_stats_used_pages,
(unsigned long long) server.vm_stats_swapped_objects,
(unsigned long long) server.vm_stats_swapins,
(unsigned long long) server.vm_stats_swapouts,
(unsigned long) listLength(server.io_newjobs),
(unsigned long) listLength(server.io_processing),
(unsigned long) listLength(server.io_processed),
(unsigned long) server.io_active_threads,
(unsigned long) server.vm_blocked_clients
);
unlockThreadedIO();
}
if (server.loading) {
double perc;
time_t eta, elapsed;
off_t remaining_bytes = server.loading_total_bytes-
server.loading_loaded_bytes;
perc = ((double)server.loading_loaded_bytes /
server.loading_total_bytes) * 100;
elapsed = time(NULL)-server.loading_start_time;
if (elapsed == 0) {
eta = 1; /* A fake 1 second figure if we don't have enough info */
} else {
eta = (elapsed*remaining_bytes)/server.loading_loaded_bytes;
}
info = sdscatprintf(info,
"loading_start_time:%ld\r\n"
"loading_total_bytes:%llu\r\n"
"loading_loaded_bytes:%llu\r\n"
"loading_loaded_perc:%.2f\r\n"
"loading_eta_seconds:%ld\r\n"
,(unsigned long) server.loading_start_time,
(unsigned long long) server.loading_total_bytes,
(unsigned long long) server.loading_loaded_bytes,
perc,
eta
);
}
for (j = 0; j < server.dbnum; j++) {
long long keys, vkeys;
keys = dictSize(server.db[j].dict);
vkeys = dictSize(server.db[j].expires);
if (keys || vkeys) {
info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld\r\n",
j, keys, vkeys);
}
}
return info;
}
void infoCommand(redisClient *c) {
sds info = genRedisInfoString();
addReplySds(c,sdscatprintf(sdsempty(),"$%lu\r\n",
(unsigned long)sdslen(info)));
addReplySds(c,info);
addReply(c,shared.crlf);
}
void monitorCommand(redisClient *c) {
/* ignore MONITOR if aleady slave or in monitor mode */
if (c->flags & REDIS_SLAVE) return;
c->flags |= (REDIS_SLAVE|REDIS_MONITOR);
c->slaveseldb = 0;
listAddNodeTail(server.monitors,c);
addReply(c,shared.ok);
}
/* ============================ Maxmemory directive ======================== */
/* This function gets called when 'maxmemory' is set on the config file to limit
* the max memory used by the server, and we are out of memory.
* This function will try to, in order:
*
* - Free objects from the free list
* - Try to remove keys with an EXPIRE set
*
* It is not possible to free enough memory to reach used-memory < maxmemory
* the server will start refusing commands that will enlarge even more the
* memory usage.
*/
void freeMemoryIfNeeded(void) {
/* Remove keys accordingly to the active policy as long as we are
* over the memory limit. */
if (server.maxmemory_policy == REDIS_MAXMEMORY_NO_EVICTION) return;
while (server.maxmemory && zmalloc_used_memory() > server.maxmemory) {
int j, k, freed = 0;
for (j = 0; j < server.dbnum; j++) {
long bestval = 0; /* just to prevent warning */
sds bestkey = NULL;
struct dictEntry *de;
redisDb *db = server.db+j;
dict *dict;
if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM)
{
dict = server.db[j].dict;
} else {
dict = server.db[j].expires;
}
if (dictSize(dict) == 0) continue;
/* volatile-random and allkeys-random policy */
if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_RANDOM ||
server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_RANDOM)
{
de = dictGetRandomKey(dict);
bestkey = dictGetEntryKey(de);
}
/* volatile-lru and allkeys-lru policy */
else if (server.maxmemory_policy == REDIS_MAXMEMORY_ALLKEYS_LRU ||
server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
{
for (k = 0; k < server.maxmemory_samples; k++) {
sds thiskey;
long thisval;
robj *o;
de = dictGetRandomKey(dict);
thiskey = dictGetEntryKey(de);
/* When policy is volatile-lru we need an additonal lookup
* to locate the real key, as dict is set to db->expires. */
if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_LRU)
de = dictFind(db->dict, thiskey);
o = dictGetEntryVal(de);
thisval = estimateObjectIdleTime(o);
/* Higher idle time is better candidate for deletion */
if (bestkey == NULL || thisval > bestval) {
bestkey = thiskey;
bestval = thisval;
}
}
}
/* volatile-ttl */
else if (server.maxmemory_policy == REDIS_MAXMEMORY_VOLATILE_TTL) {
for (k = 0; k < server.maxmemory_samples; k++) {
sds thiskey;
long thisval;
de = dictGetRandomKey(dict);
thiskey = dictGetEntryKey(de);
thisval = (long) dictGetEntryVal(de);
/* Expire sooner (minor expire unix timestamp) is better
* candidate for deletion */
if (bestkey == NULL || thisval < bestval) {
bestkey = thiskey;
bestval = thisval;
}
}
}
/* Finally remove the selected key. */
if (bestkey) {
robj *keyobj = createStringObject(bestkey,sdslen(bestkey));
dbDelete(db,keyobj);
server.stat_evictedkeys++;
decrRefCount(keyobj);
freed++;
}
}
if (!freed) return; /* nothing to free... */
}
}
/* =================================== Main! ================================ */
#ifdef __linux__
int linuxOvercommitMemoryValue(void) {
FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r");
char buf[64];
if (!fp) return -1;
if (fgets(buf,64,fp) == NULL) {
fclose(fp);
return -1;
}
fclose(fp);
return atoi(buf);
}
void linuxOvercommitMemoryWarning(void) {
if (linuxOvercommitMemoryValue() == 0) {
redisLog(REDIS_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.");
}
}
#endif /* __linux__ */
void createPidFile(void) {
/* Try to write the pid file in a best-effort way. */
FILE *fp = fopen(server.pidfile,"w");
if (fp) {
fprintf(fp,"%d\n",getpid());
fclose(fp);
}
}
void daemonize(void) {
int fd;
if (fork() != 0) exit(0); /* parent exits */
setsid(); /* create a new session */
/* Every output goes to /dev/null. If Redis is daemonized but
* the 'logfile' is set to 'stdout' in the configuration file
* it will not log at all. */
if ((fd = open("/dev/null", O_RDWR, 0)) != -1) {
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
if (fd > STDERR_FILENO) close(fd);
}
}
void version() {
printf("Redis server version %s (%s:%d)\n", REDIS_VERSION,
redisGitSHA1(), atoi(redisGitDirty()) > 0);
exit(0);
}
void usage() {
fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf]\n");
fprintf(stderr," ./redis-server - (read config from stdin)\n");
exit(1);
}
int main(int argc, char **argv) {
time_t start;
initServerConfig();
if (argc == 2) {
if (strcmp(argv[1], "-v") == 0 ||
strcmp(argv[1], "--version") == 0) version();
if (strcmp(argv[1], "--help") == 0) usage();
resetServerSaveParams();
loadServerConfig(argv[1]);
} else if ((argc > 2)) {
usage();
} else {
redisLog(REDIS_WARNING,"Warning: no config file specified, using the default config. In order to specify a config file use 'redis-server /path/to/redis.conf'");
}
if (server.daemonize) daemonize();
initServer();
if (server.daemonize) createPidFile();
redisLog(REDIS_NOTICE,"Server started, Redis version " REDIS_VERSION);
#ifdef __linux__
linuxOvercommitMemoryWarning();
#endif
start = time(NULL);
if (server.appendonly) {
if (loadAppendOnlyFile(server.appendfilename) == REDIS_OK)
redisLog(REDIS_NOTICE,"DB loaded from append only file: %ld seconds",time(NULL)-start);
} else {
if (rdbLoad(server.dbfilename) == REDIS_OK)
redisLog(REDIS_NOTICE,"DB loaded from disk: %ld seconds",time(NULL)-start);
}
if (server.ipfd > 0)
redisLog(REDIS_NOTICE,"The server is now ready to accept connections on port %d", server.port);
if (server.sofd > 0)
redisLog(REDIS_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket);
aeSetBeforeSleepProc(server.el,beforeSleep);
aeMain(server.el);
aeDeleteEventLoop(server.el);
return 0;
}
/* ============================= Backtrace support ========================= */
#ifdef HAVE_BACKTRACE
void *getMcontextEip(ucontext_t *uc) {
#if defined(__FreeBSD__)
return (void*) uc->uc_mcontext.mc_eip;
#elif defined(__dietlibc__)
return (void*) uc->uc_mcontext.eip;
#elif defined(__APPLE__) && !defined(MAC_OS_X_VERSION_10_6)
#if __x86_64__
return (void*) uc->uc_mcontext->__ss.__rip;
#else
return (void*) uc->uc_mcontext->__ss.__eip;
#endif
#elif defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)
#if defined(_STRUCT_X86_THREAD_STATE64) && !defined(__i386__)
return (void*) uc->uc_mcontext->__ss.__rip;
#else
return (void*) uc->uc_mcontext->__ss.__eip;
#endif
#elif defined(__i386__)
return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
#elif defined(__X86_64__) || defined(__x86_64__)
return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
#elif defined(__ia64__) /* Linux IA64 */
return (void*) uc->uc_mcontext.sc_ip;
#else
return NULL;
#endif
}
void segvHandler(int sig, siginfo_t *info, void *secret) {
void *trace[100];
char **messages = NULL;
int i, trace_size = 0;
ucontext_t *uc = (ucontext_t*) secret;
sds infostring;
struct sigaction act;
REDIS_NOTUSED(info);
redisLog(REDIS_WARNING,
"======= Ooops! Redis %s got signal: -%d- =======", REDIS_VERSION, sig);
infostring = genRedisInfoString();
redisLog(REDIS_WARNING, "%s",infostring);
/* It's not safe to sdsfree() the returned string under memory
* corruption conditions. Let it leak as we are going to abort */
trace_size = backtrace(trace, 100);
/* overwrite sigaction with caller's address */
if (getMcontextEip(uc) != NULL) {
trace[1] = getMcontextEip(uc);
}
messages = backtrace_symbols(trace, trace_size);
for (i=1; i<trace_size; ++i)
redisLog(REDIS_WARNING,"%s", messages[i]);
/* free(messages); Don't call free() with possibly corrupted memory. */
if (server.daemonize) unlink(server.pidfile);
/* Make sure we exit with the right signal at the end. So for instance
* the core will be dumped if enabled. */
sigemptyset (&act.sa_mask);
/* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
* is used. Otherwise, sa_handler is used */
act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
act.sa_handler = SIG_DFL;
sigaction (sig, &act, NULL);
kill(getpid(),sig);
}
void sigtermHandler(int sig) {
REDIS_NOTUSED(sig);
redisLog(REDIS_WARNING,"SIGTERM received, scheduling shutting down...");
server.shutdown_asap = 1;
}
void setupSigSegvAction(void) {
struct sigaction act;
sigemptyset (&act.sa_mask);
/* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction
* is used. Otherwise, sa_handler is used */
act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND | SA_SIGINFO;
act.sa_sigaction = segvHandler;
sigaction (SIGSEGV, &act, NULL);
sigaction (SIGBUS, &act, NULL);
sigaction (SIGFPE, &act, NULL);
sigaction (SIGILL, &act, NULL);
sigaction (SIGBUS, &act, NULL);
act.sa_flags = SA_NODEFER | SA_ONSTACK | SA_RESETHAND;
act.sa_handler = sigtermHandler;
sigaction (SIGTERM, &act, NULL);
return;
}
#else /* HAVE_BACKTRACE */
void setupSigSegvAction(void) {
}
#endif /* HAVE_BACKTRACE */
/* The End */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5533_2 |
crossvul-cpp_data_good_5649_0 | /******************************************************************************
*
* Back-end of the driver for virtual block devices. This portion of the
* driver exports a 'unified' block-device interface that can be accessed
* by any operating system that implements a compatible front end. A
* reference front-end implementation can be found in:
* drivers/block/xen-blkfront.c
*
* Copyright (c) 2003-2004, Keir Fraser & Steve Hand
* Copyright (c) 2005, Christopher Clark
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation; or, when distributed
* separately from the Linux kernel or incorporated into other
* software packages, subject to the following license:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this source file (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/list.h>
#include <linux/delay.h>
#include <linux/freezer.h>
#include <linux/bitmap.h>
#include <xen/events.h>
#include <xen/page.h>
#include <xen/xen.h>
#include <asm/xen/hypervisor.h>
#include <asm/xen/hypercall.h>
#include <xen/balloon.h>
#include "common.h"
/*
* Maximum number of unused free pages to keep in the internal buffer.
* Setting this to a value too low will reduce memory used in each backend,
* but can have a performance penalty.
*
* A sane value is xen_blkif_reqs * BLKIF_MAX_SEGMENTS_PER_REQUEST, but can
* be set to a lower value that might degrade performance on some intensive
* IO workloads.
*/
static int xen_blkif_max_buffer_pages = 1024;
module_param_named(max_buffer_pages, xen_blkif_max_buffer_pages, int, 0644);
MODULE_PARM_DESC(max_buffer_pages,
"Maximum number of free pages to keep in each block backend buffer");
/*
* Maximum number of grants to map persistently in blkback. For maximum
* performance this should be the total numbers of grants that can be used
* to fill the ring, but since this might become too high, specially with
* the use of indirect descriptors, we set it to a value that provides good
* performance without using too much memory.
*
* When the list of persistent grants is full we clean it up using a LRU
* algorithm.
*/
static int xen_blkif_max_pgrants = 1056;
module_param_named(max_persistent_grants, xen_blkif_max_pgrants, int, 0644);
MODULE_PARM_DESC(max_persistent_grants,
"Maximum number of grants to map persistently");
/*
* The LRU mechanism to clean the lists of persistent grants needs to
* be executed periodically. The time interval between consecutive executions
* of the purge mechanism is set in ms.
*/
#define LRU_INTERVAL 100
/*
* When the persistent grants list is full we will remove unused grants
* from the list. The percent number of grants to be removed at each LRU
* execution.
*/
#define LRU_PERCENT_CLEAN 5
/* Run-time switchable: /sys/module/blkback/parameters/ */
static unsigned int log_stats;
module_param(log_stats, int, 0644);
#define BLKBACK_INVALID_HANDLE (~0)
/* Number of free pages to remove on each call to free_xenballooned_pages */
#define NUM_BATCH_FREE_PAGES 10
static inline int get_free_page(struct xen_blkif *blkif, struct page **page)
{
unsigned long flags;
spin_lock_irqsave(&blkif->free_pages_lock, flags);
if (list_empty(&blkif->free_pages)) {
BUG_ON(blkif->free_pages_num != 0);
spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
return alloc_xenballooned_pages(1, page, false);
}
BUG_ON(blkif->free_pages_num == 0);
page[0] = list_first_entry(&blkif->free_pages, struct page, lru);
list_del(&page[0]->lru);
blkif->free_pages_num--;
spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
return 0;
}
static inline void put_free_pages(struct xen_blkif *blkif, struct page **page,
int num)
{
unsigned long flags;
int i;
spin_lock_irqsave(&blkif->free_pages_lock, flags);
for (i = 0; i < num; i++)
list_add(&page[i]->lru, &blkif->free_pages);
blkif->free_pages_num += num;
spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
}
static inline void shrink_free_pagepool(struct xen_blkif *blkif, int num)
{
/* Remove requested pages in batches of NUM_BATCH_FREE_PAGES */
struct page *page[NUM_BATCH_FREE_PAGES];
unsigned int num_pages = 0;
unsigned long flags;
spin_lock_irqsave(&blkif->free_pages_lock, flags);
while (blkif->free_pages_num > num) {
BUG_ON(list_empty(&blkif->free_pages));
page[num_pages] = list_first_entry(&blkif->free_pages,
struct page, lru);
list_del(&page[num_pages]->lru);
blkif->free_pages_num--;
if (++num_pages == NUM_BATCH_FREE_PAGES) {
spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
free_xenballooned_pages(num_pages, page);
spin_lock_irqsave(&blkif->free_pages_lock, flags);
num_pages = 0;
}
}
spin_unlock_irqrestore(&blkif->free_pages_lock, flags);
if (num_pages != 0)
free_xenballooned_pages(num_pages, page);
}
#define vaddr(page) ((unsigned long)pfn_to_kaddr(page_to_pfn(page)))
static int do_block_io_op(struct xen_blkif *blkif);
static int dispatch_rw_block_io(struct xen_blkif *blkif,
struct blkif_request *req,
struct pending_req *pending_req);
static void make_response(struct xen_blkif *blkif, u64 id,
unsigned short op, int st);
#define foreach_grant_safe(pos, n, rbtree, node) \
for ((pos) = container_of(rb_first((rbtree)), typeof(*(pos)), node), \
(n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL; \
&(pos)->node != NULL; \
(pos) = container_of(n, typeof(*(pos)), node), \
(n) = (&(pos)->node != NULL) ? rb_next(&(pos)->node) : NULL)
/*
* We don't need locking around the persistent grant helpers
* because blkback uses a single-thread for each backed, so we
* can be sure that this functions will never be called recursively.
*
* The only exception to that is put_persistent_grant, that can be called
* from interrupt context (by xen_blkbk_unmap), so we have to use atomic
* bit operations to modify the flags of a persistent grant and to count
* the number of used grants.
*/
static int add_persistent_gnt(struct xen_blkif *blkif,
struct persistent_gnt *persistent_gnt)
{
struct rb_node **new = NULL, *parent = NULL;
struct persistent_gnt *this;
if (blkif->persistent_gnt_c >= xen_blkif_max_pgrants) {
if (!blkif->vbd.overflow_max_grants)
blkif->vbd.overflow_max_grants = 1;
return -EBUSY;
}
/* Figure out where to put new node */
new = &blkif->persistent_gnts.rb_node;
while (*new) {
this = container_of(*new, struct persistent_gnt, node);
parent = *new;
if (persistent_gnt->gnt < this->gnt)
new = &((*new)->rb_left);
else if (persistent_gnt->gnt > this->gnt)
new = &((*new)->rb_right);
else {
pr_alert_ratelimited(DRV_PFX " trying to add a gref that's already in the tree\n");
return -EINVAL;
}
}
bitmap_zero(persistent_gnt->flags, PERSISTENT_GNT_FLAGS_SIZE);
set_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
/* Add new node and rebalance tree. */
rb_link_node(&(persistent_gnt->node), parent, new);
rb_insert_color(&(persistent_gnt->node), &blkif->persistent_gnts);
blkif->persistent_gnt_c++;
atomic_inc(&blkif->persistent_gnt_in_use);
return 0;
}
static struct persistent_gnt *get_persistent_gnt(struct xen_blkif *blkif,
grant_ref_t gref)
{
struct persistent_gnt *data;
struct rb_node *node = NULL;
node = blkif->persistent_gnts.rb_node;
while (node) {
data = container_of(node, struct persistent_gnt, node);
if (gref < data->gnt)
node = node->rb_left;
else if (gref > data->gnt)
node = node->rb_right;
else {
if(test_bit(PERSISTENT_GNT_ACTIVE, data->flags)) {
pr_alert_ratelimited(DRV_PFX " requesting a grant already in use\n");
return NULL;
}
set_bit(PERSISTENT_GNT_ACTIVE, data->flags);
atomic_inc(&blkif->persistent_gnt_in_use);
return data;
}
}
return NULL;
}
static void put_persistent_gnt(struct xen_blkif *blkif,
struct persistent_gnt *persistent_gnt)
{
if(!test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
pr_alert_ratelimited(DRV_PFX " freeing a grant already unused");
set_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
clear_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags);
atomic_dec(&blkif->persistent_gnt_in_use);
}
static void free_persistent_gnts(struct xen_blkif *blkif, struct rb_root *root,
unsigned int num)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt;
struct rb_node *n;
int ret = 0;
int segs_to_unmap = 0;
foreach_grant_safe(persistent_gnt, n, root, node) {
BUG_ON(persistent_gnt->handle ==
BLKBACK_INVALID_HANDLE);
gnttab_set_unmap_op(&unmap[segs_to_unmap],
(unsigned long) pfn_to_kaddr(page_to_pfn(
persistent_gnt->page)),
GNTMAP_host_map,
persistent_gnt->handle);
pages[segs_to_unmap] = persistent_gnt->page;
if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST ||
!rb_next(&persistent_gnt->node)) {
ret = gnttab_unmap_refs(unmap, NULL, pages,
segs_to_unmap);
BUG_ON(ret);
put_free_pages(blkif, pages, segs_to_unmap);
segs_to_unmap = 0;
}
rb_erase(&persistent_gnt->node, root);
kfree(persistent_gnt);
num--;
}
BUG_ON(num != 0);
}
static void unmap_purged_grants(struct work_struct *work)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt;
int ret, segs_to_unmap = 0;
struct xen_blkif *blkif = container_of(work, typeof(*blkif), persistent_purge_work);
while(!list_empty(&blkif->persistent_purge_list)) {
persistent_gnt = list_first_entry(&blkif->persistent_purge_list,
struct persistent_gnt,
remove_node);
list_del(&persistent_gnt->remove_node);
gnttab_set_unmap_op(&unmap[segs_to_unmap],
vaddr(persistent_gnt->page),
GNTMAP_host_map,
persistent_gnt->handle);
pages[segs_to_unmap] = persistent_gnt->page;
if (++segs_to_unmap == BLKIF_MAX_SEGMENTS_PER_REQUEST) {
ret = gnttab_unmap_refs(unmap, NULL, pages,
segs_to_unmap);
BUG_ON(ret);
put_free_pages(blkif, pages, segs_to_unmap);
segs_to_unmap = 0;
}
kfree(persistent_gnt);
}
if (segs_to_unmap > 0) {
ret = gnttab_unmap_refs(unmap, NULL, pages, segs_to_unmap);
BUG_ON(ret);
put_free_pages(blkif, pages, segs_to_unmap);
}
}
static void purge_persistent_gnt(struct xen_blkif *blkif)
{
struct persistent_gnt *persistent_gnt;
struct rb_node *n;
unsigned int num_clean, total;
bool scan_used = false;
struct rb_root *root;
if (blkif->persistent_gnt_c < xen_blkif_max_pgrants ||
(blkif->persistent_gnt_c == xen_blkif_max_pgrants &&
!blkif->vbd.overflow_max_grants)) {
return;
}
if (work_pending(&blkif->persistent_purge_work)) {
pr_alert_ratelimited(DRV_PFX "Scheduled work from previous purge is still pending, cannot purge list\n");
return;
}
num_clean = (xen_blkif_max_pgrants / 100) * LRU_PERCENT_CLEAN;
num_clean = blkif->persistent_gnt_c - xen_blkif_max_pgrants + num_clean;
num_clean = min(blkif->persistent_gnt_c, num_clean);
if (num_clean >
(blkif->persistent_gnt_c -
atomic_read(&blkif->persistent_gnt_in_use)))
return;
/*
* At this point, we can assure that there will be no calls
* to get_persistent_grant (because we are executing this code from
* xen_blkif_schedule), there can only be calls to put_persistent_gnt,
* which means that the number of currently used grants will go down,
* but never up, so we will always be able to remove the requested
* number of grants.
*/
total = num_clean;
pr_debug(DRV_PFX "Going to purge %u persistent grants\n", num_clean);
INIT_LIST_HEAD(&blkif->persistent_purge_list);
root = &blkif->persistent_gnts;
purge_list:
foreach_grant_safe(persistent_gnt, n, root, node) {
BUG_ON(persistent_gnt->handle ==
BLKBACK_INVALID_HANDLE);
if (test_bit(PERSISTENT_GNT_ACTIVE, persistent_gnt->flags))
continue;
if (!scan_used &&
(test_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags)))
continue;
rb_erase(&persistent_gnt->node, root);
list_add(&persistent_gnt->remove_node,
&blkif->persistent_purge_list);
if (--num_clean == 0)
goto finished;
}
/*
* If we get here it means we also need to start cleaning
* grants that were used since last purge in order to cope
* with the requested num
*/
if (!scan_used) {
pr_debug(DRV_PFX "Still missing %u purged frames\n", num_clean);
scan_used = true;
goto purge_list;
}
finished:
/* Remove the "used" flag from all the persistent grants */
foreach_grant_safe(persistent_gnt, n, root, node) {
BUG_ON(persistent_gnt->handle ==
BLKBACK_INVALID_HANDLE);
clear_bit(PERSISTENT_GNT_WAS_ACTIVE, persistent_gnt->flags);
}
blkif->persistent_gnt_c -= (total - num_clean);
blkif->vbd.overflow_max_grants = 0;
/* We can defer this work */
INIT_WORK(&blkif->persistent_purge_work, unmap_purged_grants);
schedule_work(&blkif->persistent_purge_work);
pr_debug(DRV_PFX "Purged %u/%u\n", (total - num_clean), total);
return;
}
/*
* Retrieve from the 'pending_reqs' a free pending_req structure to be used.
*/
static struct pending_req *alloc_req(struct xen_blkif *blkif)
{
struct pending_req *req = NULL;
unsigned long flags;
spin_lock_irqsave(&blkif->pending_free_lock, flags);
if (!list_empty(&blkif->pending_free)) {
req = list_entry(blkif->pending_free.next, struct pending_req,
free_list);
list_del(&req->free_list);
}
spin_unlock_irqrestore(&blkif->pending_free_lock, flags);
return req;
}
/*
* Return the 'pending_req' structure back to the freepool. We also
* wake up the thread if it was waiting for a free page.
*/
static void free_req(struct xen_blkif *blkif, struct pending_req *req)
{
unsigned long flags;
int was_empty;
spin_lock_irqsave(&blkif->pending_free_lock, flags);
was_empty = list_empty(&blkif->pending_free);
list_add(&req->free_list, &blkif->pending_free);
spin_unlock_irqrestore(&blkif->pending_free_lock, flags);
if (was_empty)
wake_up(&blkif->pending_free_wq);
}
/*
* Routines for managing virtual block devices (vbds).
*/
static int xen_vbd_translate(struct phys_req *req, struct xen_blkif *blkif,
int operation)
{
struct xen_vbd *vbd = &blkif->vbd;
int rc = -EACCES;
if ((operation != READ) && vbd->readonly)
goto out;
if (likely(req->nr_sects)) {
blkif_sector_t end = req->sector_number + req->nr_sects;
if (unlikely(end < req->sector_number))
goto out;
if (unlikely(end > vbd_sz(vbd)))
goto out;
}
req->dev = vbd->pdevice;
req->bdev = vbd->bdev;
rc = 0;
out:
return rc;
}
static void xen_vbd_resize(struct xen_blkif *blkif)
{
struct xen_vbd *vbd = &blkif->vbd;
struct xenbus_transaction xbt;
int err;
struct xenbus_device *dev = xen_blkbk_xenbus(blkif->be);
unsigned long long new_size = vbd_sz(vbd);
pr_info(DRV_PFX "VBD Resize: Domid: %d, Device: (%d, %d)\n",
blkif->domid, MAJOR(vbd->pdevice), MINOR(vbd->pdevice));
pr_info(DRV_PFX "VBD Resize: new size %llu\n", new_size);
vbd->size = new_size;
again:
err = xenbus_transaction_start(&xbt);
if (err) {
pr_warn(DRV_PFX "Error starting transaction");
return;
}
err = xenbus_printf(xbt, dev->nodename, "sectors", "%llu",
(unsigned long long)vbd_sz(vbd));
if (err) {
pr_warn(DRV_PFX "Error writing new size");
goto abort;
}
/*
* Write the current state; we will use this to synchronize
* the front-end. If the current state is "connected" the
* front-end will get the new size information online.
*/
err = xenbus_printf(xbt, dev->nodename, "state", "%d", dev->state);
if (err) {
pr_warn(DRV_PFX "Error writing the state");
goto abort;
}
err = xenbus_transaction_end(xbt, 0);
if (err == -EAGAIN)
goto again;
if (err)
pr_warn(DRV_PFX "Error ending transaction");
return;
abort:
xenbus_transaction_end(xbt, 1);
}
/*
* Notification from the guest OS.
*/
static void blkif_notify_work(struct xen_blkif *blkif)
{
blkif->waiting_reqs = 1;
wake_up(&blkif->wq);
}
irqreturn_t xen_blkif_be_int(int irq, void *dev_id)
{
blkif_notify_work(dev_id);
return IRQ_HANDLED;
}
/*
* SCHEDULER FUNCTIONS
*/
static void print_stats(struct xen_blkif *blkif)
{
pr_info("xen-blkback (%s): oo %3llu | rd %4llu | wr %4llu | f %4llu"
" | ds %4llu | pg: %4u/%4d\n",
current->comm, blkif->st_oo_req,
blkif->st_rd_req, blkif->st_wr_req,
blkif->st_f_req, blkif->st_ds_req,
blkif->persistent_gnt_c,
xen_blkif_max_pgrants);
blkif->st_print = jiffies + msecs_to_jiffies(10 * 1000);
blkif->st_rd_req = 0;
blkif->st_wr_req = 0;
blkif->st_oo_req = 0;
blkif->st_ds_req = 0;
}
int xen_blkif_schedule(void *arg)
{
struct xen_blkif *blkif = arg;
struct xen_vbd *vbd = &blkif->vbd;
unsigned long timeout;
xen_blkif_get(blkif);
while (!kthread_should_stop()) {
if (try_to_freeze())
continue;
if (unlikely(vbd->size != vbd_sz(vbd)))
xen_vbd_resize(blkif);
timeout = msecs_to_jiffies(LRU_INTERVAL);
timeout = wait_event_interruptible_timeout(
blkif->wq,
blkif->waiting_reqs || kthread_should_stop(),
timeout);
if (timeout == 0)
goto purge_gnt_list;
timeout = wait_event_interruptible_timeout(
blkif->pending_free_wq,
!list_empty(&blkif->pending_free) ||
kthread_should_stop(),
timeout);
if (timeout == 0)
goto purge_gnt_list;
blkif->waiting_reqs = 0;
smp_mb(); /* clear flag *before* checking for work */
if (do_block_io_op(blkif))
blkif->waiting_reqs = 1;
purge_gnt_list:
if (blkif->vbd.feature_gnt_persistent &&
time_after(jiffies, blkif->next_lru)) {
purge_persistent_gnt(blkif);
blkif->next_lru = jiffies + msecs_to_jiffies(LRU_INTERVAL);
}
/* Shrink if we have more than xen_blkif_max_buffer_pages */
shrink_free_pagepool(blkif, xen_blkif_max_buffer_pages);
if (log_stats && time_after(jiffies, blkif->st_print))
print_stats(blkif);
}
/* Since we are shutting down remove all pages from the buffer */
shrink_free_pagepool(blkif, 0 /* All */);
/* Free all persistent grant pages */
if (!RB_EMPTY_ROOT(&blkif->persistent_gnts))
free_persistent_gnts(blkif, &blkif->persistent_gnts,
blkif->persistent_gnt_c);
BUG_ON(!RB_EMPTY_ROOT(&blkif->persistent_gnts));
blkif->persistent_gnt_c = 0;
if (log_stats)
print_stats(blkif);
blkif->xenblkd = NULL;
xen_blkif_put(blkif);
return 0;
}
/*
* Unmap the grant references, and also remove the M2P over-rides
* used in the 'pending_req'.
*/
static void xen_blkbk_unmap(struct xen_blkif *blkif,
struct grant_page *pages[],
int num)
{
struct gnttab_unmap_grant_ref unmap[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *unmap_pages[BLKIF_MAX_SEGMENTS_PER_REQUEST];
unsigned int i, invcount = 0;
int ret;
for (i = 0; i < num; i++) {
if (pages[i]->persistent_gnt != NULL) {
put_persistent_gnt(blkif, pages[i]->persistent_gnt);
continue;
}
if (pages[i]->handle == BLKBACK_INVALID_HANDLE)
continue;
unmap_pages[invcount] = pages[i]->page;
gnttab_set_unmap_op(&unmap[invcount], vaddr(pages[i]->page),
GNTMAP_host_map, pages[i]->handle);
pages[i]->handle = BLKBACK_INVALID_HANDLE;
if (++invcount == BLKIF_MAX_SEGMENTS_PER_REQUEST) {
ret = gnttab_unmap_refs(unmap, NULL, unmap_pages,
invcount);
BUG_ON(ret);
put_free_pages(blkif, unmap_pages, invcount);
invcount = 0;
}
}
if (invcount) {
ret = gnttab_unmap_refs(unmap, NULL, unmap_pages, invcount);
BUG_ON(ret);
put_free_pages(blkif, unmap_pages, invcount);
}
}
static int xen_blkbk_map(struct xen_blkif *blkif,
struct grant_page *pages[],
int num, bool ro)
{
struct gnttab_map_grant_ref map[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct page *pages_to_gnt[BLKIF_MAX_SEGMENTS_PER_REQUEST];
struct persistent_gnt *persistent_gnt = NULL;
phys_addr_t addr = 0;
int i, seg_idx, new_map_idx;
int segs_to_map = 0;
int ret = 0;
int last_map = 0, map_until = 0;
int use_persistent_gnts;
use_persistent_gnts = (blkif->vbd.feature_gnt_persistent);
/*
* Fill out preq.nr_sects with proper amount of sectors, and setup
* assign map[..] with the PFN of the page in our domain with the
* corresponding grant reference for each page.
*/
again:
for (i = map_until; i < num; i++) {
uint32_t flags;
if (use_persistent_gnts)
persistent_gnt = get_persistent_gnt(
blkif,
pages[i]->gref);
if (persistent_gnt) {
/*
* We are using persistent grants and
* the grant is already mapped
*/
pages[i]->page = persistent_gnt->page;
pages[i]->persistent_gnt = persistent_gnt;
} else {
if (get_free_page(blkif, &pages[i]->page))
goto out_of_memory;
addr = vaddr(pages[i]->page);
pages_to_gnt[segs_to_map] = pages[i]->page;
pages[i]->persistent_gnt = NULL;
flags = GNTMAP_host_map;
if (!use_persistent_gnts && ro)
flags |= GNTMAP_readonly;
gnttab_set_map_op(&map[segs_to_map++], addr,
flags, pages[i]->gref,
blkif->domid);
}
map_until = i + 1;
if (segs_to_map == BLKIF_MAX_SEGMENTS_PER_REQUEST)
break;
}
if (segs_to_map) {
ret = gnttab_map_refs(map, NULL, pages_to_gnt, segs_to_map);
BUG_ON(ret);
}
/*
* Now swizzle the MFN in our domain with the MFN from the other domain
* so that when we access vaddr(pending_req,i) it has the contents of
* the page from the other domain.
*/
for (seg_idx = last_map, new_map_idx = 0; seg_idx < map_until; seg_idx++) {
if (!pages[seg_idx]->persistent_gnt) {
/* This is a newly mapped grant */
BUG_ON(new_map_idx >= segs_to_map);
if (unlikely(map[new_map_idx].status != 0)) {
pr_debug(DRV_PFX "invalid buffer -- could not remap it\n");
pages[seg_idx]->handle = BLKBACK_INVALID_HANDLE;
ret |= 1;
goto next;
}
pages[seg_idx]->handle = map[new_map_idx].handle;
} else {
continue;
}
if (use_persistent_gnts &&
blkif->persistent_gnt_c < xen_blkif_max_pgrants) {
/*
* We are using persistent grants, the grant is
* not mapped but we might have room for it.
*/
persistent_gnt = kmalloc(sizeof(struct persistent_gnt),
GFP_KERNEL);
if (!persistent_gnt) {
/*
* If we don't have enough memory to
* allocate the persistent_gnt struct
* map this grant non-persistenly
*/
goto next;
}
persistent_gnt->gnt = map[new_map_idx].ref;
persistent_gnt->handle = map[new_map_idx].handle;
persistent_gnt->page = pages[seg_idx]->page;
if (add_persistent_gnt(blkif,
persistent_gnt)) {
kfree(persistent_gnt);
persistent_gnt = NULL;
goto next;
}
pages[seg_idx]->persistent_gnt = persistent_gnt;
pr_debug(DRV_PFX " grant %u added to the tree of persistent grants, using %u/%u\n",
persistent_gnt->gnt, blkif->persistent_gnt_c,
xen_blkif_max_pgrants);
goto next;
}
if (use_persistent_gnts && !blkif->vbd.overflow_max_grants) {
blkif->vbd.overflow_max_grants = 1;
pr_debug(DRV_PFX " domain %u, device %#x is using maximum number of persistent grants\n",
blkif->domid, blkif->vbd.handle);
}
/*
* We could not map this grant persistently, so use it as
* a non-persistent grant.
*/
next:
new_map_idx++;
}
segs_to_map = 0;
last_map = map_until;
if (map_until != num)
goto again;
return ret;
out_of_memory:
pr_alert(DRV_PFX "%s: out of memory\n", __func__);
put_free_pages(blkif, pages_to_gnt, segs_to_map);
return -ENOMEM;
}
static int xen_blkbk_map_seg(struct pending_req *pending_req)
{
int rc;
rc = xen_blkbk_map(pending_req->blkif, pending_req->segments,
pending_req->nr_pages,
(pending_req->operation != BLKIF_OP_READ));
return rc;
}
static int xen_blkbk_parse_indirect(struct blkif_request *req,
struct pending_req *pending_req,
struct seg_buf seg[],
struct phys_req *preq)
{
struct grant_page **pages = pending_req->indirect_pages;
struct xen_blkif *blkif = pending_req->blkif;
int indirect_grefs, rc, n, nseg, i;
struct blkif_request_segment_aligned *segments = NULL;
nseg = pending_req->nr_pages;
indirect_grefs = INDIRECT_PAGES(nseg);
BUG_ON(indirect_grefs > BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST);
for (i = 0; i < indirect_grefs; i++)
pages[i]->gref = req->u.indirect.indirect_grefs[i];
rc = xen_blkbk_map(blkif, pages, indirect_grefs, true);
if (rc)
goto unmap;
for (n = 0, i = 0; n < nseg; n++) {
if ((n % SEGS_PER_INDIRECT_FRAME) == 0) {
/* Map indirect segments */
if (segments)
kunmap_atomic(segments);
segments = kmap_atomic(pages[n/SEGS_PER_INDIRECT_FRAME]->page);
}
i = n % SEGS_PER_INDIRECT_FRAME;
pending_req->segments[n]->gref = segments[i].gref;
seg[n].nsec = segments[i].last_sect -
segments[i].first_sect + 1;
seg[n].offset = (segments[i].first_sect << 9);
if ((segments[i].last_sect >= (PAGE_SIZE >> 9)) ||
(segments[i].last_sect < segments[i].first_sect)) {
rc = -EINVAL;
goto unmap;
}
preq->nr_sects += seg[n].nsec;
}
unmap:
if (segments)
kunmap_atomic(segments);
xen_blkbk_unmap(blkif, pages, indirect_grefs);
return rc;
}
static int dispatch_discard_io(struct xen_blkif *blkif,
struct blkif_request *req)
{
int err = 0;
int status = BLKIF_RSP_OKAY;
struct block_device *bdev = blkif->vbd.bdev;
unsigned long secure;
struct phys_req preq;
preq.sector_number = req->u.discard.sector_number;
preq.nr_sects = req->u.discard.nr_sectors;
err = xen_vbd_translate(&preq, blkif, WRITE);
if (err) {
pr_warn(DRV_PFX "access denied: DISCARD [%llu->%llu] on dev=%04x\n",
preq.sector_number,
preq.sector_number + preq.nr_sects, blkif->vbd.pdevice);
goto fail_response;
}
blkif->st_ds_req++;
xen_blkif_get(blkif);
secure = (blkif->vbd.discard_secure &&
(req->u.discard.flag & BLKIF_DISCARD_SECURE)) ?
BLKDEV_DISCARD_SECURE : 0;
err = blkdev_issue_discard(bdev, req->u.discard.sector_number,
req->u.discard.nr_sectors,
GFP_KERNEL, secure);
fail_response:
if (err == -EOPNOTSUPP) {
pr_debug(DRV_PFX "discard op failed, not supported\n");
status = BLKIF_RSP_EOPNOTSUPP;
} else if (err)
status = BLKIF_RSP_ERROR;
make_response(blkif, req->u.discard.id, req->operation, status);
xen_blkif_put(blkif);
return err;
}
static int dispatch_other_io(struct xen_blkif *blkif,
struct blkif_request *req,
struct pending_req *pending_req)
{
free_req(blkif, pending_req);
make_response(blkif, req->u.other.id, req->operation,
BLKIF_RSP_EOPNOTSUPP);
return -EIO;
}
static void xen_blk_drain_io(struct xen_blkif *blkif)
{
atomic_set(&blkif->drain, 1);
do {
/* The initial value is one, and one refcnt taken at the
* start of the xen_blkif_schedule thread. */
if (atomic_read(&blkif->refcnt) <= 2)
break;
wait_for_completion_interruptible_timeout(
&blkif->drain_complete, HZ);
if (!atomic_read(&blkif->drain))
break;
} while (!kthread_should_stop());
atomic_set(&blkif->drain, 0);
}
/*
* Completion callback on the bio's. Called as bh->b_end_io()
*/
static void __end_block_io_op(struct pending_req *pending_req, int error)
{
/* An error fails the entire request. */
if ((pending_req->operation == BLKIF_OP_FLUSH_DISKCACHE) &&
(error == -EOPNOTSUPP)) {
pr_debug(DRV_PFX "flush diskcache op failed, not supported\n");
xen_blkbk_flush_diskcache(XBT_NIL, pending_req->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if ((pending_req->operation == BLKIF_OP_WRITE_BARRIER) &&
(error == -EOPNOTSUPP)) {
pr_debug(DRV_PFX "write barrier op failed, not supported\n");
xen_blkbk_barrier(XBT_NIL, pending_req->blkif->be, 0);
pending_req->status = BLKIF_RSP_EOPNOTSUPP;
} else if (error) {
pr_debug(DRV_PFX "Buffer not up-to-date at end of operation,"
" error=%d\n", error);
pending_req->status = BLKIF_RSP_ERROR;
}
/*
* If all of the bio's have completed it is time to unmap
* the grant references associated with 'request' and provide
* the proper response on the ring.
*/
if (atomic_dec_and_test(&pending_req->pendcnt)) {
xen_blkbk_unmap(pending_req->blkif,
pending_req->segments,
pending_req->nr_pages);
make_response(pending_req->blkif, pending_req->id,
pending_req->operation, pending_req->status);
xen_blkif_put(pending_req->blkif);
if (atomic_read(&pending_req->blkif->refcnt) <= 2) {
if (atomic_read(&pending_req->blkif->drain))
complete(&pending_req->blkif->drain_complete);
}
free_req(pending_req->blkif, pending_req);
}
}
/*
* bio callback.
*/
static void end_block_io_op(struct bio *bio, int error)
{
__end_block_io_op(bio->bi_private, error);
bio_put(bio);
}
/*
* Function to copy the from the ring buffer the 'struct blkif_request'
* (which has the sectors we want, number of them, grant references, etc),
* and transmute it to the block API to hand it over to the proper block disk.
*/
static int
__do_block_io_op(struct xen_blkif *blkif)
{
union blkif_back_rings *blk_rings = &blkif->blk_rings;
struct blkif_request req;
struct pending_req *pending_req;
RING_IDX rc, rp;
int more_to_do = 0;
rc = blk_rings->common.req_cons;
rp = blk_rings->common.sring->req_prod;
rmb(); /* Ensure we see queued requests up to 'rp'. */
while (rc != rp) {
if (RING_REQUEST_CONS_OVERFLOW(&blk_rings->common, rc))
break;
if (kthread_should_stop()) {
more_to_do = 1;
break;
}
pending_req = alloc_req(blkif);
if (NULL == pending_req) {
blkif->st_oo_req++;
more_to_do = 1;
break;
}
switch (blkif->blk_protocol) {
case BLKIF_PROTOCOL_NATIVE:
memcpy(&req, RING_GET_REQUEST(&blk_rings->native, rc), sizeof(req));
break;
case BLKIF_PROTOCOL_X86_32:
blkif_get_x86_32_req(&req, RING_GET_REQUEST(&blk_rings->x86_32, rc));
break;
case BLKIF_PROTOCOL_X86_64:
blkif_get_x86_64_req(&req, RING_GET_REQUEST(&blk_rings->x86_64, rc));
break;
default:
BUG();
}
blk_rings->common.req_cons = ++rc; /* before make_response() */
/* Apply all sanity checks to /private copy/ of request. */
barrier();
switch (req.operation) {
case BLKIF_OP_READ:
case BLKIF_OP_WRITE:
case BLKIF_OP_WRITE_BARRIER:
case BLKIF_OP_FLUSH_DISKCACHE:
case BLKIF_OP_INDIRECT:
if (dispatch_rw_block_io(blkif, &req, pending_req))
goto done;
break;
case BLKIF_OP_DISCARD:
free_req(blkif, pending_req);
if (dispatch_discard_io(blkif, &req))
goto done;
break;
default:
if (dispatch_other_io(blkif, &req, pending_req))
goto done;
break;
}
/* Yield point for this unbounded loop. */
cond_resched();
}
done:
return more_to_do;
}
static int
do_block_io_op(struct xen_blkif *blkif)
{
union blkif_back_rings *blk_rings = &blkif->blk_rings;
int more_to_do;
do {
more_to_do = __do_block_io_op(blkif);
if (more_to_do)
break;
RING_FINAL_CHECK_FOR_REQUESTS(&blk_rings->common, more_to_do);
} while (more_to_do);
return more_to_do;
}
/*
* Transmutation of the 'struct blkif_request' to a proper 'struct bio'
* and call the 'submit_bio' to pass it to the underlying storage.
*/
static int dispatch_rw_block_io(struct xen_blkif *blkif,
struct blkif_request *req,
struct pending_req *pending_req)
{
struct phys_req preq;
struct seg_buf *seg = pending_req->seg;
unsigned int nseg;
struct bio *bio = NULL;
struct bio **biolist = pending_req->biolist;
int i, nbio = 0;
int operation;
struct blk_plug plug;
bool drain = false;
struct grant_page **pages = pending_req->segments;
unsigned short req_operation;
req_operation = req->operation == BLKIF_OP_INDIRECT ?
req->u.indirect.indirect_op : req->operation;
if ((req->operation == BLKIF_OP_INDIRECT) &&
(req_operation != BLKIF_OP_READ) &&
(req_operation != BLKIF_OP_WRITE)) {
pr_debug(DRV_PFX "Invalid indirect operation (%u)\n",
req_operation);
goto fail_response;
}
switch (req_operation) {
case BLKIF_OP_READ:
blkif->st_rd_req++;
operation = READ;
break;
case BLKIF_OP_WRITE:
blkif->st_wr_req++;
operation = WRITE_ODIRECT;
break;
case BLKIF_OP_WRITE_BARRIER:
drain = true;
case BLKIF_OP_FLUSH_DISKCACHE:
blkif->st_f_req++;
operation = WRITE_FLUSH;
break;
default:
operation = 0; /* make gcc happy */
goto fail_response;
break;
}
/* Check that the number of segments is sane. */
nseg = req->operation == BLKIF_OP_INDIRECT ?
req->u.indirect.nr_segments : req->u.rw.nr_segments;
if (unlikely(nseg == 0 && operation != WRITE_FLUSH) ||
unlikely((req->operation != BLKIF_OP_INDIRECT) &&
(nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST)) ||
unlikely((req->operation == BLKIF_OP_INDIRECT) &&
(nseg > MAX_INDIRECT_SEGMENTS))) {
pr_debug(DRV_PFX "Bad number of segments in request (%d)\n",
nseg);
/* Haven't submitted any bio's yet. */
goto fail_response;
}
preq.nr_sects = 0;
pending_req->blkif = blkif;
pending_req->id = req->u.rw.id;
pending_req->operation = req_operation;
pending_req->status = BLKIF_RSP_OKAY;
pending_req->nr_pages = nseg;
if (req->operation != BLKIF_OP_INDIRECT) {
preq.dev = req->u.rw.handle;
preq.sector_number = req->u.rw.sector_number;
for (i = 0; i < nseg; i++) {
pages[i]->gref = req->u.rw.seg[i].gref;
seg[i].nsec = req->u.rw.seg[i].last_sect -
req->u.rw.seg[i].first_sect + 1;
seg[i].offset = (req->u.rw.seg[i].first_sect << 9);
if ((req->u.rw.seg[i].last_sect >= (PAGE_SIZE >> 9)) ||
(req->u.rw.seg[i].last_sect <
req->u.rw.seg[i].first_sect))
goto fail_response;
preq.nr_sects += seg[i].nsec;
}
} else {
preq.dev = req->u.indirect.handle;
preq.sector_number = req->u.indirect.sector_number;
if (xen_blkbk_parse_indirect(req, pending_req, seg, &preq))
goto fail_response;
}
if (xen_vbd_translate(&preq, blkif, operation) != 0) {
pr_debug(DRV_PFX "access denied: %s of [%llu,%llu] on dev=%04x\n",
operation == READ ? "read" : "write",
preq.sector_number,
preq.sector_number + preq.nr_sects,
blkif->vbd.pdevice);
goto fail_response;
}
/*
* This check _MUST_ be done after xen_vbd_translate as the preq.bdev
* is set there.
*/
for (i = 0; i < nseg; i++) {
if (((int)preq.sector_number|(int)seg[i].nsec) &
((bdev_logical_block_size(preq.bdev) >> 9) - 1)) {
pr_debug(DRV_PFX "Misaligned I/O request from domain %d",
blkif->domid);
goto fail_response;
}
}
/* Wait on all outstanding I/O's and once that has been completed
* issue the WRITE_FLUSH.
*/
if (drain)
xen_blk_drain_io(pending_req->blkif);
/*
* If we have failed at this point, we need to undo the M2P override,
* set gnttab_set_unmap_op on all of the grant references and perform
* the hypercall to unmap the grants - that is all done in
* xen_blkbk_unmap.
*/
if (xen_blkbk_map_seg(pending_req))
goto fail_flush;
/*
* This corresponding xen_blkif_put is done in __end_block_io_op, or
* below (in "!bio") if we are handling a BLKIF_OP_DISCARD.
*/
xen_blkif_get(blkif);
for (i = 0; i < nseg; i++) {
while ((bio == NULL) ||
(bio_add_page(bio,
pages[i]->page,
seg[i].nsec << 9,
seg[i].offset) == 0)) {
bio = bio_alloc(GFP_KERNEL, nseg-i);
if (unlikely(bio == NULL))
goto fail_put_bio;
biolist[nbio++] = bio;
bio->bi_bdev = preq.bdev;
bio->bi_private = pending_req;
bio->bi_end_io = end_block_io_op;
bio->bi_sector = preq.sector_number;
}
preq.sector_number += seg[i].nsec;
}
/* This will be hit if the operation was a flush or discard. */
if (!bio) {
BUG_ON(operation != WRITE_FLUSH);
bio = bio_alloc(GFP_KERNEL, 0);
if (unlikely(bio == NULL))
goto fail_put_bio;
biolist[nbio++] = bio;
bio->bi_bdev = preq.bdev;
bio->bi_private = pending_req;
bio->bi_end_io = end_block_io_op;
}
atomic_set(&pending_req->pendcnt, nbio);
blk_start_plug(&plug);
for (i = 0; i < nbio; i++)
submit_bio(operation, biolist[i]);
/* Let the I/Os go.. */
blk_finish_plug(&plug);
if (operation == READ)
blkif->st_rd_sect += preq.nr_sects;
else if (operation & WRITE)
blkif->st_wr_sect += preq.nr_sects;
return 0;
fail_flush:
xen_blkbk_unmap(blkif, pending_req->segments,
pending_req->nr_pages);
fail_response:
/* Haven't submitted any bio's yet. */
make_response(blkif, req->u.rw.id, req_operation, BLKIF_RSP_ERROR);
free_req(blkif, pending_req);
msleep(1); /* back off a bit */
return -EIO;
fail_put_bio:
for (i = 0; i < nbio; i++)
bio_put(biolist[i]);
atomic_set(&pending_req->pendcnt, 1);
__end_block_io_op(pending_req, -EINVAL);
msleep(1); /* back off a bit */
return -EIO;
}
/*
* Put a response on the ring on how the operation fared.
*/
static void make_response(struct xen_blkif *blkif, u64 id,
unsigned short op, int st)
{
struct blkif_response resp;
unsigned long flags;
union blkif_back_rings *blk_rings = &blkif->blk_rings;
int notify;
resp.id = id;
resp.operation = op;
resp.status = st;
spin_lock_irqsave(&blkif->blk_ring_lock, flags);
/* Place on the response ring for the relevant domain. */
switch (blkif->blk_protocol) {
case BLKIF_PROTOCOL_NATIVE:
memcpy(RING_GET_RESPONSE(&blk_rings->native, blk_rings->native.rsp_prod_pvt),
&resp, sizeof(resp));
break;
case BLKIF_PROTOCOL_X86_32:
memcpy(RING_GET_RESPONSE(&blk_rings->x86_32, blk_rings->x86_32.rsp_prod_pvt),
&resp, sizeof(resp));
break;
case BLKIF_PROTOCOL_X86_64:
memcpy(RING_GET_RESPONSE(&blk_rings->x86_64, blk_rings->x86_64.rsp_prod_pvt),
&resp, sizeof(resp));
break;
default:
BUG();
}
blk_rings->common.rsp_prod_pvt++;
RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&blk_rings->common, notify);
spin_unlock_irqrestore(&blkif->blk_ring_lock, flags);
if (notify)
notify_remote_via_irq(blkif->irq);
}
static int __init xen_blkif_init(void)
{
int rc = 0;
if (!xen_domain())
return -ENODEV;
rc = xen_blkif_interface_init();
if (rc)
goto failed_init;
rc = xen_blkif_xenbus_init();
if (rc)
goto failed_init;
failed_init:
return rc;
}
module_init(xen_blkif_init);
MODULE_LICENSE("Dual BSD/GPL");
MODULE_ALIAS("xen-backend:vbd");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5649_0 |
crossvul-cpp_data_bad_4701_2 | /*
server.c : irssi
Copyright (C) 1999-2000 Timo Sirainen
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "module.h"
#include "signals.h"
#include "commands.h"
#include "net-disconnect.h"
#include "net-nonblock.h"
#include "net-sendbuffer.h"
#include "misc.h"
#include "rawlog.h"
#include "settings.h"
#include "chat-protocols.h"
#include "servers.h"
#include "servers-reconnect.h"
#include "servers-setup.h"
#include "channels.h"
#include "queries.h"
GSList *servers, *lookup_servers;
/* connection to server failed */
void server_connect_failed(SERVER_REC *server, const char *msg)
{
g_return_if_fail(IS_SERVER(server));
lookup_servers = g_slist_remove(lookup_servers, server);
signal_emit("server connect failed", 2, server, msg);
if (server->connect_tag != -1) {
g_source_remove(server->connect_tag);
server->connect_tag = -1;
}
if (server->handle != NULL) {
net_sendbuffer_destroy(server->handle, TRUE);
server->handle = NULL;
}
if (server->connect_pipe[0] != NULL) {
g_io_channel_close(server->connect_pipe[0]);
g_io_channel_unref(server->connect_pipe[0]);
g_io_channel_close(server->connect_pipe[1]);
g_io_channel_unref(server->connect_pipe[1]);
server->connect_pipe[0] = NULL;
server->connect_pipe[1] = NULL;
}
server_unref(server);
}
/* generate tag from server's address */
static char *server_create_address_tag(const char *address)
{
const char *start, *end;
g_return_val_if_fail(address != NULL, NULL);
/* try to generate a reasonable server tag */
if (strchr(address, '.') == NULL) {
start = end = NULL;
} else if (g_ascii_strncasecmp(address, "irc", 3) == 0 ||
g_ascii_strncasecmp(address, "chat", 4) == 0) {
/* irc-2.cs.hut.fi -> hut, chat.bt.net -> bt */
end = strrchr(address, '.');
start = end-1;
while (start > address && *start != '.') start--;
} else {
/* efnet.cs.hut.fi -> efnet */
end = strchr(address, '.');
start = end;
}
if (start == end) start = address; else start++;
if (end == NULL) end = address + strlen(address);
return g_strndup(start, (int) (end-start));
}
/* create unique tag for server. prefer ircnet's name or
generate it from server's address */
static char *server_create_tag(SERVER_CONNECT_REC *conn)
{
GString *str;
char *tag;
int num;
g_return_val_if_fail(IS_SERVER_CONNECT(conn), NULL);
tag = conn->chatnet != NULL && *conn->chatnet != '\0' ?
g_strdup(conn->chatnet) :
server_create_address_tag(conn->address);
if (conn->tag != NULL && server_find_tag(conn->tag) == NULL &&
server_find_lookup_tag(conn->tag) == NULL &&
strncmp(conn->tag, tag, strlen(tag)) == 0) {
/* use the existing tag if it begins with the same ID -
this is useful when you have several connections to
same server and you want to keep the same tags with
the servers (or it would cause problems when rejoining
/LAYOUT SAVEd channels). */
g_free(tag);
return g_strdup(conn->tag);
}
/* then just append numbers after tag until unused is found.. */
str = g_string_new(tag);
num = 2;
while (server_find_tag(str->str) != NULL ||
server_find_lookup_tag(str->str) != NULL) {
g_string_printf(str, "%s%d", tag, num);
num++;
}
g_free(tag);
tag = str->str;
g_string_free(str, FALSE);
return tag;
}
/* Connection to server finished, fill the rest of the fields */
void server_connect_finished(SERVER_REC *server)
{
server->connect_time = time(NULL);
servers = g_slist_append(servers, server);
signal_emit("server connected", 1, server);
}
static void server_connect_callback_init(SERVER_REC *server, GIOChannel *handle)
{
int error;
g_return_if_fail(IS_SERVER(server));
error = net_geterror(handle);
if (error != 0) {
server->connection_lost = TRUE;
server_connect_failed(server, g_strerror(error));
return;
}
lookup_servers = g_slist_remove(lookup_servers, server);
g_source_remove(server->connect_tag);
server->connect_tag = -1;
server_connect_finished(server);
}
#ifdef HAVE_OPENSSL
static void server_connect_callback_init_ssl(SERVER_REC *server, GIOChannel *handle)
{
int error;
g_return_if_fail(IS_SERVER(server));
error = irssi_ssl_handshake(handle);
if (error == -1) {
server->connection_lost = TRUE;
server_connect_failed(server, NULL);
return;
}
if (error & 1) {
if (server->connect_tag != -1)
g_source_remove(server->connect_tag);
server->connect_tag = g_input_add(handle, error == 1 ? G_INPUT_READ : G_INPUT_WRITE,
(GInputFunction)
server_connect_callback_init_ssl,
server);
return;
}
lookup_servers = g_slist_remove(lookup_servers, server);
if (server->connect_tag != -1) {
g_source_remove(server->connect_tag);
server->connect_tag = -1;
}
server_connect_finished(server);
}
#endif
static void server_real_connect(SERVER_REC *server, IPADDR *ip,
const char *unix_socket)
{
GIOChannel *handle;
IPADDR *own_ip = NULL;
const char *errmsg;
char *errmsg2;
char ipaddr[MAX_IP_LEN];
int port;
g_return_if_fail(ip != NULL || unix_socket != NULL);
signal_emit("server connecting", 2, server, ip);
if (server->connrec->no_connect)
return;
if (ip != NULL) {
own_ip = ip == NULL ? NULL :
(IPADDR_IS_V6(ip) ? server->connrec->own_ip6 :
server->connrec->own_ip4);
port = server->connrec->proxy != NULL ?
server->connrec->proxy_port : server->connrec->port;
handle = server->connrec->use_ssl ?
net_connect_ip_ssl(ip, port, own_ip, server->connrec->ssl_cert, server->connrec->ssl_pkey,
server->connrec->ssl_cafile, server->connrec->ssl_capath, server->connrec->ssl_verify) :
net_connect_ip(ip, port, own_ip);
} else {
handle = net_connect_unix(unix_socket);
}
if (handle == NULL) {
/* failed */
errmsg = g_strerror(errno);
errmsg2 = NULL;
if (errno == EADDRNOTAVAIL) {
if (own_ip != NULL) {
/* show the IP which is causing the error */
net_ip2host(own_ip, ipaddr);
errmsg2 = g_strconcat(errmsg, ": ", ipaddr, NULL);
}
server->no_reconnect = TRUE;
}
if (server->connrec->use_ssl && errno == ENOSYS)
server->no_reconnect = TRUE;
server->connection_lost = TRUE;
server_connect_failed(server, errmsg2 ? errmsg2 : errmsg);
g_free(errmsg2);
} else {
server->handle = net_sendbuffer_create(handle, 0);
#ifdef HAVE_OPENSSL
if (server->connrec->use_ssl)
server_connect_callback_init_ssl(server, handle);
else
#endif
server->connect_tag =
g_input_add(handle, G_INPUT_WRITE | G_INPUT_READ,
(GInputFunction)
server_connect_callback_init,
server);
}
}
static void server_connect_callback_readpipe(SERVER_REC *server)
{
RESOLVED_IP_REC iprec;
IPADDR *ip;
const char *errormsg;
char *servername = NULL;
g_source_remove(server->connect_tag);
server->connect_tag = -1;
net_gethostbyname_return(server->connect_pipe[0], &iprec);
g_io_channel_close(server->connect_pipe[0]);
g_io_channel_unref(server->connect_pipe[0]);
g_io_channel_close(server->connect_pipe[1]);
g_io_channel_unref(server->connect_pipe[1]);
server->connect_pipe[0] = NULL;
server->connect_pipe[1] = NULL;
/* figure out if we should use IPv4 or v6 address */
if (iprec.error != 0) {
/* error */
ip = NULL;
} else if (server->connrec->family == AF_INET) {
/* force IPv4 connection */
ip = iprec.ip4.family == 0 ? NULL : &iprec.ip4;
servername = iprec.host4;
} else if (server->connrec->family == AF_INET6) {
/* force IPv6 connection */
ip = iprec.ip6.family == 0 ? NULL : &iprec.ip6;
servername = iprec.host6;
} else {
/* pick the one that was found, or if both do it like
/SET resolve_prefer_ipv6 says. */
if (iprec.ip4.family == 0 ||
(iprec.ip6.family != 0 &&
settings_get_bool("resolve_prefer_ipv6"))) {
ip = &iprec.ip6;
servername = iprec.host6;
} else {
ip = &iprec.ip4;
servername = iprec.host4;
}
}
if (ip != NULL) {
/* host lookup ok */
if (servername) {
g_free(server->connrec->address);
server->connrec->address = g_strdup(servername);
}
server_real_connect(server, ip, NULL);
errormsg = NULL;
} else {
if (iprec.error == 0 || net_hosterror_notfound(iprec.error)) {
/* IP wasn't found for the host, don't try to
reconnect back to this server */
server->dns_error = TRUE;
}
if (iprec.error == 0) {
/* forced IPv4 or IPv6 address but it wasn't found */
errormsg = server->connrec->family == AF_INET ?
"IPv4 address not found for host" :
"IPv6 address not found for host";
} else {
/* gethostbyname() failed */
errormsg = iprec.errorstr != NULL ? iprec.errorstr :
"Host lookup failed";
}
server->connection_lost = TRUE;
server_connect_failed(server, errormsg);
}
g_free(iprec.errorstr);
g_free(iprec.host4);
g_free(iprec.host6);
}
SERVER_REC *server_connect(SERVER_CONNECT_REC *conn)
{
CHAT_PROTOCOL_REC *proto;
SERVER_REC *server;
proto = CHAT_PROTOCOL(conn);
server = proto->server_init_connect(conn);
proto->server_connect(server);
return server;
}
/* initializes server record but doesn't start connecting */
void server_connect_init(SERVER_REC *server)
{
const char *str;
g_return_if_fail(server != NULL);
MODULE_DATA_INIT(server);
server->type = module_get_uniq_id("SERVER", 0);
server_ref(server);
server->nick = g_strdup(server->connrec->nick);
if (server->connrec->username == NULL || *server->connrec->username == '\0') {
g_free_not_null(server->connrec->username);
str = g_get_user_name();
if (*str == '\0') str = "unknown";
server->connrec->username = g_strdup(str);
}
if (server->connrec->realname == NULL || *server->connrec->realname == '\0') {
g_free_not_null(server->connrec->realname);
str = g_get_real_name();
if (*str == '\0') str = server->connrec->username;
server->connrec->realname = g_strdup(str);
}
server->tag = server_create_tag(server->connrec);
server->connect_tag = -1;
}
/* starts connecting to server */
int server_start_connect(SERVER_REC *server)
{
const char *connect_address;
int fd[2];
g_return_val_if_fail(server != NULL, FALSE);
if (!server->connrec->unix_socket && server->connrec->port <= 0)
return FALSE;
server->rawlog = rawlog_create();
if (server->connrec->connect_handle != NULL) {
/* already connected */
GIOChannel *handle = server->connrec->connect_handle;
server->connrec->connect_handle = NULL;
server->handle = net_sendbuffer_create(handle, 0);
server_connect_finished(server);
} else if (server->connrec->unix_socket) {
/* connect with unix socket */
server_real_connect(server, NULL, server->connrec->address);
} else {
/* resolve host name */
if (pipe(fd) != 0) {
g_warning("server_connect(): pipe() failed.");
g_free(server->tag);
g_free(server->nick);
return FALSE;
}
server->connect_pipe[0] = g_io_channel_unix_new(fd[0]);
server->connect_pipe[1] = g_io_channel_unix_new(fd[1]);
connect_address = server->connrec->proxy != NULL ?
server->connrec->proxy : server->connrec->address;
server->connect_pid =
net_gethostbyname_nonblock(connect_address,
server->connect_pipe[1],
settings_get_bool("resolve_reverse_lookup"));
server->connect_tag =
g_input_add(server->connect_pipe[0], G_INPUT_READ,
(GInputFunction)
server_connect_callback_readpipe,
server);
lookup_servers = g_slist_append(lookup_servers, server);
signal_emit("server looking", 1, server);
}
return TRUE;
}
static int server_remove_channels(SERVER_REC *server)
{
GSList *tmp, *next;
int found;
g_return_val_if_fail(server != NULL, FALSE);
found = FALSE;
for (tmp = server->channels; tmp != NULL; tmp = next) {
CHANNEL_REC *channel = tmp->data;
next = tmp->next;
channel_destroy(channel);
found = TRUE;
}
while (server->queries != NULL)
query_change_server(server->queries->data, NULL);
g_slist_free(server->channels);
g_slist_free(server->queries);
return found;
}
void server_disconnect(SERVER_REC *server)
{
int chans;
g_return_if_fail(IS_SERVER(server));
if (server->disconnected)
return;
if (server->connect_tag != -1) {
/* still connecting to server.. */
if (server->connect_pid != -1)
net_disconnect_nonblock(server->connect_pid);
server_connect_failed(server, NULL);
return;
}
servers = g_slist_remove(servers, server);
server->disconnected = TRUE;
signal_emit("server disconnected", 1, server);
/* close all channels */
chans = server_remove_channels(server);
if (server->handle != NULL) {
if (!chans || server->connection_lost)
net_sendbuffer_destroy(server->handle, TRUE);
else {
/* we were on some channels, try to let the server
disconnect so that our quit message is guaranteed
to get displayed */
net_disconnect_later(net_sendbuffer_handle(server->handle));
net_sendbuffer_destroy(server->handle, FALSE);
}
server->handle = NULL;
}
if (server->readtag > 0) {
g_source_remove(server->readtag);
server->readtag = -1;
}
server_unref(server);
}
void server_ref(SERVER_REC *server)
{
g_return_if_fail(IS_SERVER(server));
server->refcount++;
}
int server_unref(SERVER_REC *server)
{
g_return_val_if_fail(IS_SERVER(server), FALSE);
if (--server->refcount > 0)
return TRUE;
if (g_slist_find(servers, server) != NULL) {
g_warning("Non-referenced server wasn't disconnected");
server_disconnect(server);
return TRUE;
}
MODULE_DATA_DEINIT(server);
server_connect_unref(server->connrec);
if (server->rawlog != NULL) rawlog_destroy(server->rawlog);
g_free(server->version);
g_free(server->away_reason);
g_free(server->nick);
g_free(server->tag);
server->type = 0;
g_free(server);
return FALSE;
}
SERVER_REC *server_find_tag(const char *tag)
{
GSList *tmp;
g_return_val_if_fail(tag != NULL, NULL);
if (*tag == '\0') return NULL;
for (tmp = servers; tmp != NULL; tmp = tmp->next) {
SERVER_REC *server = tmp->data;
if (g_strcasecmp(server->tag, tag) == 0)
return server;
}
return NULL;
}
SERVER_REC *server_find_lookup_tag(const char *tag)
{
GSList *tmp;
g_return_val_if_fail(tag != NULL, NULL);
if (*tag == '\0') return NULL;
for (tmp = lookup_servers; tmp != NULL; tmp = tmp->next) {
SERVER_REC *server = tmp->data;
if (g_strcasecmp(server->tag, tag) == 0)
return server;
}
return NULL;
}
SERVER_REC *server_find_chatnet(const char *chatnet)
{
GSList *tmp;
g_return_val_if_fail(chatnet != NULL, NULL);
if (*chatnet == '\0') return NULL;
for (tmp = servers; tmp != NULL; tmp = tmp->next) {
SERVER_REC *server = tmp->data;
if (server->connrec->chatnet != NULL &&
g_strcasecmp(server->connrec->chatnet, chatnet) == 0)
return server;
}
return NULL;
}
void server_connect_ref(SERVER_CONNECT_REC *conn)
{
conn->refcount++;
}
void server_connect_unref(SERVER_CONNECT_REC *conn)
{
g_return_if_fail(IS_SERVER_CONNECT(conn));
if (--conn->refcount > 0)
return;
if (conn->refcount < 0) {
g_warning("Connection '%s' refcount = %d",
conn->tag, conn->refcount);
}
CHAT_PROTOCOL(conn)->destroy_server_connect(conn);
if (conn->connect_handle != NULL)
net_disconnect(conn->connect_handle);
g_free_not_null(conn->proxy);
g_free_not_null(conn->proxy_string);
g_free_not_null(conn->proxy_string_after);
g_free_not_null(conn->proxy_password);
g_free_not_null(conn->tag);
g_free_not_null(conn->address);
g_free_not_null(conn->chatnet);
g_free_not_null(conn->own_ip4);
g_free_not_null(conn->own_ip6);
g_free_not_null(conn->password);
g_free_not_null(conn->nick);
g_free_not_null(conn->username);
g_free_not_null(conn->realname);
g_free_not_null(conn->ssl_cert);
g_free_not_null(conn->ssl_pkey);
g_free_not_null(conn->ssl_cafile);
g_free_not_null(conn->ssl_capath);
g_free_not_null(conn->channels);
g_free_not_null(conn->away_reason);
conn->type = 0;
g_free(conn);
}
void server_change_nick(SERVER_REC *server, const char *nick)
{
g_free(server->nick);
server->nick = g_strdup(nick);
signal_emit("server nick changed", 1, server);
}
/* Update own IPv4 and IPv6 records */
void server_connect_own_ip_save(SERVER_CONNECT_REC *conn,
IPADDR *ip4, IPADDR *ip6)
{
if (ip4 == NULL || ip4->family == 0)
g_free_and_null(conn->own_ip4);
if (ip6 == NULL || ip6->family == 0)
g_free_and_null(conn->own_ip6);
if (ip4 != NULL && ip4->family != 0) {
/* IPv4 address was found */
if (conn->own_ip4 == NULL)
conn->own_ip4 = g_new0(IPADDR, 1);
memcpy(conn->own_ip4, ip4, sizeof(IPADDR));
}
if (ip6 != NULL && ip6->family != 0) {
/* IPv6 address was found */
if (conn->own_ip6 == NULL)
conn->own_ip6 = g_new0(IPADDR, 1);
memcpy(conn->own_ip6, ip6, sizeof(IPADDR));
}
}
/* `optlist' should contain only one unknown key - the server tag.
returns NULL if there was unknown -option */
SERVER_REC *cmd_options_get_server(const char *cmd,
GHashTable *optlist,
SERVER_REC *defserver)
{
SERVER_REC *server;
GSList *list, *tmp, *next;
/* get all the options, then remove the known ones. there should
be only one left - the server tag. */
list = hashtable_get_keys(optlist);
if (cmd != NULL) {
for (tmp = list; tmp != NULL; tmp = next) {
char *option = tmp->data;
next = tmp->next;
if (command_have_option(cmd, option))
list = g_slist_remove(list, option);
}
}
if (list == NULL)
return defserver;
server = server_find_tag(list->data);
if (server == NULL || list->next != NULL) {
/* unknown option (not server tag) */
signal_emit("error command", 2,
GINT_TO_POINTER(CMDERR_OPTION_UNKNOWN),
server == NULL ? list->data : list->next->data);
signal_stop();
server = NULL;
}
g_slist_free(list);
return server;
}
static void disconnect_servers(GSList *servers, int chat_type)
{
GSList *tmp, *next;
for (tmp = servers; tmp != NULL; tmp = next) {
SERVER_REC *rec = tmp->data;
next = tmp->next;
if (rec->chat_type == chat_type)
server_disconnect(rec);
}
}
static void sig_chat_protocol_deinit(CHAT_PROTOCOL_REC *proto)
{
disconnect_servers(servers, proto->id);
disconnect_servers(lookup_servers, proto->id);
}
void servers_init(void)
{
settings_add_bool("server", "resolve_prefer_ipv6", FALSE);
settings_add_bool("server", "resolve_reverse_lookup", FALSE);
lookup_servers = servers = NULL;
signal_add("chat protocol deinit", (SIGNAL_FUNC) sig_chat_protocol_deinit);
servers_reconnect_init();
servers_setup_init();
}
void servers_deinit(void)
{
signal_remove("chat protocol deinit", (SIGNAL_FUNC) sig_chat_protocol_deinit);
servers_setup_deinit();
servers_reconnect_deinit();
module_uniq_destroy("SERVER");
module_uniq_destroy("SERVER CONNECT");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4701_2 |
crossvul-cpp_data_good_2891_11 | /* Request key authorisation token key definition.
*
* Copyright (C) 2005 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* See Documentation/security/keys/request-key.rst
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/err.h>
#include <linux/seq_file.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include "internal.h"
#include <keys/user-type.h>
static int request_key_auth_preparse(struct key_preparsed_payload *);
static void request_key_auth_free_preparse(struct key_preparsed_payload *);
static int request_key_auth_instantiate(struct key *,
struct key_preparsed_payload *);
static void request_key_auth_describe(const struct key *, struct seq_file *);
static void request_key_auth_revoke(struct key *);
static void request_key_auth_destroy(struct key *);
static long request_key_auth_read(const struct key *, char __user *, size_t);
/*
* The request-key authorisation key type definition.
*/
struct key_type key_type_request_key_auth = {
.name = ".request_key_auth",
.def_datalen = sizeof(struct request_key_auth),
.preparse = request_key_auth_preparse,
.free_preparse = request_key_auth_free_preparse,
.instantiate = request_key_auth_instantiate,
.describe = request_key_auth_describe,
.revoke = request_key_auth_revoke,
.destroy = request_key_auth_destroy,
.read = request_key_auth_read,
};
static int request_key_auth_preparse(struct key_preparsed_payload *prep)
{
return 0;
}
static void request_key_auth_free_preparse(struct key_preparsed_payload *prep)
{
}
/*
* Instantiate a request-key authorisation key.
*/
static int request_key_auth_instantiate(struct key *key,
struct key_preparsed_payload *prep)
{
key->payload.data[0] = (struct request_key_auth *)prep->data;
return 0;
}
/*
* Describe an authorisation token.
*/
static void request_key_auth_describe(const struct key *key,
struct seq_file *m)
{
struct request_key_auth *rka = key->payload.data[0];
seq_puts(m, "key:");
seq_puts(m, key->description);
if (key_is_positive(key))
seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len);
}
/*
* Read the callout_info data (retrieves the callout information).
* - the key's semaphore is read-locked
*/
static long request_key_auth_read(const struct key *key,
char __user *buffer, size_t buflen)
{
struct request_key_auth *rka = key->payload.data[0];
size_t datalen;
long ret;
datalen = rka->callout_len;
ret = datalen;
/* we can return the data as is */
if (buffer && buflen > 0) {
if (buflen > datalen)
buflen = datalen;
if (copy_to_user(buffer, rka->callout_info, buflen) != 0)
ret = -EFAULT;
}
return ret;
}
/*
* Handle revocation of an authorisation token key.
*
* Called with the key sem write-locked.
*/
static void request_key_auth_revoke(struct key *key)
{
struct request_key_auth *rka = key->payload.data[0];
kenter("{%d}", key->serial);
if (rka->cred) {
put_cred(rka->cred);
rka->cred = NULL;
}
}
static void free_request_key_auth(struct request_key_auth *rka)
{
if (!rka)
return;
key_put(rka->target_key);
key_put(rka->dest_keyring);
if (rka->cred)
put_cred(rka->cred);
kfree(rka->callout_info);
kfree(rka);
}
/*
* Destroy an instantiation authorisation token key.
*/
static void request_key_auth_destroy(struct key *key)
{
struct request_key_auth *rka = key->payload.data[0];
kenter("{%d}", key->serial);
free_request_key_auth(rka);
}
/*
* Create an authorisation token for /sbin/request-key or whoever to gain
* access to the caller's security data.
*/
struct key *request_key_auth_new(struct key *target, const void *callout_info,
size_t callout_len, struct key *dest_keyring)
{
struct request_key_auth *rka, *irka;
const struct cred *cred = current->cred;
struct key *authkey = NULL;
char desc[20];
int ret = -ENOMEM;
kenter("%d,", target->serial);
/* allocate a auth record */
rka = kzalloc(sizeof(*rka), GFP_KERNEL);
if (!rka)
goto error;
rka->callout_info = kmemdup(callout_info, callout_len, GFP_KERNEL);
if (!rka->callout_info)
goto error_free_rka;
rka->callout_len = callout_len;
/* see if the calling process is already servicing the key request of
* another process */
if (cred->request_key_auth) {
/* it is - use that instantiation context here too */
down_read(&cred->request_key_auth->sem);
/* if the auth key has been revoked, then the key we're
* servicing is already instantiated */
if (test_bit(KEY_FLAG_REVOKED,
&cred->request_key_auth->flags)) {
up_read(&cred->request_key_auth->sem);
ret = -EKEYREVOKED;
goto error_free_rka;
}
irka = cred->request_key_auth->payload.data[0];
rka->cred = get_cred(irka->cred);
rka->pid = irka->pid;
up_read(&cred->request_key_auth->sem);
}
else {
/* it isn't - use this process as the context */
rka->cred = get_cred(cred);
rka->pid = current->pid;
}
rka->target_key = key_get(target);
rka->dest_keyring = key_get(dest_keyring);
/* allocate the auth key */
sprintf(desc, "%x", target->serial);
authkey = key_alloc(&key_type_request_key_auth, desc,
cred->fsuid, cred->fsgid, cred,
KEY_POS_VIEW | KEY_POS_READ | KEY_POS_SEARCH |
KEY_USR_VIEW, KEY_ALLOC_NOT_IN_QUOTA, NULL);
if (IS_ERR(authkey)) {
ret = PTR_ERR(authkey);
goto error_free_rka;
}
/* construct the auth key */
ret = key_instantiate_and_link(authkey, rka, 0, NULL, NULL);
if (ret < 0)
goto error_put_authkey;
kleave(" = {%d,%d}", authkey->serial, refcount_read(&authkey->usage));
return authkey;
error_put_authkey:
key_put(authkey);
error_free_rka:
free_request_key_auth(rka);
error:
kleave("= %d", ret);
return ERR_PTR(ret);
}
/*
* Search the current process's keyrings for the authorisation key for
* instantiation of a key.
*/
struct key *key_get_instantiation_authkey(key_serial_t target_id)
{
char description[16];
struct keyring_search_context ctx = {
.index_key.type = &key_type_request_key_auth,
.index_key.description = description,
.cred = current_cred(),
.match_data.cmp = key_default_cmp,
.match_data.raw_data = description,
.match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT,
.flags = KEYRING_SEARCH_DO_STATE_CHECK,
};
struct key *authkey;
key_ref_t authkey_ref;
sprintf(description, "%x", target_id);
authkey_ref = search_process_keyrings(&ctx);
if (IS_ERR(authkey_ref)) {
authkey = ERR_CAST(authkey_ref);
if (authkey == ERR_PTR(-EAGAIN))
authkey = ERR_PTR(-ENOKEY);
goto error;
}
authkey = key_ref_to_ptr(authkey_ref);
if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) {
key_put(authkey);
authkey = ERR_PTR(-EKEYREVOKED);
}
error:
return authkey;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2891_11 |
crossvul-cpp_data_good_3987_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "path.h"
#include "posix.h"
#include "repository.h"
#ifdef GIT_WIN32
#include "win32/posix.h"
#include "win32/w32_buffer.h"
#include "win32/w32_util.h"
#include "win32/version.h"
#include <aclapi.h>
#else
#include <dirent.h>
#endif
#include <stdio.h>
#include <ctype.h>
#define LOOKS_LIKE_DRIVE_PREFIX(S) (git__isalpha((S)[0]) && (S)[1] == ':')
#ifdef GIT_WIN32
static bool looks_like_network_computer_name(const char *path, int pos)
{
if (pos < 3)
return false;
if (path[0] != '/' || path[1] != '/')
return false;
while (pos-- > 2) {
if (path[pos] == '/')
return false;
}
return true;
}
#endif
/*
* Based on the Android implementation, BSD licensed.
* http://android.git.kernel.org/
*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git_path_basename_r(git_buf *buffer, const char *path)
{
const char *endp, *startp;
int len, result;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
startp = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
/* All slashes becomes "/" */
if (endp == path && *endp == '/') {
startp = "/";
len = 1;
goto Exit;
}
/* Find the start of the base */
startp = endp;
while (startp > path && *(startp - 1) != '/')
startp--;
/* Cast is safe because max path < max int */
len = (int)(endp - startp + 1);
Exit:
result = len;
if (buffer != NULL && git_buf_set(buffer, startp, len) < 0)
return -1;
return result;
}
/*
* Determine if the path is a Windows prefix and, if so, returns
* its actual lentgh. If it is not a prefix, returns -1.
*/
static int win32_prefix_length(const char *path, int len)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
GIT_UNUSED(len);
#else
/*
* Mimic unix behavior where '/.git' returns '/': 'C:/.git' will return
* 'C:/' here
*/
if (len == 2 && LOOKS_LIKE_DRIVE_PREFIX(path))
return 2;
/*
* Similarly checks if we're dealing with a network computer name
* '//computername/.git' will return '//computername/'
*/
if (looks_like_network_computer_name(path, len))
return len;
#endif
return -1;
}
/*
* Based on the Android implementation, BSD licensed.
* Check http://android.git.kernel.org/
*/
int git_path_dirname_r(git_buf *buffer, const char *path)
{
const char *endp;
int is_prefix = 0, len;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
path = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Find the start of the dir */
while (endp > path && *endp != '/')
endp--;
/* Either the dir is "/" or there are no slashes */
if (endp == path) {
path = (*endp == '/') ? "/" : ".";
len = 1;
goto Exit;
}
do {
endp--;
} while (endp > path && *endp == '/');
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Cast is safe because max path < max int */
len = (int)(endp - path + 1);
Exit:
if (buffer) {
if (git_buf_set(buffer, path, len) < 0)
return -1;
if (is_prefix && git_buf_putc(buffer, '/') < 0)
return -1;
}
return len;
}
char *git_path_dirname(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *dirname;
git_path_dirname_r(&buf, path);
dirname = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return dirname;
}
char *git_path_basename(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *basename;
git_path_basename_r(&buf, path);
basename = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return basename;
}
size_t git_path_basename_offset(git_buf *buffer)
{
ssize_t slash;
if (!buffer || buffer->size <= 0)
return 0;
slash = git_buf_rfind_next(buffer, '/');
if (slash >= 0 && buffer->ptr[slash] == '/')
return (size_t)(slash + 1);
return 0;
}
const char *git_path_topdir(const char *path)
{
size_t len;
ssize_t i;
assert(path);
len = strlen(path);
if (!len || path[len - 1] != '/')
return NULL;
for (i = (ssize_t)len - 2; i >= 0; --i)
if (path[i] == '/')
break;
return &path[i + 1];
}
int git_path_root(const char *path)
{
int offset = 0;
/* Does the root of the path look like a windows drive ? */
if (LOOKS_LIKE_DRIVE_PREFIX(path))
offset += 2;
#ifdef GIT_WIN32
/* Are we dealing with a windows network path? */
else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
(path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
{
offset += 2;
/* Skip the computer name segment */
while (path[offset] && path[offset] != '/' && path[offset] != '\\')
offset++;
}
if (path[offset] == '\\')
return offset;
#endif
if (path[offset] == '/')
return offset;
return -1; /* Not a real error - signals that path is not rooted */
}
void git_path_trim_slashes(git_buf *path)
{
int ceiling = git_path_root(path->ptr) + 1;
assert(ceiling >= 0);
while (path->size > (size_t)ceiling) {
if (path->ptr[path->size-1] != '/')
break;
path->ptr[path->size-1] = '\0';
path->size--;
}
}
int git_path_join_unrooted(
git_buf *path_out, const char *path, const char *base, ssize_t *root_at)
{
ssize_t root;
assert(path && path_out);
root = (ssize_t)git_path_root(path);
if (base != NULL && root < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
root = (ssize_t)strlen(base);
} else {
if (git_buf_sets(path_out, path) < 0)
return -1;
if (root < 0)
root = 0;
else if (base)
git_path_equal_or_prefixed(base, path, &root);
}
if (root_at)
*root_at = root;
return 0;
}
void git_path_squash_slashes(git_buf *path)
{
char *p, *q;
if (path->size == 0)
return;
for (p = path->ptr, q = path->ptr; *q; p++, q++) {
*p = *q;
while (*q == '/' && *(q+1) == '/') {
path->size--;
q++;
}
}
*p = '\0';
}
int git_path_prettify(git_buf *path_out, const char *path, const char *base)
{
char buf[GIT_PATH_MAX];
assert(path && path_out);
/* construct path if needed */
if (base != NULL && git_path_root(path) < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
path = path_out->ptr;
}
if (p_realpath(path, buf) == NULL) {
/* git_error_set resets the errno when dealing with a GIT_ERROR_OS kind of error */
int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
git_error_set(GIT_ERROR_OS, "failed to resolve path '%s'", path);
git_buf_clear(path_out);
return error;
}
return git_buf_sets(path_out, buf);
}
int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
{
int error = git_path_prettify(path_out, path, base);
return (error < 0) ? error : git_path_to_dir(path_out);
}
int git_path_to_dir(git_buf *path)
{
if (path->asize > 0 &&
git_buf_len(path) > 0 &&
path->ptr[git_buf_len(path) - 1] != '/')
git_buf_putc(path, '/');
return git_buf_oom(path) ? -1 : 0;
}
void git_path_string_to_dir(char* path, size_t size)
{
size_t end = strlen(path);
if (end && path[end - 1] != '/' && end < size) {
path[end] = '/';
path[end + 1] = '\0';
}
}
int git__percent_decode(git_buf *decoded_out, const char *input)
{
int len, hi, lo, i;
assert(decoded_out && input);
len = (int)strlen(input);
git_buf_clear(decoded_out);
for(i = 0; i < len; i++)
{
char c = input[i];
if (c != '%')
goto append;
if (i >= len - 2)
goto append;
hi = git__fromhex(input[i + 1]);
lo = git__fromhex(input[i + 2]);
if (hi < 0 || lo < 0)
goto append;
c = (char)(hi << 4 | lo);
i += 2;
append:
if (git_buf_putc(decoded_out, c) < 0)
return -1;
}
return 0;
}
static int error_invalid_local_file_uri(const char *uri)
{
git_error_set(GIT_ERROR_CONFIG, "'%s' is not a valid local file URI", uri);
return -1;
}
static int local_file_url_prefixlen(const char *file_url)
{
int len = -1;
if (git__prefixcmp(file_url, "file://") == 0) {
if (file_url[7] == '/')
len = 8;
else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
len = 17;
}
return len;
}
bool git_path_is_local_file_url(const char *file_url)
{
return (local_file_url_prefixlen(file_url) > 0);
}
int git_path_fromurl(git_buf *local_path_out, const char *file_url)
{
int offset;
assert(local_path_out && file_url);
if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
file_url[offset] == '\0' || file_url[offset] == '/')
return error_invalid_local_file_uri(file_url);
#ifndef GIT_WIN32
offset--; /* A *nix absolute path starts with a forward slash */
#endif
git_buf_clear(local_path_out);
return git__percent_decode(local_path_out, file_url + offset);
}
int git_path_walk_up(
git_buf *path,
const char *ceiling,
int (*cb)(void *data, const char *),
void *data)
{
int error = 0;
git_buf iter;
ssize_t stop = 0, scan;
char oldc = '\0';
assert(path && cb);
if (ceiling != NULL) {
if (git__prefixcmp(path->ptr, ceiling) == 0)
stop = (ssize_t)strlen(ceiling);
else
stop = git_buf_len(path);
}
scan = git_buf_len(path);
/* empty path: yield only once */
if (!scan) {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
return error;
}
iter.ptr = path->ptr;
iter.size = git_buf_len(path);
iter.asize = path->asize;
while (scan >= stop) {
error = cb(data, iter.ptr);
iter.ptr[scan] = oldc;
if (error) {
git_error_set_after_callback(error);
break;
}
scan = git_buf_rfind_next(&iter, '/');
if (scan >= 0) {
scan++;
oldc = iter.ptr[scan];
iter.size = scan;
iter.ptr[scan] = '\0';
}
}
if (scan >= 0)
iter.ptr[scan] = oldc;
/* relative path: yield for the last component */
if (!error && stop == 0 && iter.ptr[0] != '/') {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
}
return error;
}
bool git_path_exists(const char *path)
{
assert(path);
return p_access(path, F_OK) == 0;
}
bool git_path_isdir(const char *path)
{
struct stat st;
if (p_stat(path, &st) < 0)
return false;
return S_ISDIR(st.st_mode) != 0;
}
bool git_path_isfile(const char *path)
{
struct stat st;
assert(path);
if (p_stat(path, &st) < 0)
return false;
return S_ISREG(st.st_mode) != 0;
}
bool git_path_islink(const char *path)
{
struct stat st;
assert(path);
if (p_lstat(path, &st) < 0)
return false;
return S_ISLNK(st.st_mode) != 0;
}
#ifdef GIT_WIN32
bool git_path_is_empty_dir(const char *path)
{
git_win32_path filter_w;
bool empty = false;
if (git_win32__findfirstfile_filter(filter_w, path)) {
WIN32_FIND_DATAW findData;
HANDLE hFind = FindFirstFileW(filter_w, &findData);
/* FindFirstFile will fail if there are no children to the given
* path, which can happen if the given path is a file (and obviously
* has no children) or if the given path is an empty mount point.
* (Most directories have at least directory entries '.' and '..',
* but ridiculously another volume mounted in another drive letter's
* path space do not, and thus have nothing to enumerate.) If
* FindFirstFile fails, check if this is a directory-like thing
* (a mount point).
*/
if (hFind == INVALID_HANDLE_VALUE)
return git_path_isdir(path);
/* If the find handle was created successfully, then it's a directory */
empty = true;
do {
/* Allow the enumeration to return . and .. and still be considered
* empty. In the special case of drive roots (i.e. C:\) where . and
* .. do not occur, we can still consider the path to be an empty
* directory if there's nothing there. */
if (!git_path_is_dot_or_dotdotW(findData.cFileName)) {
empty = false;
break;
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
return empty;
}
#else
static int path_found_entry(void *payload, git_buf *path)
{
GIT_UNUSED(payload);
return !git_path_is_dot_or_dotdot(path->ptr);
}
bool git_path_is_empty_dir(const char *path)
{
int error;
git_buf dir = GIT_BUF_INIT;
if (!git_path_isdir(path))
return false;
if ((error = git_buf_sets(&dir, path)) != 0)
git_error_clear();
else
error = git_path_direach(&dir, 0, path_found_entry, NULL);
git_buf_dispose(&dir);
return !error;
}
#endif
int git_path_set_error(int errno_value, const char *path, const char *action)
{
switch (errno_value) {
case ENOENT:
case ENOTDIR:
git_error_set(GIT_ERROR_OS, "could not find '%s' to %s", path, action);
return GIT_ENOTFOUND;
case EINVAL:
case ENAMETOOLONG:
git_error_set(GIT_ERROR_OS, "invalid path for filesystem '%s'", path);
return GIT_EINVALIDSPEC;
case EEXIST:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' already exists", action, path);
return GIT_EEXISTS;
case EACCES:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' is locked", action, path);
return GIT_ELOCKED;
default:
git_error_set(GIT_ERROR_OS, "could not %s '%s'", action, path);
return -1;
}
}
int git_path_lstat(const char *path, struct stat *st)
{
if (p_lstat(path, st) == 0)
return 0;
return git_path_set_error(errno, path, "stat");
}
static bool _check_dir_contents(
git_buf *dir,
const char *sub,
bool (*predicate)(const char *))
{
bool result;
size_t dir_size = git_buf_len(dir);
size_t sub_size = strlen(sub);
size_t alloc_size;
/* leave base valid even if we could not make space for subdir */
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
git_buf_try_grow(dir, alloc_size, false) < 0)
return false;
/* save excursion */
if (git_buf_joinpath(dir, dir->ptr, sub) < 0)
return false;
result = predicate(dir->ptr);
/* restore path */
git_buf_truncate(dir, dir_size);
return result;
}
bool git_path_contains(git_buf *dir, const char *item)
{
return _check_dir_contents(dir, item, &git_path_exists);
}
bool git_path_contains_dir(git_buf *base, const char *subdir)
{
return _check_dir_contents(base, subdir, &git_path_isdir);
}
bool git_path_contains_file(git_buf *base, const char *file)
{
return _check_dir_contents(base, file, &git_path_isfile);
}
int git_path_find_dir(git_buf *dir, const char *path, const char *base)
{
int error = git_path_join_unrooted(dir, path, base, NULL);
if (!error) {
char buf[GIT_PATH_MAX];
if (p_realpath(dir->ptr, buf) != NULL)
error = git_buf_sets(dir, buf);
}
/* call dirname if this is not a directory */
if (!error) /* && git_path_isdir(dir->ptr) == false) */
error = (git_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
if (!error)
error = git_path_to_dir(dir);
return error;
}
int git_path_resolve_relative(git_buf *path, size_t ceiling)
{
char *base, *to, *from, *next;
size_t len;
GIT_ERROR_CHECK_ALLOC_BUF(path);
if (ceiling > path->size)
ceiling = path->size;
/* recognize drive prefixes, etc. that should not be backed over */
if (ceiling == 0)
ceiling = git_path_root(path->ptr) + 1;
/* recognize URL prefixes that should not be backed over */
if (ceiling == 0) {
for (next = path->ptr; *next && git__isalpha(*next); ++next);
if (next[0] == ':' && next[1] == '/' && next[2] == '/')
ceiling = (next + 3) - path->ptr;
}
base = to = from = path->ptr + ceiling;
while (*from) {
for (next = from; *next && *next != '/'; ++next);
len = next - from;
if (len == 1 && from[0] == '.')
/* do nothing with singleton dot */;
else if (len == 2 && from[0] == '.' && from[1] == '.') {
/* error out if trying to up one from a hard base */
if (to == base && ceiling != 0) {
git_error_set(GIT_ERROR_INVALID,
"cannot strip root component off url");
return -1;
}
/* no more path segments to strip,
* use '../' as a new base path */
if (to == base) {
if (*next == '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
/* this is now the base, can't back up from a
* relative prefix */
base = to;
} else {
/* back up a path segment */
while (to > base && to[-1] == '/') to--;
while (to > base && to[-1] != '/') to--;
}
} else {
if (*next == '/' && *from != '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
}
from += len;
while (*from == '/') from++;
}
*to = '\0';
path->size = to - path->ptr;
return 0;
}
int git_path_apply_relative(git_buf *target, const char *relpath)
{
return git_buf_joinpath(target, git_buf_cstr(target), relpath) ||
git_path_resolve_relative(target, 0);
}
int git_path_cmp(
const char *name1, size_t len1, int isdir1,
const char *name2, size_t len2, int isdir2,
int (*compare)(const char *, const char *, size_t))
{
unsigned char c1, c2;
size_t len = len1 < len2 ? len1 : len2;
int cmp;
cmp = compare(name1, name2, len);
if (cmp)
return cmp;
c1 = name1[len];
c2 = name2[len];
if (c1 == '\0' && isdir1)
c1 = '/';
if (c2 == '\0' && isdir2)
c2 = '/';
return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}
size_t git_path_common_dirlen(const char *one, const char *two)
{
const char *p, *q, *dirsep = NULL;
for (p = one, q = two; *p && *q; p++, q++) {
if (*p == '/' && *q == '/')
dirsep = p;
else if (*p != *q)
break;
}
return dirsep ? (dirsep - one) + 1 : 0;
}
int git_path_make_relative(git_buf *path, const char *parent)
{
const char *p, *q, *p_dirsep, *q_dirsep;
size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
if (*p == '/' && *q == '/') {
p_dirsep = p;
q_dirsep = q;
}
else if (*p != *q)
break;
}
/* need at least 1 common path segment */
if ((p_dirsep == path->ptr || q_dirsep == parent) &&
(*p_dirsep != '/' || *q_dirsep != '/')) {
git_error_set(GIT_ERROR_INVALID,
"%s is not a parent of %s", parent, path->ptr);
return GIT_ENOTFOUND;
}
if (*p == '/' && !*q)
p++;
else if (!*p && *q == '/')
q++;
else if (!*p && !*q)
return git_buf_clear(path), 0;
else {
p = p_dirsep + 1;
q = q_dirsep + 1;
}
plen -= (p - path->ptr);
if (!*q)
return git_buf_set(path, p, plen);
for (; (q = strchr(q, '/')) && *(q + 1); q++)
depth++;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
GIT_ERROR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
/* save the offset as we might realllocate the pointer */
offset = p - path->ptr;
if (git_buf_try_grow(path, alloclen, 1) < 0)
return -1;
p = path->ptr + offset;
memmove(path->ptr + (depth * 3), p, plen + 1);
for (i = 0; i < depth; i++)
memcpy(path->ptr + (i * 3), "../", 3);
path->size = newlen;
return 0;
}
bool git_path_has_non_ascii(const char *path, size_t pathlen)
{
const uint8_t *scan = (const uint8_t *)path, *end;
for (end = scan + pathlen; scan < end; ++scan)
if (*scan & 0x80)
return true;
return false;
}
#ifdef GIT_USE_ICONV
int git_path_iconv_init_precompose(git_path_iconv_t *ic)
{
git_buf_init(&ic->buf, 0);
ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
return 0;
}
void git_path_iconv_clear(git_path_iconv_t *ic)
{
if (ic) {
if (ic->map != (iconv_t)-1)
iconv_close(ic->map);
git_buf_dispose(&ic->buf);
}
}
int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen)
{
char *nfd = (char*)*in, *nfc;
size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
int retry = 1;
if (!ic || ic->map == (iconv_t)-1 ||
!git_path_has_non_ascii(*in, *inlen))
return 0;
git_buf_clear(&ic->buf);
while (1) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
if (git_buf_grow(&ic->buf, alloclen) < 0)
return -1;
nfc = ic->buf.ptr + ic->buf.size;
nfclen = ic->buf.asize - ic->buf.size;
rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
ic->buf.size = (nfc - ic->buf.ptr);
if (rv != (size_t)-1)
break;
/* if we cannot convert the data (probably because iconv thinks
* it is not valid UTF-8 source data), then use original data
*/
if (errno != E2BIG)
return 0;
/* make space for 2x the remaining data to be converted
* (with per retry overhead to avoid infinite loops)
*/
wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
if (retry++ > 4)
goto fail;
}
ic->buf.ptr[ic->buf.size] = '\0';
*in = ic->buf.ptr;
*inlen = ic->buf.size;
return 0;
fail:
git_error_set(GIT_ERROR_OS, "unable to convert unicode path data");
return -1;
}
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D.XXXXXX";
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D.XXXXXX";
/* Check if the platform is decomposing unicode data for us. We will
* emulate core Git and prefer to use precomposed unicode data internally
* on these platforms, composing the decomposed unicode on the fly.
*
* This mainly happens on the Mac where HDFS stores filenames as
* decomposed unicode. Even on VFAT and SAMBA file systems, the Mac will
* return decomposed unicode from readdir() even when the actual
* filesystem is storing precomposed unicode.
*/
bool git_path_does_fs_decompose_unicode(const char *root)
{
git_buf path = GIT_BUF_INIT;
int fd;
bool found_decomposed = false;
char tmp[6];
/* Create a file using a precomposed path and then try to find it
* using the decomposed name. If the lookup fails, then we will mark
* that we should precompose unicode for this repository.
*/
if (git_buf_joinpath(&path, root, nfc_file) < 0 ||
(fd = p_mkstemp(path.ptr)) < 0)
goto done;
p_close(fd);
/* record trailing digits generated by mkstemp */
memcpy(tmp, path.ptr + path.size - sizeof(tmp), sizeof(tmp));
/* try to look up as NFD path */
if (git_buf_joinpath(&path, root, nfd_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
found_decomposed = git_path_exists(path.ptr);
/* remove temporary file (using original precomposed path) */
if (git_buf_joinpath(&path, root, nfc_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
(void)p_unlink(path.ptr);
done:
git_buf_dispose(&path);
return found_decomposed;
}
#else
bool git_path_does_fs_decompose_unicode(const char *root)
{
GIT_UNUSED(root);
return false;
}
#endif
#if defined(__sun) || defined(__GNU__)
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
#else
typedef struct dirent path_dirent_data;
#endif
int git_path_direach(
git_buf *path,
uint32_t flags,
int (*fn)(void *, git_buf *),
void *arg)
{
int error = 0;
ssize_t wd_len;
DIR *dir;
struct dirent *de;
#ifdef GIT_USE_ICONV
git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
#endif
GIT_UNUSED(flags);
if (git_path_to_dir(path) < 0)
return -1;
wd_len = git_buf_len(path);
if ((dir = opendir(path->ptr)) == NULL) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path->ptr);
if (errno == ENOENT)
return GIT_ENOTFOUND;
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&ic);
#endif
while ((de = readdir(dir)) != NULL) {
const char *de_path = de->d_name;
size_t de_len = strlen(de_path);
if (git_path_is_dot_or_dotdot(de_path))
continue;
#ifdef GIT_USE_ICONV
if ((error = git_path_iconv(&ic, &de_path, &de_len)) < 0)
break;
#endif
if ((error = git_buf_put(path, de_path, de_len)) < 0)
break;
git_error_clear();
error = fn(arg, path);
git_buf_truncate(path, wd_len); /* restore path */
/* Only set our own error if the callback did not set one already */
if (error != 0) {
if (!git_error_last())
git_error_set_after_callback(error);
break;
}
}
closedir(dir);
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&ic);
#endif
return error;
}
#if defined(GIT_WIN32) && !defined(__MINGW32__)
/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
* and better.
*/
#ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 2
#endif
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
git_win32_path path_filter;
static int is_win7_or_later = -1;
if (is_win7_or_later < 0)
is_win7_or_later = git_has_win32_version(6, 1, 0);
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
diriter->handle = INVALID_HANDLE_VALUE;
if (git_buf_puts(&diriter->path_utf8, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path_utf8);
if (diriter->path_utf8.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
!git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
git_error_set(GIT_ERROR_OS, "could not parse the directory path '%s'", path);
return -1;
}
diriter->handle = FindFirstFileExW(
path_filter,
is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
&diriter->current,
FindExSearchNameMatch,
NULL,
is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
if (diriter->handle == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", path);
return -1;
}
diriter->parent_utf8_len = diriter->path_utf8.size;
diriter->flags = flags;
return 0;
}
static int diriter_update_paths(git_path_diriter *diriter)
{
size_t filename_len, path_len;
filename_len = wcslen(diriter->current.cFileName);
if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
return -1;
if (path_len > GIT_WIN_PATH_UTF16) {
git_error_set(GIT_ERROR_FILESYSTEM,
"invalid path '%.*ls\\%ls' (path too long)",
diriter->parent_len, diriter->path, diriter->current.cFileName);
return -1;
}
diriter->path[diriter->parent_len] = L'\\';
memcpy(&diriter->path[diriter->parent_len+1],
diriter->current.cFileName, filename_len * sizeof(wchar_t));
diriter->path[path_len-1] = L'\0';
git_buf_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
if (diriter->parent_utf8_len > 0 &&
diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
git_buf_putc(&diriter->path_utf8, '/');
git_buf_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
if (git_buf_oom(&diriter->path_utf8))
return -1;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
do {
/* Our first time through, we already have the data from
* FindFirstFileW. Use it, otherwise get the next file.
*/
if (!diriter->needs_next)
diriter->needs_next = 1;
else if (!FindNextFileW(diriter->handle, &diriter->current))
return GIT_ITEROVER;
} while (skip_dot && git_path_is_dot_or_dotdotW(diriter->current.cFileName));
if (diriter_update_paths(diriter) < 0)
return -1;
return 0;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path_utf8.size > diriter->parent_utf8_len);
*out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
*out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path_utf8.ptr;
*out_len = diriter->path_utf8.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_win32__file_attribute_to_stat(out,
(WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
diriter->path);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
git_buf_dispose(&diriter->path_utf8);
if (diriter->handle != INVALID_HANDLE_VALUE) {
FindClose(diriter->handle);
diriter->handle = INVALID_HANDLE_VALUE;
}
}
#else
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
if (git_buf_puts(&diriter->path, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path);
if (diriter->path.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
git_buf_dispose(&diriter->path);
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path);
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&diriter->ic);
#endif
diriter->parent_len = diriter->path.size;
diriter->flags = flags;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
struct dirent *de;
const char *filename;
size_t filename_len;
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
int error = 0;
assert(diriter);
errno = 0;
do {
if ((de = readdir(diriter->dir)) == NULL) {
if (!errno)
return GIT_ITEROVER;
git_error_set(GIT_ERROR_OS,
"could not read directory '%s'", diriter->path.ptr);
return -1;
}
} while (skip_dot && git_path_is_dot_or_dotdot(de->d_name));
filename = de->d_name;
filename_len = strlen(filename);
#ifdef GIT_USE_ICONV
if ((diriter->flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
(error = git_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
return error;
#endif
git_buf_truncate(&diriter->path, diriter->parent_len);
if (diriter->parent_len > 0 &&
diriter->path.ptr[diriter->parent_len-1] != '/')
git_buf_putc(&diriter->path, '/');
git_buf_put(&diriter->path, filename, filename_len);
if (git_buf_oom(&diriter->path))
return -1;
return error;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path.size > diriter->parent_len);
*out = &diriter->path.ptr[diriter->parent_len+1];
*out_len = diriter->path.size - diriter->parent_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path.ptr;
*out_len = diriter->path.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_path_lstat(diriter->path.ptr, out);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
if (diriter->dir) {
closedir(diriter->dir);
diriter->dir = NULL;
}
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&diriter->ic);
#endif
git_buf_dispose(&diriter->path);
}
#endif
int git_path_dirload(
git_vector *contents,
const char *path,
size_t prefix_len,
uint32_t flags)
{
git_path_diriter iter = GIT_PATH_DIRITER_INIT;
const char *name;
size_t name_len;
char *dup;
int error;
assert(contents && path);
if ((error = git_path_diriter_init(&iter, path, flags)) < 0)
return error;
while ((error = git_path_diriter_next(&iter)) == 0) {
if ((error = git_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
break;
assert(name_len > prefix_len);
dup = git__strndup(name + prefix_len, name_len - prefix_len);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(contents, dup)) < 0)
break;
}
if (error == GIT_ITEROVER)
error = 0;
git_path_diriter_free(&iter);
return error;
}
int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path)
{
if (git_path_is_local_file_url(url_or_path))
return git_path_fromurl(local_path_out, url_or_path);
else
return git_buf_sets(local_path_out, url_or_path);
}
/* Reject paths like AUX or COM1, or those versions that end in a dot or
* colon. ("AUX." or "AUX:")
*/
GIT_INLINE(bool) verify_dospath(
const char *component,
size_t len,
const char dospath[3],
bool trailing_num)
{
size_t last = trailing_num ? 4 : 3;
if (len < last || git__strncasecmp(component, dospath, 3) != 0)
return true;
if (trailing_num && (component[3] < '1' || component[3] > '9'))
return true;
return (len > last &&
component[last] != '.' &&
component[last] != ':');
}
static int32_t next_hfs_char(const char **in, size_t *len)
{
while (*len) {
int32_t codepoint;
int cp_len = git__utf8_iterate((const uint8_t *)(*in), (int)(*len), &codepoint);
if (cp_len < 0)
return -1;
(*in) += cp_len;
(*len) -= cp_len;
/* these code points are ignored completely */
switch (codepoint) {
case 0x200c: /* ZERO WIDTH NON-JOINER */
case 0x200d: /* ZERO WIDTH JOINER */
case 0x200e: /* LEFT-TO-RIGHT MARK */
case 0x200f: /* RIGHT-TO-LEFT MARK */
case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
case 0x202c: /* POP DIRECTIONAL FORMATTING */
case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
case 0x206e: /* NATIONAL DIGIT SHAPES */
case 0x206f: /* NOMINAL DIGIT SHAPES */
case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
continue;
}
/* fold into lowercase -- this will only fold characters in
* the ASCII range, which is perfectly fine, because the
* git folder name can only be composed of ascii characters
*/
return git__tolower(codepoint);
}
return 0; /* NULL byte -- end of string */
}
static bool verify_dotgit_hfs_generic(const char *path, size_t len, const char *needle, size_t needle_len)
{
size_t i;
char c;
if (next_hfs_char(&path, &len) != '.')
return true;
for (i = 0; i < needle_len; i++) {
c = next_hfs_char(&path, &len);
if (c != needle[i])
return true;
}
if (next_hfs_char(&path, &len) != '\0')
return true;
return false;
}
static bool verify_dotgit_hfs(const char *path, size_t len)
{
return verify_dotgit_hfs_generic(path, len, "git", CONST_STRLEN("git"));
}
GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)
{
git_buf *reserved = git_repository__reserved_names_win32;
size_t reserved_len = git_repository__reserved_names_win32_len;
size_t start = 0, i;
if (repo)
git_repository__reserved_names(&reserved, &reserved_len, repo, true);
for (i = 0; i < reserved_len; i++) {
git_buf *r = &reserved[i];
if (len >= r->size &&
strncasecmp(path, r->ptr, r->size) == 0) {
start = r->size;
break;
}
}
if (!start)
return true;
/*
* Reject paths that start with Windows-style directory separators
* (".git\") or NTFS alternate streams (".git:") and could be used
* to write to the ".git" directory on Windows platforms.
*/
if (path[start] == '\\' || path[start] == ':')
return false;
/* Reject paths like '.git ' or '.git.' */
for (i = start; i < len; i++) {
if (path[i] != ' ' && path[i] != '.')
return true;
}
return false;
}
GIT_INLINE(bool) only_spaces_and_dots(const char *path)
{
const char *c = path;
for (;; c++) {
if (*c == '\0')
return true;
if (*c != ' ' && *c != '.')
return false;
}
return true;
}
GIT_INLINE(bool) verify_dotgit_ntfs_generic(const char *name, size_t len, const char *dotgit_name, size_t dotgit_len, const char *shortname_pfix)
{
int i, saw_tilde;
if (name[0] == '.' && len >= dotgit_len &&
!strncasecmp(name + 1, dotgit_name, dotgit_len)) {
return !only_spaces_and_dots(name + dotgit_len + 1);
}
/* Detect the basic NTFS shortname with the first six chars */
if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
name[7] >= '1' && name[7] <= '4')
return !only_spaces_and_dots(name + 8);
/* Catch fallback names */
for (i = 0, saw_tilde = 0; i < 8; i++) {
if (name[i] == '\0') {
return true;
} else if (saw_tilde) {
if (name[i] < '0' || name[i] > '9')
return true;
} else if (name[i] == '~') {
if (name[i+1] < '1' || name[i+1] > '9')
return true;
saw_tilde = 1;
} else if (i >= 6) {
return true;
} else if ((unsigned char)name[i] > 127) {
return true;
} else if (git__tolower(name[i]) != shortname_pfix[i]) {
return true;
}
}
return !only_spaces_and_dots(name + i);
}
GIT_INLINE(bool) verify_char(unsigned char c, unsigned int flags)
{
if ((flags & GIT_PATH_REJECT_BACKSLASH) && c == '\\')
return false;
if ((flags & GIT_PATH_REJECT_SLASH) && c == '/')
return false;
if (flags & GIT_PATH_REJECT_NT_CHARS) {
if (c < 32)
return false;
switch (c) {
case '<':
case '>':
case ':':
case '"':
case '|':
case '?':
case '*':
return false;
}
}
return true;
}
/*
* Return the length of the common prefix between str and prefix, comparing them
* case-insensitively (must be ASCII to match).
*/
GIT_INLINE(size_t) common_prefix_icase(const char *str, size_t len, const char *prefix)
{
size_t count = 0;
while (len >0 && tolower(*str) == tolower(*prefix)) {
count++;
str++;
prefix++;
len--;
}
return count;
}
/*
* We fundamentally don't like some paths when dealing with user-inputted
* strings (in checkout or ref names): we don't want dot or dot-dot
* anywhere, we want to avoid writing weird paths on Windows that can't
* be handled by tools that use the non-\\?\ APIs, we don't want slashes
* or double slashes at the end of paths that can make them ambiguous.
*
* For checkout, we don't want to recurse into ".git" either.
*/
static bool verify_component(
git_repository *repo,
const char *component,
size_t len,
uint16_t mode,
unsigned int flags)
{
if (len == 0)
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 1 && component[0] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 2 && component[0] == '.' && component[1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_DOT) && component[len-1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_SPACE) && component[len-1] == ' ')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_COLON) && component[len-1] == ':')
return false;
if (flags & GIT_PATH_REJECT_DOS_PATHS) {
if (!verify_dospath(component, len, "CON", false) ||
!verify_dospath(component, len, "PRN", false) ||
!verify_dospath(component, len, "AUX", false) ||
!verify_dospath(component, len, "NUL", false) ||
!verify_dospath(component, len, "COM", true) ||
!verify_dospath(component, len, "LPT", true))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_HFS) {
if (!verify_dotgit_hfs(component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_HFS))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_NTFS) {
if (!verify_dotgit_ntfs(repo, component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_NTFS))
return false;
}
/* don't bother rerunning the `.git` test if we ran the HFS or NTFS
* specific tests, they would have already rejected `.git`.
*/
if ((flags & GIT_PATH_REJECT_DOT_GIT_HFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_NTFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_LITERAL)) {
if (len >= 4 &&
component[0] == '.' &&
(component[1] == 'g' || component[1] == 'G') &&
(component[2] == 'i' || component[2] == 'I') &&
(component[3] == 't' || component[3] == 'T')) {
if (len == 4)
return false;
if (S_ISLNK(mode) && common_prefix_icase(component, len, ".gitmodules") == len)
return false;
}
}
return true;
}
GIT_INLINE(unsigned int) dotgit_flags(
git_repository *repo,
unsigned int flags)
{
int protectHFS = 0, protectNTFS = 0;
int error = 0;
flags |= GIT_PATH_REJECT_DOT_GIT_LITERAL;
#ifdef __APPLE__
protectHFS = 1;
#endif
#ifdef GIT_WIN32
protectNTFS = 1;
#endif
if (repo && !protectHFS)
error = git_repository__configmap_lookup(&protectHFS, repo, GIT_CONFIGMAP_PROTECTHFS);
if (!error && protectHFS)
flags |= GIT_PATH_REJECT_DOT_GIT_HFS;
if (repo && !protectNTFS)
error = git_repository__configmap_lookup(&protectNTFS, repo, GIT_CONFIGMAP_PROTECTNTFS);
if (!error && protectNTFS)
flags |= GIT_PATH_REJECT_DOT_GIT_NTFS;
return flags;
}
bool git_path_isvalid(
git_repository *repo,
const char *path,
uint16_t mode,
unsigned int flags)
{
const char *start, *c;
/* Upgrade the ".git" checks based on platform */
if ((flags & GIT_PATH_REJECT_DOT_GIT))
flags = dotgit_flags(repo, flags);
for (start = c = path; *c; c++) {
if (!verify_char(*c, flags))
return false;
if (*c == '/') {
if (!verify_component(repo, start, (c - start), mode, flags))
return false;
start = c+1;
}
}
return verify_component(repo, start, (c - start), mode, flags);
}
int git_path_normalize_slashes(git_buf *out, const char *path)
{
int error;
char *p;
if ((error = git_buf_puts(out, path)) < 0)
return error;
for (p = out->ptr; *p; p++) {
if (*p == '\\')
*p = '/';
}
return 0;
}
static const struct {
const char *file;
const char *hash;
size_t filelen;
} gitfiles[] = {
{ "gitignore", "gi250a", CONST_STRLEN("gitignore") },
{ "gitmodules", "gi7eba", CONST_STRLEN("gitmodules") },
{ "gitattributes", "gi7d29", CONST_STRLEN("gitattributes") }
};
extern int git_path_is_gitfile(const char *path, size_t pathlen, git_path_gitfile gitfile, git_path_fs fs)
{
const char *file, *hash;
size_t filelen;
if (!(gitfile >= GIT_PATH_GITFILE_GITIGNORE && gitfile < ARRAY_SIZE(gitfiles))) {
git_error_set(GIT_ERROR_OS, "invalid gitfile for path validation");
return -1;
}
file = gitfiles[gitfile].file;
filelen = gitfiles[gitfile].filelen;
hash = gitfiles[gitfile].hash;
switch (fs) {
case GIT_PATH_FS_GENERIC:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash) ||
!verify_dotgit_hfs_generic(path, pathlen, file, filelen);
case GIT_PATH_FS_NTFS:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash);
case GIT_PATH_FS_HFS:
return !verify_dotgit_hfs_generic(path, pathlen, file, filelen);
default:
git_error_set(GIT_ERROR_OS, "invalid filesystem for path validation");
return -1;
}
}
bool git_path_supports_symlinks(const char *dir)
{
git_buf path = GIT_BUF_INIT;
bool supported = false;
struct stat st;
int fd;
if ((fd = git_futils_mktmp(&path, dir, 0666)) < 0 ||
p_close(fd) < 0 ||
p_unlink(path.ptr) < 0 ||
p_symlink("testing", path.ptr) < 0 ||
p_lstat(path.ptr, &st) < 0)
goto done;
supported = (S_ISLNK(st.st_mode) != 0);
done:
if (path.size)
(void)p_unlink(path.ptr);
git_buf_dispose(&path);
return supported;
}
int git_path_validate_system_file_ownership(const char *path)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
return GIT_OK;
#else
git_win32_path buf;
PSID owner_sid;
PSECURITY_DESCRIPTOR descriptor = NULL;
HANDLE token;
TOKEN_USER *info = NULL;
DWORD err, len;
int ret;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
err = GetNamedSecurityInfoW(buf, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION,
&owner_sid, NULL, NULL, NULL, &descriptor);
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
ret = GIT_ENOTFOUND;
goto cleanup;
}
if (err != ERROR_SUCCESS) {
git_error_set(GIT_ERROR_OS, "failed to get security information");
ret = GIT_ERROR;
goto cleanup;
}
if (!IsValidSid(owner_sid)) {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is unknown");
ret = GIT_ERROR;
goto cleanup;
}
if (IsWellKnownSid(owner_sid, WinBuiltinAdministratorsSid) ||
IsWellKnownSid(owner_sid, WinLocalSystemSid)) {
ret = GIT_OK;
goto cleanup;
}
/* Obtain current user's SID */
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
info = git__malloc(len);
GIT_ERROR_CHECK_ALLOC(info);
if (!GetTokenInformation(token, TokenUser, info, len, &len)) {
git__free(info);
info = NULL;
}
}
/*
* If the file is owned by the same account that is running the current
* process, it's okay to read from that file.
*/
if (info && EqualSid(owner_sid, info->User.Sid))
ret = GIT_OK;
else {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is not valid");
ret = GIT_ERROR;
}
free(info);
cleanup:
if (descriptor)
LocalFree(descriptor);
return ret;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3987_0 |
crossvul-cpp_data_good_3641_0 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Generic socket support routines. Memory allocators, socket lock/release
* handler for protocols to use and generic option handler.
*
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Florian La Roche, <flla@stud.uni-sb.de>
* Alan Cox, <A.Cox@swansea.ac.uk>
*
* Fixes:
* Alan Cox : Numerous verify_area() problems
* Alan Cox : Connecting on a connecting socket
* now returns an error for tcp.
* Alan Cox : sock->protocol is set correctly.
* and is not sometimes left as 0.
* Alan Cox : connect handles icmp errors on a
* connect properly. Unfortunately there
* is a restart syscall nasty there. I
* can't match BSD without hacking the C
* library. Ideas urgently sought!
* Alan Cox : Disallow bind() to addresses that are
* not ours - especially broadcast ones!!
* Alan Cox : Socket 1024 _IS_ ok for users. (fencepost)
* Alan Cox : sock_wfree/sock_rfree don't destroy sockets,
* instead they leave that for the DESTROY timer.
* Alan Cox : Clean up error flag in accept
* Alan Cox : TCP ack handling is buggy, the DESTROY timer
* was buggy. Put a remove_sock() in the handler
* for memory when we hit 0. Also altered the timer
* code. The ACK stuff can wait and needs major
* TCP layer surgery.
* Alan Cox : Fixed TCP ack bug, removed remove sock
* and fixed timer/inet_bh race.
* Alan Cox : Added zapped flag for TCP
* Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code
* Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb
* Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources
* Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing.
* Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so...
* Rick Sladkey : Relaxed UDP rules for matching packets.
* C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support
* Pauline Middelink : identd support
* Alan Cox : Fixed connect() taking signals I think.
* Alan Cox : SO_LINGER supported
* Alan Cox : Error reporting fixes
* Anonymous : inet_create tidied up (sk->reuse setting)
* Alan Cox : inet sockets don't set sk->type!
* Alan Cox : Split socket option code
* Alan Cox : Callbacks
* Alan Cox : Nagle flag for Charles & Johannes stuff
* Alex : Removed restriction on inet fioctl
* Alan Cox : Splitting INET from NET core
* Alan Cox : Fixed bogus SO_TYPE handling in getsockopt()
* Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code
* Alan Cox : Split IP from generic code
* Alan Cox : New kfree_skbmem()
* Alan Cox : Make SO_DEBUG superuser only.
* Alan Cox : Allow anyone to clear SO_DEBUG
* (compatibility fix)
* Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput.
* Alan Cox : Allocator for a socket is settable.
* Alan Cox : SO_ERROR includes soft errors.
* Alan Cox : Allow NULL arguments on some SO_ opts
* Alan Cox : Generic socket allocation to make hooks
* easier (suggested by Craig Metz).
* Michael Pall : SO_ERROR returns positive errno again
* Steve Whitehouse: Added default destructor to free
* protocol private data.
* Steve Whitehouse: Added various other default routines
* common to several socket families.
* Chris Evans : Call suser() check last on F_SETOWN
* Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER.
* Andi Kleen : Add sock_kmalloc()/sock_kfree_s()
* Andi Kleen : Fix write_space callback
* Chris Evans : Security fixes - signedness again
* Arnaldo C. Melo : cleanups, use skb_queue_purge
*
* To Fix:
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/poll.h>
#include <linux/tcp.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/user_namespace.h>
#include <linux/static_key.h>
#include <linux/memcontrol.h>
#include <linux/prefetch.h>
#include <asm/uaccess.h>
#include <linux/netdevice.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/request_sock.h>
#include <net/sock.h>
#include <linux/net_tstamp.h>
#include <net/xfrm.h>
#include <linux/ipsec.h>
#include <net/cls_cgroup.h>
#include <net/netprio_cgroup.h>
#include <linux/filter.h>
#include <trace/events/sock.h>
#ifdef CONFIG_INET
#include <net/tcp.h>
#endif
static DEFINE_MUTEX(proto_list_mutex);
static LIST_HEAD(proto_list);
#ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
int mem_cgroup_sockets_init(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
{
struct proto *proto;
int ret = 0;
mutex_lock(&proto_list_mutex);
list_for_each_entry(proto, &proto_list, node) {
if (proto->init_cgroup) {
ret = proto->init_cgroup(memcg, ss);
if (ret)
goto out;
}
}
mutex_unlock(&proto_list_mutex);
return ret;
out:
list_for_each_entry_continue_reverse(proto, &proto_list, node)
if (proto->destroy_cgroup)
proto->destroy_cgroup(memcg);
mutex_unlock(&proto_list_mutex);
return ret;
}
void mem_cgroup_sockets_destroy(struct mem_cgroup *memcg)
{
struct proto *proto;
mutex_lock(&proto_list_mutex);
list_for_each_entry_reverse(proto, &proto_list, node)
if (proto->destroy_cgroup)
proto->destroy_cgroup(memcg);
mutex_unlock(&proto_list_mutex);
}
#endif
/*
* Each address family might have different locking rules, so we have
* one slock key per address family:
*/
static struct lock_class_key af_family_keys[AF_MAX];
static struct lock_class_key af_family_slock_keys[AF_MAX];
struct static_key memcg_socket_limit_enabled;
EXPORT_SYMBOL(memcg_socket_limit_enabled);
/*
* Make lock validator output more readable. (we pre-construct these
* strings build-time, so that runtime initialization of socket
* locks is fast):
*/
static const char *const af_family_key_strings[AF_MAX+1] = {
"sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" ,
"sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK",
"sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" ,
"sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" ,
"sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" ,
"sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" ,
"sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" ,
"sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" ,
"sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" ,
"sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" ,
"sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" ,
"sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" ,
"sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" ,
"sk_lock-AF_NFC" , "sk_lock-AF_MAX"
};
static const char *const af_family_slock_key_strings[AF_MAX+1] = {
"slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" ,
"slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK",
"slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" ,
"slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" ,
"slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" ,
"slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" ,
"slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" ,
"slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" ,
"slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" ,
"slock-27" , "slock-28" , "slock-AF_CAN" ,
"slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" ,
"slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" ,
"slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" ,
"slock-AF_NFC" , "slock-AF_MAX"
};
static const char *const af_family_clock_key_strings[AF_MAX+1] = {
"clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" ,
"clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK",
"clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" ,
"clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" ,
"clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" ,
"clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" ,
"clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" ,
"clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" ,
"clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" ,
"clock-27" , "clock-28" , "clock-AF_CAN" ,
"clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" ,
"clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" ,
"clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" ,
"clock-AF_NFC" , "clock-AF_MAX"
};
/*
* sk_callback_lock locking rules are per-address-family,
* so split the lock classes by using a per-AF key:
*/
static struct lock_class_key af_callback_keys[AF_MAX];
/* Take into consideration the size of the struct sk_buff overhead in the
* determination of these values, since that is non-constant across
* platforms. This makes socket queueing behavior and performance
* not depend upon such differences.
*/
#define _SK_MEM_PACKETS 256
#define _SK_MEM_OVERHEAD SKB_TRUESIZE(256)
#define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
#define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
/* Run time adjustable parameters. */
__u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
EXPORT_SYMBOL(sysctl_wmem_max);
__u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
EXPORT_SYMBOL(sysctl_rmem_max);
__u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
__u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
/* Maximal space eaten by iovec or ancillary data plus some space */
int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512);
EXPORT_SYMBOL(sysctl_optmem_max);
#if defined(CONFIG_CGROUPS)
#if !defined(CONFIG_NET_CLS_CGROUP)
int net_cls_subsys_id = -1;
EXPORT_SYMBOL_GPL(net_cls_subsys_id);
#endif
#if !defined(CONFIG_NETPRIO_CGROUP)
int net_prio_subsys_id = -1;
EXPORT_SYMBOL_GPL(net_prio_subsys_id);
#endif
#endif
static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen)
{
struct timeval tv;
if (optlen < sizeof(tv))
return -EINVAL;
if (copy_from_user(&tv, optval, sizeof(tv)))
return -EFAULT;
if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
return -EDOM;
if (tv.tv_sec < 0) {
static int warned __read_mostly;
*timeo_p = 0;
if (warned < 10 && net_ratelimit()) {
warned++;
pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
__func__, current->comm, task_pid_nr(current));
}
return 0;
}
*timeo_p = MAX_SCHEDULE_TIMEOUT;
if (tv.tv_sec == 0 && tv.tv_usec == 0)
return 0;
if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1))
*timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ);
return 0;
}
static void sock_warn_obsolete_bsdism(const char *name)
{
static int warned;
static char warncomm[TASK_COMM_LEN];
if (strcmp(warncomm, current->comm) && warned < 5) {
strcpy(warncomm, current->comm);
pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n",
warncomm, name);
warned++;
}
}
#define SK_FLAGS_TIMESTAMP ((1UL << SOCK_TIMESTAMP) | (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE))
static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
{
if (sk->sk_flags & flags) {
sk->sk_flags &= ~flags;
if (!(sk->sk_flags & SK_FLAGS_TIMESTAMP))
net_disable_timestamp();
}
}
int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
int err;
int skb_len;
unsigned long flags;
struct sk_buff_head *list = &sk->sk_receive_queue;
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) {
atomic_inc(&sk->sk_drops);
trace_sock_rcvqueue_full(sk, skb);
return -ENOMEM;
}
err = sk_filter(sk, skb);
if (err)
return err;
if (!sk_rmem_schedule(sk, skb->truesize)) {
atomic_inc(&sk->sk_drops);
return -ENOBUFS;
}
skb->dev = NULL;
skb_set_owner_r(skb, sk);
/* Cache the SKB length before we tack it onto the receive
* queue. Once it is added it no longer belongs to us and
* may be freed by other threads of control pulling packets
* from the queue.
*/
skb_len = skb->len;
/* we escape from rcu protected region, make sure we dont leak
* a norefcounted dst
*/
skb_dst_force(skb);
spin_lock_irqsave(&list->lock, flags);
skb->dropcount = atomic_read(&sk->sk_drops);
__skb_queue_tail(list, skb);
spin_unlock_irqrestore(&list->lock, flags);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, skb_len);
return 0;
}
EXPORT_SYMBOL(sock_queue_rcv_skb);
int sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested)
{
int rc = NET_RX_SUCCESS;
if (sk_filter(sk, skb))
goto discard_and_relse;
skb->dev = NULL;
if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf)) {
atomic_inc(&sk->sk_drops);
goto discard_and_relse;
}
if (nested)
bh_lock_sock_nested(sk);
else
bh_lock_sock(sk);
if (!sock_owned_by_user(sk)) {
/*
* trylock + unlock semantics:
*/
mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
rc = sk_backlog_rcv(sk, skb);
mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);
} else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
bh_unlock_sock(sk);
atomic_inc(&sk->sk_drops);
goto discard_and_relse;
}
bh_unlock_sock(sk);
out:
sock_put(sk);
return rc;
discard_and_relse:
kfree_skb(skb);
goto out;
}
EXPORT_SYMBOL(sk_receive_skb);
void sk_reset_txq(struct sock *sk)
{
sk_tx_queue_clear(sk);
}
EXPORT_SYMBOL(sk_reset_txq);
struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
{
struct dst_entry *dst = __sk_dst_get(sk);
if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk_tx_queue_clear(sk);
RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
dst_release(dst);
return NULL;
}
return dst;
}
EXPORT_SYMBOL(__sk_dst_check);
struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
{
struct dst_entry *dst = sk_dst_get(sk);
if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk_dst_reset(sk);
dst_release(dst);
return NULL;
}
return dst;
}
EXPORT_SYMBOL(sk_dst_check);
static int sock_bindtodevice(struct sock *sk, char __user *optval, int optlen)
{
int ret = -ENOPROTOOPT;
#ifdef CONFIG_NETDEVICES
struct net *net = sock_net(sk);
char devname[IFNAMSIZ];
int index;
/* Sorry... */
ret = -EPERM;
if (!capable(CAP_NET_RAW))
goto out;
ret = -EINVAL;
if (optlen < 0)
goto out;
/* Bind this socket to a particular device like "eth0",
* as specified in the passed interface name. If the
* name is "" or the option length is zero the socket
* is not bound.
*/
if (optlen > IFNAMSIZ - 1)
optlen = IFNAMSIZ - 1;
memset(devname, 0, sizeof(devname));
ret = -EFAULT;
if (copy_from_user(devname, optval, optlen))
goto out;
index = 0;
if (devname[0] != '\0') {
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, devname);
if (dev)
index = dev->ifindex;
rcu_read_unlock();
ret = -ENODEV;
if (!dev)
goto out;
}
lock_sock(sk);
sk->sk_bound_dev_if = index;
sk_dst_reset(sk);
release_sock(sk);
ret = 0;
out:
#endif
return ret;
}
static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool)
{
if (valbool)
sock_set_flag(sk, bit);
else
sock_reset_flag(sk, bit);
}
/*
* This is meant for all protocols to use and covers goings on
* at the socket level. Everything here is generic.
*/
int sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int val;
int valbool;
struct linger ling;
int ret = 0;
/*
* Options without arguments
*/
if (optname == SO_BINDTODEVICE)
return sock_bindtodevice(sk, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
valbool = val ? 1 : 0;
lock_sock(sk);
switch (optname) {
case SO_DEBUG:
if (val && !capable(CAP_NET_ADMIN))
ret = -EACCES;
else
sock_valbool_flag(sk, SOCK_DBG, valbool);
break;
case SO_REUSEADDR:
sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
break;
case SO_TYPE:
case SO_PROTOCOL:
case SO_DOMAIN:
case SO_ERROR:
ret = -ENOPROTOOPT;
break;
case SO_DONTROUTE:
sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
break;
case SO_BROADCAST:
sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
break;
case SO_SNDBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_wmem_max);
set_sndbuf:
sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF);
/* Wake up sending tasks if we upped the value. */
sk->sk_write_space(sk);
break;
case SO_SNDBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_sndbuf;
case SO_RCVBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_rmem_max);
set_rcvbuf:
sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
/*
* We double it on the way in to account for
* "struct sk_buff" etc. overhead. Applications
* assume that the SO_RCVBUF setting they make will
* allow that much actual data to be received on that
* socket.
*
* Applications are unaware that "struct sk_buff" and
* other overheads allocate from the receive buffer
* during socket buffer allocation.
*
* And after considering the possible alternatives,
* returning the value we actually used in getsockopt
* is the most desirable behavior.
*/
sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF);
break;
case SO_RCVBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_rcvbuf;
case SO_KEEPALIVE:
#ifdef CONFIG_INET
if (sk->sk_protocol == IPPROTO_TCP)
tcp_set_keepalive(sk, valbool);
#endif
sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
break;
case SO_OOBINLINE:
sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
break;
case SO_NO_CHECK:
sk->sk_no_check = valbool;
break;
case SO_PRIORITY:
if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN))
sk->sk_priority = val;
else
ret = -EPERM;
break;
case SO_LINGER:
if (optlen < sizeof(ling)) {
ret = -EINVAL; /* 1003.1g */
break;
}
if (copy_from_user(&ling, optval, sizeof(ling))) {
ret = -EFAULT;
break;
}
if (!ling.l_onoff)
sock_reset_flag(sk, SOCK_LINGER);
else {
#if (BITS_PER_LONG == 32)
if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
else
#endif
sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
sock_set_flag(sk, SOCK_LINGER);
}
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("setsockopt");
break;
case SO_PASSCRED:
if (valbool)
set_bit(SOCK_PASSCRED, &sock->flags);
else
clear_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_TIMESTAMP:
case SO_TIMESTAMPNS:
if (valbool) {
if (optname == SO_TIMESTAMP)
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
else
sock_set_flag(sk, SOCK_RCVTSTAMPNS);
sock_set_flag(sk, SOCK_RCVTSTAMP);
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
} else {
sock_reset_flag(sk, SOCK_RCVTSTAMP);
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
}
break;
case SO_TIMESTAMPING:
if (val & ~SOF_TIMESTAMPING_MASK) {
ret = -EINVAL;
break;
}
sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE,
val & SOF_TIMESTAMPING_TX_HARDWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE,
val & SOF_TIMESTAMPING_TX_SOFTWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE,
val & SOF_TIMESTAMPING_RX_HARDWARE);
if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
sock_enable_timestamp(sk,
SOCK_TIMESTAMPING_RX_SOFTWARE);
else
sock_disable_timestamp(sk,
(1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE,
val & SOF_TIMESTAMPING_SOFTWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE,
val & SOF_TIMESTAMPING_SYS_HARDWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE,
val & SOF_TIMESTAMPING_RAW_HARDWARE);
break;
case SO_RCVLOWAT:
if (val < 0)
val = INT_MAX;
sk->sk_rcvlowat = val ? : 1;
break;
case SO_RCVTIMEO:
ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen);
break;
case SO_SNDTIMEO:
ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen);
break;
case SO_ATTACH_FILTER:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, sk);
}
break;
case SO_DETACH_FILTER:
ret = sk_detach_filter(sk);
break;
case SO_PASSSEC:
if (valbool)
set_bit(SOCK_PASSSEC, &sock->flags);
else
clear_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_MARK:
if (!capable(CAP_NET_ADMIN))
ret = -EPERM;
else
sk->sk_mark = val;
break;
/* We implement the SO_SNDLOWAT etc to
not be settable (1003.1g 5.3) */
case SO_RXQ_OVFL:
sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
break;
case SO_WIFI_STATUS:
sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
break;
case SO_PEEK_OFF:
if (sock->ops->set_peek_off)
sock->ops->set_peek_off(sk, val);
else
ret = -EOPNOTSUPP;
break;
case SO_NOFCS:
sock_valbool_flag(sk, SOCK_NOFCS, valbool);
break;
default:
ret = -ENOPROTOOPT;
break;
}
release_sock(sk);
return ret;
}
EXPORT_SYMBOL(sock_setsockopt);
void cred_to_ucred(struct pid *pid, const struct cred *cred,
struct ucred *ucred)
{
ucred->pid = pid_vnr(pid);
ucred->uid = ucred->gid = -1;
if (cred) {
struct user_namespace *current_ns = current_user_ns();
ucred->uid = from_kuid(current_ns, cred->euid);
ucred->gid = from_kgid(current_ns, cred->egid);
}
}
EXPORT_SYMBOL_GPL(cred_to_ucred);
int sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
union {
int val;
struct linger ling;
struct timeval tm;
} v;
int lv = sizeof(int);
int len;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
memset(&v, 0, sizeof(v));
switch (optname) {
case SO_DEBUG:
v.val = sock_flag(sk, SOCK_DBG);
break;
case SO_DONTROUTE:
v.val = sock_flag(sk, SOCK_LOCALROUTE);
break;
case SO_BROADCAST:
v.val = sock_flag(sk, SOCK_BROADCAST);
break;
case SO_SNDBUF:
v.val = sk->sk_sndbuf;
break;
case SO_RCVBUF:
v.val = sk->sk_rcvbuf;
break;
case SO_REUSEADDR:
v.val = sk->sk_reuse;
break;
case SO_KEEPALIVE:
v.val = sock_flag(sk, SOCK_KEEPOPEN);
break;
case SO_TYPE:
v.val = sk->sk_type;
break;
case SO_PROTOCOL:
v.val = sk->sk_protocol;
break;
case SO_DOMAIN:
v.val = sk->sk_family;
break;
case SO_ERROR:
v.val = -sock_error(sk);
if (v.val == 0)
v.val = xchg(&sk->sk_err_soft, 0);
break;
case SO_OOBINLINE:
v.val = sock_flag(sk, SOCK_URGINLINE);
break;
case SO_NO_CHECK:
v.val = sk->sk_no_check;
break;
case SO_PRIORITY:
v.val = sk->sk_priority;
break;
case SO_LINGER:
lv = sizeof(v.ling);
v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
v.ling.l_linger = sk->sk_lingertime / HZ;
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("getsockopt");
break;
case SO_TIMESTAMP:
v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
!sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPNS:
v.val = sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPING:
v.val = 0;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE))
v.val |= SOF_TIMESTAMPING_TX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_TX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE))
v.val |= SOF_TIMESTAMPING_RX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_RX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE))
v.val |= SOF_TIMESTAMPING_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE))
v.val |= SOF_TIMESTAMPING_SYS_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE))
v.val |= SOF_TIMESTAMPING_RAW_HARDWARE;
break;
case SO_RCVTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_rcvtimeo / HZ;
v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_SNDTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_sndtimeo / HZ;
v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_RCVLOWAT:
v.val = sk->sk_rcvlowat;
break;
case SO_SNDLOWAT:
v.val = 1;
break;
case SO_PASSCRED:
v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_PEERCRED:
{
struct ucred peercred;
if (len > sizeof(peercred))
len = sizeof(peercred);
cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
if (copy_to_user(optval, &peercred, len))
return -EFAULT;
goto lenout;
}
case SO_PEERNAME:
{
char address[128];
if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2))
return -ENOTCONN;
if (lv < len)
return -EINVAL;
if (copy_to_user(optval, address, len))
return -EFAULT;
goto lenout;
}
/* Dubious BSD thing... Probably nobody even uses it, but
* the UNIX standard wants it for whatever reason... -DaveM
*/
case SO_ACCEPTCONN:
v.val = sk->sk_state == TCP_LISTEN;
break;
case SO_PASSSEC:
v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_PEERSEC:
return security_socket_getpeersec_stream(sock, optval, optlen, len);
case SO_MARK:
v.val = sk->sk_mark;
break;
case SO_RXQ_OVFL:
v.val = sock_flag(sk, SOCK_RXQ_OVFL);
break;
case SO_WIFI_STATUS:
v.val = sock_flag(sk, SOCK_WIFI_STATUS);
break;
case SO_PEEK_OFF:
if (!sock->ops->set_peek_off)
return -EOPNOTSUPP;
v.val = sk->sk_peek_off;
break;
case SO_NOFCS:
v.val = sock_flag(sk, SOCK_NOFCS);
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (copy_to_user(optval, &v, len))
return -EFAULT;
lenout:
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
/*
* Initialize an sk_lock.
*
* (We also register the sk_lock with the lock validator.)
*/
static inline void sock_lock_init(struct sock *sk)
{
sock_lock_init_class_and_name(sk,
af_family_slock_key_strings[sk->sk_family],
af_family_slock_keys + sk->sk_family,
af_family_key_strings[sk->sk_family],
af_family_keys + sk->sk_family);
}
/*
* Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
* even temporarly, because of RCU lookups. sk_node should also be left as is.
* We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
*/
static void sock_copy(struct sock *nsk, const struct sock *osk)
{
#ifdef CONFIG_SECURITY_NETWORK
void *sptr = nsk->sk_security;
#endif
memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end));
#ifdef CONFIG_SECURITY_NETWORK
nsk->sk_security = sptr;
security_sk_clone(osk, nsk);
#endif
}
/*
* caches using SLAB_DESTROY_BY_RCU should let .next pointer from nulls nodes
* un-modified. Special care is taken when initializing object to zero.
*/
static inline void sk_prot_clear_nulls(struct sock *sk, int size)
{
if (offsetof(struct sock, sk_node.next) != 0)
memset(sk, 0, offsetof(struct sock, sk_node.next));
memset(&sk->sk_node.pprev, 0,
size - offsetof(struct sock, sk_node.pprev));
}
void sk_prot_clear_portaddr_nulls(struct sock *sk, int size)
{
unsigned long nulls1, nulls2;
nulls1 = offsetof(struct sock, __sk_common.skc_node.next);
nulls2 = offsetof(struct sock, __sk_common.skc_portaddr_node.next);
if (nulls1 > nulls2)
swap(nulls1, nulls2);
if (nulls1 != 0)
memset((char *)sk, 0, nulls1);
memset((char *)sk + nulls1 + sizeof(void *), 0,
nulls2 - nulls1 - sizeof(void *));
memset((char *)sk + nulls2 + sizeof(void *), 0,
size - nulls2 - sizeof(void *));
}
EXPORT_SYMBOL(sk_prot_clear_portaddr_nulls);
static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
int family)
{
struct sock *sk;
struct kmem_cache *slab;
slab = prot->slab;
if (slab != NULL) {
sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
if (!sk)
return sk;
if (priority & __GFP_ZERO) {
if (prot->clear_sk)
prot->clear_sk(sk, prot->obj_size);
else
sk_prot_clear_nulls(sk, prot->obj_size);
}
} else
sk = kmalloc(prot->obj_size, priority);
if (sk != NULL) {
kmemcheck_annotate_bitfield(sk, flags);
if (security_sk_alloc(sk, family, priority))
goto out_free;
if (!try_module_get(prot->owner))
goto out_free_sec;
sk_tx_queue_clear(sk);
}
return sk;
out_free_sec:
security_sk_free(sk);
out_free:
if (slab != NULL)
kmem_cache_free(slab, sk);
else
kfree(sk);
return NULL;
}
static void sk_prot_free(struct proto *prot, struct sock *sk)
{
struct kmem_cache *slab;
struct module *owner;
owner = prot->owner;
slab = prot->slab;
security_sk_free(sk);
if (slab != NULL)
kmem_cache_free(slab, sk);
else
kfree(sk);
module_put(owner);
}
#ifdef CONFIG_CGROUPS
void sock_update_classid(struct sock *sk)
{
u32 classid;
rcu_read_lock(); /* doing current task, which cannot vanish. */
classid = task_cls_classid(current);
rcu_read_unlock();
if (classid && classid != sk->sk_classid)
sk->sk_classid = classid;
}
EXPORT_SYMBOL(sock_update_classid);
void sock_update_netprioidx(struct sock *sk)
{
if (in_interrupt())
return;
sk->sk_cgrp_prioidx = task_netprioidx(current);
}
EXPORT_SYMBOL_GPL(sock_update_netprioidx);
#endif
/**
* sk_alloc - All socket objects are allocated here
* @net: the applicable net namespace
* @family: protocol family
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
* @prot: struct proto associated with this new sock instance
*/
struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
struct proto *prot)
{
struct sock *sk;
sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
if (sk) {
sk->sk_family = family;
/*
* See comment in struct sock definition to understand
* why we need sk_prot_creator -acme
*/
sk->sk_prot = sk->sk_prot_creator = prot;
sock_lock_init(sk);
sock_net_set(sk, get_net(net));
atomic_set(&sk->sk_wmem_alloc, 1);
sock_update_classid(sk);
sock_update_netprioidx(sk);
}
return sk;
}
EXPORT_SYMBOL(sk_alloc);
static void __sk_free(struct sock *sk)
{
struct sk_filter *filter;
if (sk->sk_destruct)
sk->sk_destruct(sk);
filter = rcu_dereference_check(sk->sk_filter,
atomic_read(&sk->sk_wmem_alloc) == 0);
if (filter) {
sk_filter_uncharge(sk, filter);
RCU_INIT_POINTER(sk->sk_filter, NULL);
}
sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
if (atomic_read(&sk->sk_omem_alloc))
pr_debug("%s: optmem leakage (%d bytes) detected\n",
__func__, atomic_read(&sk->sk_omem_alloc));
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
put_pid(sk->sk_peer_pid);
put_net(sock_net(sk));
sk_prot_free(sk->sk_prot_creator, sk);
}
void sk_free(struct sock *sk)
{
/*
* We subtract one from sk_wmem_alloc and can know if
* some packets are still in some tx queue.
* If not null, sock_wfree() will call __sk_free(sk) later
*/
if (atomic_dec_and_test(&sk->sk_wmem_alloc))
__sk_free(sk);
}
EXPORT_SYMBOL(sk_free);
/*
* Last sock_put should drop reference to sk->sk_net. It has already
* been dropped in sk_change_net. Taking reference to stopping namespace
* is not an option.
* Take reference to a socket to remove it from hash _alive_ and after that
* destroy it in the context of init_net.
*/
void sk_release_kernel(struct sock *sk)
{
if (sk == NULL || sk->sk_socket == NULL)
return;
sock_hold(sk);
sock_release(sk->sk_socket);
release_net(sock_net(sk));
sock_net_set(sk, get_net(&init_net));
sock_put(sk);
}
EXPORT_SYMBOL(sk_release_kernel);
static void sk_update_clone(const struct sock *sk, struct sock *newsk)
{
if (mem_cgroup_sockets_enabled && sk->sk_cgrp)
sock_update_memcg(newsk);
}
/**
* sk_clone_lock - clone a socket, and lock its clone
* @sk: the socket to clone
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
*
* Caller must unlock socket even in error path (bh_unlock_sock(newsk))
*/
struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
{
struct sock *newsk;
newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family);
if (newsk != NULL) {
struct sk_filter *filter;
sock_copy(newsk, sk);
/* SANITY */
get_net(sock_net(newsk));
sk_node_init(&newsk->sk_node);
sock_lock_init(newsk);
bh_lock_sock(newsk);
newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
newsk->sk_backlog.len = 0;
atomic_set(&newsk->sk_rmem_alloc, 0);
/*
* sk_wmem_alloc set to one (see sk_free() and sock_wfree())
*/
atomic_set(&newsk->sk_wmem_alloc, 1);
atomic_set(&newsk->sk_omem_alloc, 0);
skb_queue_head_init(&newsk->sk_receive_queue);
skb_queue_head_init(&newsk->sk_write_queue);
#ifdef CONFIG_NET_DMA
skb_queue_head_init(&newsk->sk_async_wait_queue);
#endif
spin_lock_init(&newsk->sk_dst_lock);
rwlock_init(&newsk->sk_callback_lock);
lockdep_set_class_and_name(&newsk->sk_callback_lock,
af_callback_keys + newsk->sk_family,
af_family_clock_key_strings[newsk->sk_family]);
newsk->sk_dst_cache = NULL;
newsk->sk_wmem_queued = 0;
newsk->sk_forward_alloc = 0;
newsk->sk_send_head = NULL;
newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
sock_reset_flag(newsk, SOCK_DONE);
skb_queue_head_init(&newsk->sk_error_queue);
filter = rcu_dereference_protected(newsk->sk_filter, 1);
if (filter != NULL)
sk_filter_charge(newsk, filter);
if (unlikely(xfrm_sk_clone_policy(newsk))) {
/* It is still raw copy of parent, so invalidate
* destructor and make plain sk_free() */
newsk->sk_destruct = NULL;
bh_unlock_sock(newsk);
sk_free(newsk);
newsk = NULL;
goto out;
}
newsk->sk_err = 0;
newsk->sk_priority = 0;
/*
* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
atomic_set(&newsk->sk_refcnt, 2);
/*
* Increment the counter in the same struct proto as the master
* sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
* is the same as sk->sk_prot->socks, as this field was copied
* with memcpy).
*
* This _changes_ the previous behaviour, where
* tcp_create_openreq_child always was incrementing the
* equivalent to tcp_prot->socks (inet_sock_nr), so this have
* to be taken into account in all callers. -acme
*/
sk_refcnt_debug_inc(newsk);
sk_set_socket(newsk, NULL);
newsk->sk_wq = NULL;
sk_update_clone(sk, newsk);
if (newsk->sk_prot->sockets_allocated)
sk_sockets_allocated_inc(newsk);
if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
net_enable_timestamp();
}
out:
return newsk;
}
EXPORT_SYMBOL_GPL(sk_clone_lock);
void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
{
__sk_dst_set(sk, dst);
sk->sk_route_caps = dst->dev->features;
if (sk->sk_route_caps & NETIF_F_GSO)
sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
sk->sk_route_caps &= ~sk->sk_route_nocaps;
if (sk_can_gso(sk)) {
if (dst->header_len) {
sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
} else {
sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
sk->sk_gso_max_size = dst->dev->gso_max_size;
}
}
}
EXPORT_SYMBOL_GPL(sk_setup_caps);
void __init sk_init(void)
{
if (totalram_pages <= 4096) {
sysctl_wmem_max = 32767;
sysctl_rmem_max = 32767;
sysctl_wmem_default = 32767;
sysctl_rmem_default = 32767;
} else if (totalram_pages >= 131072) {
sysctl_wmem_max = 131071;
sysctl_rmem_max = 131071;
}
}
/*
* Simple resource managers for sockets.
*/
/*
* Write buffer destructor automatically called from kfree_skb.
*/
void sock_wfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
unsigned int len = skb->truesize;
if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
/*
* Keep a reference on sk_wmem_alloc, this will be released
* after sk_write_space() call
*/
atomic_sub(len - 1, &sk->sk_wmem_alloc);
sk->sk_write_space(sk);
len = 1;
}
/*
* if sk_wmem_alloc reaches 0, we must finish what sk_free()
* could not do because of in-flight packets
*/
if (atomic_sub_and_test(len, &sk->sk_wmem_alloc))
__sk_free(sk);
}
EXPORT_SYMBOL(sock_wfree);
/*
* Read buffer destructor automatically called from kfree_skb.
*/
void sock_rfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
unsigned int len = skb->truesize;
atomic_sub(len, &sk->sk_rmem_alloc);
sk_mem_uncharge(sk, len);
}
EXPORT_SYMBOL(sock_rfree);
int sock_i_uid(struct sock *sk)
{
int uid;
read_lock_bh(&sk->sk_callback_lock);
uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : 0;
read_unlock_bh(&sk->sk_callback_lock);
return uid;
}
EXPORT_SYMBOL(sock_i_uid);
unsigned long sock_i_ino(struct sock *sk)
{
unsigned long ino;
read_lock_bh(&sk->sk_callback_lock);
ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
read_unlock_bh(&sk->sk_callback_lock);
return ino;
}
EXPORT_SYMBOL(sock_i_ino);
/*
* Allocate a skb from the socket's send buffer.
*/
struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
gfp_t priority)
{
if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
struct sk_buff *skb = alloc_skb(size, priority);
if (skb) {
skb_set_owner_w(skb, sk);
return skb;
}
}
return NULL;
}
EXPORT_SYMBOL(sock_wmalloc);
/*
* Allocate a skb from the socket's receive buffer.
*/
struct sk_buff *sock_rmalloc(struct sock *sk, unsigned long size, int force,
gfp_t priority)
{
if (force || atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
struct sk_buff *skb = alloc_skb(size, priority);
if (skb) {
skb_set_owner_r(skb, sk);
return skb;
}
}
return NULL;
}
/*
* Allocate a memory block from the socket's option memory buffer.
*/
void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
{
if ((unsigned int)size <= sysctl_optmem_max &&
atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) {
void *mem;
/* First do the add, to avoid the race if kmalloc
* might sleep.
*/
atomic_add(size, &sk->sk_omem_alloc);
mem = kmalloc(size, priority);
if (mem)
return mem;
atomic_sub(size, &sk->sk_omem_alloc);
}
return NULL;
}
EXPORT_SYMBOL(sock_kmalloc);
/*
* Free an option memory block.
*/
void sock_kfree_s(struct sock *sk, void *mem, int size)
{
kfree(mem);
atomic_sub(size, &sk->sk_omem_alloc);
}
EXPORT_SYMBOL(sock_kfree_s);
/* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
I think, these locks should be removed for datagram sockets.
*/
static long sock_wait_for_wmem(struct sock *sk, long timeo)
{
DEFINE_WAIT(wait);
clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
for (;;) {
if (!timeo)
break;
if (signal_pending(current))
break;
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf)
break;
if (sk->sk_shutdown & SEND_SHUTDOWN)
break;
if (sk->sk_err)
break;
timeo = schedule_timeout(timeo);
}
finish_wait(sk_sleep(sk), &wait);
return timeo;
}
/*
* Generic send/receive buffer handlers
*/
struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
unsigned long data_len, int noblock,
int *errcode)
{
struct sk_buff *skb;
gfp_t gfp_mask;
long timeo;
int err;
int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
err = -EMSGSIZE;
if (npages > MAX_SKB_FRAGS)
goto failure;
gfp_mask = sk->sk_allocation;
if (gfp_mask & __GFP_WAIT)
gfp_mask |= __GFP_REPEAT;
timeo = sock_sndtimeo(sk, noblock);
while (1) {
err = sock_error(sk);
if (err != 0)
goto failure;
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto failure;
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
skb = alloc_skb(header_len, gfp_mask);
if (skb) {
int i;
/* No pages, we're done... */
if (!data_len)
break;
skb->truesize += data_len;
skb_shinfo(skb)->nr_frags = npages;
for (i = 0; i < npages; i++) {
struct page *page;
page = alloc_pages(sk->sk_allocation, 0);
if (!page) {
err = -ENOBUFS;
skb_shinfo(skb)->nr_frags = i;
kfree_skb(skb);
goto failure;
}
__skb_fill_page_desc(skb, i,
page, 0,
(data_len >= PAGE_SIZE ?
PAGE_SIZE :
data_len));
data_len -= PAGE_SIZE;
}
/* Full success... */
break;
}
err = -ENOBUFS;
goto failure;
}
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
err = -EAGAIN;
if (!timeo)
goto failure;
if (signal_pending(current))
goto interrupted;
timeo = sock_wait_for_wmem(sk, timeo);
}
skb_set_owner_w(skb, sk);
return skb;
interrupted:
err = sock_intr_errno(timeo);
failure:
*errcode = err;
return NULL;
}
EXPORT_SYMBOL(sock_alloc_send_pskb);
struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
int noblock, int *errcode)
{
return sock_alloc_send_pskb(sk, size, 0, noblock, errcode);
}
EXPORT_SYMBOL(sock_alloc_send_skb);
static void __lock_sock(struct sock *sk)
__releases(&sk->sk_lock.slock)
__acquires(&sk->sk_lock.slock)
{
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
TASK_UNINTERRUPTIBLE);
spin_unlock_bh(&sk->sk_lock.slock);
schedule();
spin_lock_bh(&sk->sk_lock.slock);
if (!sock_owned_by_user(sk))
break;
}
finish_wait(&sk->sk_lock.wq, &wait);
}
static void __release_sock(struct sock *sk)
__releases(&sk->sk_lock.slock)
__acquires(&sk->sk_lock.slock)
{
struct sk_buff *skb = sk->sk_backlog.head;
do {
sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
bh_unlock_sock(sk);
do {
struct sk_buff *next = skb->next;
prefetch(next);
WARN_ON_ONCE(skb_dst_is_noref(skb));
skb->next = NULL;
sk_backlog_rcv(sk, skb);
/*
* We are in process context here with softirqs
* disabled, use cond_resched_softirq() to preempt.
* This is safe to do because we've taken the backlog
* queue private:
*/
cond_resched_softirq();
skb = next;
} while (skb != NULL);
bh_lock_sock(sk);
} while ((skb = sk->sk_backlog.head) != NULL);
/*
* Doing the zeroing here guarantee we can not loop forever
* while a wild producer attempts to flood us.
*/
sk->sk_backlog.len = 0;
}
/**
* sk_wait_data - wait for data to arrive at sk_receive_queue
* @sk: sock to wait on
* @timeo: for how long
*
* Now socket state including sk->sk_err is changed only under lock,
* hence we may omit checks after joining wait queue.
* We check receive queue before schedule() only as optimization;
* it is very likely that release_sock() added new data.
*/
int sk_wait_data(struct sock *sk, long *timeo)
{
int rc;
DEFINE_WAIT(wait);
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
rc = sk_wait_event(sk, timeo, !skb_queue_empty(&sk->sk_receive_queue));
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
finish_wait(sk_sleep(sk), &wait);
return rc;
}
EXPORT_SYMBOL(sk_wait_data);
/**
* __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
* @sk: socket
* @size: memory size to allocate
* @kind: allocation type
*
* If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
* rmem allocation. This function assumes that protocols which have
* memory_pressure use sk_wmem_queued as write buffer accounting.
*/
int __sk_mem_schedule(struct sock *sk, int size, int kind)
{
struct proto *prot = sk->sk_prot;
int amt = sk_mem_pages(size);
long allocated;
int parent_status = UNDER_LIMIT;
sk->sk_forward_alloc += amt * SK_MEM_QUANTUM;
allocated = sk_memory_allocated_add(sk, amt, &parent_status);
/* Under limit. */
if (parent_status == UNDER_LIMIT &&
allocated <= sk_prot_mem_limits(sk, 0)) {
sk_leave_memory_pressure(sk);
return 1;
}
/* Under pressure. (we or our parents) */
if ((parent_status > SOFT_LIMIT) ||
allocated > sk_prot_mem_limits(sk, 1))
sk_enter_memory_pressure(sk);
/* Over hard limit (we or our parents) */
if ((parent_status == OVER_LIMIT) ||
(allocated > sk_prot_mem_limits(sk, 2)))
goto suppress_allocation;
/* guarantee minimum buffer size under pressure */
if (kind == SK_MEM_RECV) {
if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0])
return 1;
} else { /* SK_MEM_SEND */
if (sk->sk_type == SOCK_STREAM) {
if (sk->sk_wmem_queued < prot->sysctl_wmem[0])
return 1;
} else if (atomic_read(&sk->sk_wmem_alloc) <
prot->sysctl_wmem[0])
return 1;
}
if (sk_has_memory_pressure(sk)) {
int alloc;
if (!sk_under_memory_pressure(sk))
return 1;
alloc = sk_sockets_allocated_read_positive(sk);
if (sk_prot_mem_limits(sk, 2) > alloc *
sk_mem_pages(sk->sk_wmem_queued +
atomic_read(&sk->sk_rmem_alloc) +
sk->sk_forward_alloc))
return 1;
}
suppress_allocation:
if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
sk_stream_moderate_sndbuf(sk);
/* Fail only if socket is _under_ its sndbuf.
* In this case we cannot block, so that we have to fail.
*/
if (sk->sk_wmem_queued + size >= sk->sk_sndbuf)
return 1;
}
trace_sock_exceed_buf_limit(sk, prot, allocated);
/* Alas. Undo changes. */
sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM;
sk_memory_allocated_sub(sk, amt);
return 0;
}
EXPORT_SYMBOL(__sk_mem_schedule);
/**
* __sk_reclaim - reclaim memory_allocated
* @sk: socket
*/
void __sk_mem_reclaim(struct sock *sk)
{
sk_memory_allocated_sub(sk,
sk->sk_forward_alloc >> SK_MEM_QUANTUM_SHIFT);
sk->sk_forward_alloc &= SK_MEM_QUANTUM - 1;
if (sk_under_memory_pressure(sk) &&
(sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
sk_leave_memory_pressure(sk);
}
EXPORT_SYMBOL(__sk_mem_reclaim);
/*
* Set of default routines for initialising struct proto_ops when
* the protocol does not support a particular function. In certain
* cases where it makes no sense for a protocol to have a "do nothing"
* function, some default processing is provided.
*/
int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_bind);
int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
int len, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_connect);
int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_socketpair);
int sock_no_accept(struct socket *sock, struct socket *newsock, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_accept);
int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
int *len, int peer)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_getname);
unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt)
{
return 0;
}
EXPORT_SYMBOL(sock_no_poll);
int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_ioctl);
int sock_no_listen(struct socket *sock, int backlog)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_listen);
int sock_no_shutdown(struct socket *sock, int how)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_shutdown);
int sock_no_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_setsockopt);
int sock_no_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_getsockopt);
int sock_no_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t len)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_sendmsg);
int sock_no_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t len, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_recvmsg);
int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
{
/* Mirror missing mmap method error code */
return -ENODEV;
}
EXPORT_SYMBOL(sock_no_mmap);
ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
{
ssize_t res;
struct msghdr msg = {.msg_flags = flags};
struct kvec iov;
char *kaddr = kmap(page);
iov.iov_base = kaddr + offset;
iov.iov_len = size;
res = kernel_sendmsg(sock, &msg, &iov, 1, size);
kunmap(page);
return res;
}
EXPORT_SYMBOL(sock_no_sendpage);
/*
* Default Socket Callbacks
*/
static void sock_def_wakeup(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_all(&wq->wait);
rcu_read_unlock();
}
static void sock_def_error_report(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_poll(&wq->wait, POLLERR);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
rcu_read_unlock();
}
static void sock_def_readable(struct sock *sk, int len)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI |
POLLRDNORM | POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static void sock_def_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
/* Do not wake up a writer until he can make "significant"
* progress. --DaveM
*/
if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLWRNORM | POLLWRBAND);
/* Should agree with poll, otherwise some programs break */
if (sock_writeable(sk))
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
static void sock_def_destruct(struct sock *sk)
{
kfree(sk->sk_protinfo);
}
void sk_send_sigurg(struct sock *sk)
{
if (sk->sk_socket && sk->sk_socket->file)
if (send_sigurg(&sk->sk_socket->file->f_owner))
sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
}
EXPORT_SYMBOL(sk_send_sigurg);
void sk_reset_timer(struct sock *sk, struct timer_list* timer,
unsigned long expires)
{
if (!mod_timer(timer, expires))
sock_hold(sk);
}
EXPORT_SYMBOL(sk_reset_timer);
void sk_stop_timer(struct sock *sk, struct timer_list* timer)
{
if (timer_pending(timer) && del_timer(timer))
__sock_put(sk);
}
EXPORT_SYMBOL(sk_stop_timer);
void sock_init_data(struct socket *sock, struct sock *sk)
{
skb_queue_head_init(&sk->sk_receive_queue);
skb_queue_head_init(&sk->sk_write_queue);
skb_queue_head_init(&sk->sk_error_queue);
#ifdef CONFIG_NET_DMA
skb_queue_head_init(&sk->sk_async_wait_queue);
#endif
sk->sk_send_head = NULL;
init_timer(&sk->sk_timer);
sk->sk_allocation = GFP_KERNEL;
sk->sk_rcvbuf = sysctl_rmem_default;
sk->sk_sndbuf = sysctl_wmem_default;
sk->sk_state = TCP_CLOSE;
sk_set_socket(sk, sock);
sock_set_flag(sk, SOCK_ZAPPED);
if (sock) {
sk->sk_type = sock->type;
sk->sk_wq = sock->wq;
sock->sk = sk;
} else
sk->sk_wq = NULL;
spin_lock_init(&sk->sk_dst_lock);
rwlock_init(&sk->sk_callback_lock);
lockdep_set_class_and_name(&sk->sk_callback_lock,
af_callback_keys + sk->sk_family,
af_family_clock_key_strings[sk->sk_family]);
sk->sk_state_change = sock_def_wakeup;
sk->sk_data_ready = sock_def_readable;
sk->sk_write_space = sock_def_write_space;
sk->sk_error_report = sock_def_error_report;
sk->sk_destruct = sock_def_destruct;
sk->sk_sndmsg_page = NULL;
sk->sk_sndmsg_off = 0;
sk->sk_peek_off = -1;
sk->sk_peer_pid = NULL;
sk->sk_peer_cred = NULL;
sk->sk_write_pending = 0;
sk->sk_rcvlowat = 1;
sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
sk->sk_stamp = ktime_set(-1L, 0);
/*
* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
atomic_set(&sk->sk_refcnt, 1);
atomic_set(&sk->sk_drops, 0);
}
EXPORT_SYMBOL(sock_init_data);
void lock_sock_nested(struct sock *sk, int subclass)
{
might_sleep();
spin_lock_bh(&sk->sk_lock.slock);
if (sk->sk_lock.owned)
__lock_sock(sk);
sk->sk_lock.owned = 1;
spin_unlock(&sk->sk_lock.slock);
/*
* The sk_lock has mutex_lock() semantics here:
*/
mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
local_bh_enable();
}
EXPORT_SYMBOL(lock_sock_nested);
void release_sock(struct sock *sk)
{
/*
* The sk_lock has mutex_unlock() semantics:
*/
mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);
spin_lock_bh(&sk->sk_lock.slock);
if (sk->sk_backlog.tail)
__release_sock(sk);
sk->sk_lock.owned = 0;
if (waitqueue_active(&sk->sk_lock.wq))
wake_up(&sk->sk_lock.wq);
spin_unlock_bh(&sk->sk_lock.slock);
}
EXPORT_SYMBOL(release_sock);
/**
* lock_sock_fast - fast version of lock_sock
* @sk: socket
*
* This version should be used for very small section, where process wont block
* return false if fast path is taken
* sk_lock.slock locked, owned = 0, BH disabled
* return true if slow path is taken
* sk_lock.slock unlocked, owned = 1, BH enabled
*/
bool lock_sock_fast(struct sock *sk)
{
might_sleep();
spin_lock_bh(&sk->sk_lock.slock);
if (!sk->sk_lock.owned)
/*
* Note : We must disable BH
*/
return false;
__lock_sock(sk);
sk->sk_lock.owned = 1;
spin_unlock(&sk->sk_lock.slock);
/*
* The sk_lock has mutex_lock() semantics here:
*/
mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_);
local_bh_enable();
return true;
}
EXPORT_SYMBOL(lock_sock_fast);
int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp)
{
struct timeval tv;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
tv = ktime_to_timeval(sk->sk_stamp);
if (tv.tv_sec == -1)
return -ENOENT;
if (tv.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
tv = ktime_to_timeval(sk->sk_stamp);
}
return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0;
}
EXPORT_SYMBOL(sock_get_timestamp);
int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp)
{
struct timespec ts;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
ts = ktime_to_timespec(sk->sk_stamp);
if (ts.tv_sec == -1)
return -ENOENT;
if (ts.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
ts = ktime_to_timespec(sk->sk_stamp);
}
return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0;
}
EXPORT_SYMBOL(sock_get_timestampns);
void sock_enable_timestamp(struct sock *sk, int flag)
{
if (!sock_flag(sk, flag)) {
unsigned long previous_flags = sk->sk_flags;
sock_set_flag(sk, flag);
/*
* we just set one of the two flags which require net
* time stamping, but time stamping might have been on
* already because of the other one
*/
if (!(previous_flags & SK_FLAGS_TIMESTAMP))
net_enable_timestamp();
}
}
/*
* Get a socket option on an socket.
*
* FIX: POSIX 1003.1g is very ambiguous here. It states that
* asynchronous errors should be reported by getsockopt. We assume
* this means if you specify SO_ERROR (otherwise whats the point of it).
*/
int sock_common_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(sock_common_getsockopt);
#ifdef CONFIG_COMPAT
int compat_sock_common_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
if (sk->sk_prot->compat_getsockopt != NULL)
return sk->sk_prot->compat_getsockopt(sk, level, optname,
optval, optlen);
return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_sock_common_getsockopt);
#endif
int sock_common_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
int addr_len = 0;
int err;
err = sk->sk_prot->recvmsg(iocb, sk, msg, size, flags & MSG_DONTWAIT,
flags & ~MSG_DONTWAIT, &addr_len);
if (err >= 0)
msg->msg_namelen = addr_len;
return err;
}
EXPORT_SYMBOL(sock_common_recvmsg);
/*
* Set socket options on an inet socket.
*/
int sock_common_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(sock_common_setsockopt);
#ifdef CONFIG_COMPAT
int compat_sock_common_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
if (sk->sk_prot->compat_setsockopt != NULL)
return sk->sk_prot->compat_setsockopt(sk, level, optname,
optval, optlen);
return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_sock_common_setsockopt);
#endif
void sk_common_release(struct sock *sk)
{
if (sk->sk_prot->destroy)
sk->sk_prot->destroy(sk);
/*
* Observation: when sock_common_release is called, processes have
* no access to socket. But net still has.
* Step one, detach it from networking:
*
* A. Remove from hash tables.
*/
sk->sk_prot->unhash(sk);
/*
* In this point socket cannot receive new packets, but it is possible
* that some packets are in flight because some CPU runs receiver and
* did hash table lookup before we unhashed socket. They will achieve
* receive queue and will be purged by socket destructor.
*
* Also we still have packets pending on receive queue and probably,
* our own packets waiting in device queues. sock_destroy will drain
* receive queue, but transmitted packets will delay socket destruction
* until the last reference will be released.
*/
sock_orphan(sk);
xfrm_sk_free_policy(sk);
sk_refcnt_debug_release(sk);
sock_put(sk);
}
EXPORT_SYMBOL(sk_common_release);
#ifdef CONFIG_PROC_FS
#define PROTO_INUSE_NR 64 /* should be enough for the first time */
struct prot_inuse {
int val[PROTO_INUSE_NR];
};
static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
#ifdef CONFIG_NET_NS
void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
{
__this_cpu_add(net->core.inuse->val[prot->inuse_idx], val);
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
int sock_prot_inuse_get(struct net *net, struct proto *prot)
{
int cpu, idx = prot->inuse_idx;
int res = 0;
for_each_possible_cpu(cpu)
res += per_cpu_ptr(net->core.inuse, cpu)->val[idx];
return res >= 0 ? res : 0;
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
static int __net_init sock_inuse_init_net(struct net *net)
{
net->core.inuse = alloc_percpu(struct prot_inuse);
return net->core.inuse ? 0 : -ENOMEM;
}
static void __net_exit sock_inuse_exit_net(struct net *net)
{
free_percpu(net->core.inuse);
}
static struct pernet_operations net_inuse_ops = {
.init = sock_inuse_init_net,
.exit = sock_inuse_exit_net,
};
static __init int net_inuse_init(void)
{
if (register_pernet_subsys(&net_inuse_ops))
panic("Cannot initialize net inuse counters");
return 0;
}
core_initcall(net_inuse_init);
#else
static DEFINE_PER_CPU(struct prot_inuse, prot_inuse);
void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
{
__this_cpu_add(prot_inuse.val[prot->inuse_idx], val);
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
int sock_prot_inuse_get(struct net *net, struct proto *prot)
{
int cpu, idx = prot->inuse_idx;
int res = 0;
for_each_possible_cpu(cpu)
res += per_cpu(prot_inuse, cpu).val[idx];
return res >= 0 ? res : 0;
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
#endif
static void assign_proto_idx(struct proto *prot)
{
prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) {
pr_err("PROTO_INUSE_NR exhausted\n");
return;
}
set_bit(prot->inuse_idx, proto_inuse_idx);
}
static void release_proto_idx(struct proto *prot)
{
if (prot->inuse_idx != PROTO_INUSE_NR - 1)
clear_bit(prot->inuse_idx, proto_inuse_idx);
}
#else
static inline void assign_proto_idx(struct proto *prot)
{
}
static inline void release_proto_idx(struct proto *prot)
{
}
#endif
int proto_register(struct proto *prot, int alloc_slab)
{
if (alloc_slab) {
prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0,
SLAB_HWCACHE_ALIGN | prot->slab_flags,
NULL);
if (prot->slab == NULL) {
pr_crit("%s: Can't create sock SLAB cache!\n",
prot->name);
goto out;
}
if (prot->rsk_prot != NULL) {
prot->rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name);
if (prot->rsk_prot->slab_name == NULL)
goto out_free_sock_slab;
prot->rsk_prot->slab = kmem_cache_create(prot->rsk_prot->slab_name,
prot->rsk_prot->obj_size, 0,
SLAB_HWCACHE_ALIGN, NULL);
if (prot->rsk_prot->slab == NULL) {
pr_crit("%s: Can't create request sock SLAB cache!\n",
prot->name);
goto out_free_request_sock_slab_name;
}
}
if (prot->twsk_prot != NULL) {
prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name);
if (prot->twsk_prot->twsk_slab_name == NULL)
goto out_free_request_sock_slab;
prot->twsk_prot->twsk_slab =
kmem_cache_create(prot->twsk_prot->twsk_slab_name,
prot->twsk_prot->twsk_obj_size,
0,
SLAB_HWCACHE_ALIGN |
prot->slab_flags,
NULL);
if (prot->twsk_prot->twsk_slab == NULL)
goto out_free_timewait_sock_slab_name;
}
}
mutex_lock(&proto_list_mutex);
list_add(&prot->node, &proto_list);
assign_proto_idx(prot);
mutex_unlock(&proto_list_mutex);
return 0;
out_free_timewait_sock_slab_name:
kfree(prot->twsk_prot->twsk_slab_name);
out_free_request_sock_slab:
if (prot->rsk_prot && prot->rsk_prot->slab) {
kmem_cache_destroy(prot->rsk_prot->slab);
prot->rsk_prot->slab = NULL;
}
out_free_request_sock_slab_name:
if (prot->rsk_prot)
kfree(prot->rsk_prot->slab_name);
out_free_sock_slab:
kmem_cache_destroy(prot->slab);
prot->slab = NULL;
out:
return -ENOBUFS;
}
EXPORT_SYMBOL(proto_register);
void proto_unregister(struct proto *prot)
{
mutex_lock(&proto_list_mutex);
release_proto_idx(prot);
list_del(&prot->node);
mutex_unlock(&proto_list_mutex);
if (prot->slab != NULL) {
kmem_cache_destroy(prot->slab);
prot->slab = NULL;
}
if (prot->rsk_prot != NULL && prot->rsk_prot->slab != NULL) {
kmem_cache_destroy(prot->rsk_prot->slab);
kfree(prot->rsk_prot->slab_name);
prot->rsk_prot->slab = NULL;
}
if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) {
kmem_cache_destroy(prot->twsk_prot->twsk_slab);
kfree(prot->twsk_prot->twsk_slab_name);
prot->twsk_prot->twsk_slab = NULL;
}
}
EXPORT_SYMBOL(proto_unregister);
#ifdef CONFIG_PROC_FS
static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(proto_list_mutex)
{
mutex_lock(&proto_list_mutex);
return seq_list_start_head(&proto_list, *pos);
}
static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_list_next(v, &proto_list, pos);
}
static void proto_seq_stop(struct seq_file *seq, void *v)
__releases(proto_list_mutex)
{
mutex_unlock(&proto_list_mutex);
}
static char proto_method_implemented(const void *method)
{
return method == NULL ? 'n' : 'y';
}
static long sock_prot_memory_allocated(struct proto *proto)
{
return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
}
static char *sock_prot_memory_pressure(struct proto *proto)
{
return proto->memory_pressure != NULL ?
proto_memory_pressure(proto) ? "yes" : "no" : "NI";
}
static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
{
seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
"%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
proto->name,
proto->obj_size,
sock_prot_inuse_get(seq_file_net(seq), proto),
sock_prot_memory_allocated(proto),
sock_prot_memory_pressure(proto),
proto->max_header,
proto->slab == NULL ? "no" : "yes",
module_name(proto->owner),
proto_method_implemented(proto->close),
proto_method_implemented(proto->connect),
proto_method_implemented(proto->disconnect),
proto_method_implemented(proto->accept),
proto_method_implemented(proto->ioctl),
proto_method_implemented(proto->init),
proto_method_implemented(proto->destroy),
proto_method_implemented(proto->shutdown),
proto_method_implemented(proto->setsockopt),
proto_method_implemented(proto->getsockopt),
proto_method_implemented(proto->sendmsg),
proto_method_implemented(proto->recvmsg),
proto_method_implemented(proto->sendpage),
proto_method_implemented(proto->bind),
proto_method_implemented(proto->backlog_rcv),
proto_method_implemented(proto->hash),
proto_method_implemented(proto->unhash),
proto_method_implemented(proto->get_port),
proto_method_implemented(proto->enter_memory_pressure));
}
static int proto_seq_show(struct seq_file *seq, void *v)
{
if (v == &proto_list)
seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
"protocol",
"size",
"sockets",
"memory",
"press",
"maxhdr",
"slab",
"module",
"cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n");
else
proto_seq_printf(seq, list_entry(v, struct proto, node));
return 0;
}
static const struct seq_operations proto_seq_ops = {
.start = proto_seq_start,
.next = proto_seq_next,
.stop = proto_seq_stop,
.show = proto_seq_show,
};
static int proto_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &proto_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations proto_seq_fops = {
.owner = THIS_MODULE,
.open = proto_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static __net_init int proto_init_net(struct net *net)
{
if (!proc_net_fops_create(net, "protocols", S_IRUGO, &proto_seq_fops))
return -ENOMEM;
return 0;
}
static __net_exit void proto_exit_net(struct net *net)
{
proc_net_remove(net, "protocols");
}
static __net_initdata struct pernet_operations proto_net_ops = {
.init = proto_init_net,
.exit = proto_exit_net,
};
static int __init proto_init(void)
{
return register_pernet_subsys(&proto_net_ops);
}
subsys_initcall(proto_init);
#endif /* PROC_FS */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3641_0 |
crossvul-cpp_data_bad_245_0 | /**
* @file
* Send/receive commands to/from an IMAP server
*
* @authors
* Copyright (C) 1996-1998,2010,2012 Michael R. Elkins <me@mutt.org>
* Copyright (C) 1996-1999 Brandon Long <blong@fiction.net>
* Copyright (C) 1999-2009,2011 Brendan Cully <brendan@kublai.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @page imap_command Send/receive commands to/from an IMAP server
*
* Send/receive commands to/from an IMAP server
*/
#include "config.h"
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "imap_private.h"
#include "mutt/mutt.h"
#include "conn/conn.h"
#include "buffy.h"
#include "context.h"
#include "globals.h"
#include "header.h"
#include "imap/imap.h"
#include "mailbox.h"
#include "message.h"
#include "mutt_account.h"
#include "mutt_menu.h"
#include "mutt_socket.h"
#include "mx.h"
#include "options.h"
#include "protos.h"
#include "url.h"
#define IMAP_CMD_BUFSIZE 512
/**
* Capabilities - Server capabilities strings that we understand
*
* @note This must be kept in the same order as ImapCaps.
*
* @note Gmail documents one string but use another, so we support both.
*/
static const char *const Capabilities[] = {
"IMAP4", "IMAP4rev1", "STATUS", "ACL",
"NAMESPACE", "AUTH=CRAM-MD5", "AUTH=GSSAPI", "AUTH=ANONYMOUS",
"STARTTLS", "LOGINDISABLED", "IDLE", "SASL-IR",
"ENABLE", "X-GM-EXT-1", "X-GM-EXT1", NULL,
};
/**
* cmd_queue_full - Is the IMAP command queue full?
* @param idata Server data
* @retval true Queue is full
*/
static bool cmd_queue_full(struct ImapData *idata)
{
if ((idata->nextcmd + 1) % idata->cmdslots == idata->lastcmd)
return true;
return false;
}
/**
* cmd_new - Create and queue a new command control block
* @param idata IMAP data
* @retval NULL if the pipeline is full
* @retval ptr New command
*/
static struct ImapCommand *cmd_new(struct ImapData *idata)
{
struct ImapCommand *cmd = NULL;
if (cmd_queue_full(idata))
{
mutt_debug(3, "IMAP command queue full\n");
return NULL;
}
cmd = idata->cmds + idata->nextcmd;
idata->nextcmd = (idata->nextcmd + 1) % idata->cmdslots;
snprintf(cmd->seq, sizeof(cmd->seq), "a%04u", idata->seqno++);
if (idata->seqno > 9999)
idata->seqno = 0;
cmd->state = IMAP_CMD_NEW;
return cmd;
}
/**
* cmd_queue - Add a IMAP command to the queue
* @param idata Server data
* @param cmdstr Command string
* @param flags Server flags, e.g. #IMAP_CMD_POLL
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If the queue is full, attempts to drain it.
*/
static int cmd_queue(struct ImapData *idata, const char *cmdstr, int flags)
{
if (cmd_queue_full(idata))
{
mutt_debug(3, "Draining IMAP command pipeline\n");
const int rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK | (flags & IMAP_CMD_POLL));
if (rc < 0 && rc != -2)
return rc;
}
struct ImapCommand *cmd = cmd_new(idata);
if (!cmd)
return IMAP_CMD_BAD;
if (mutt_buffer_printf(idata->cmdbuf, "%s %s\r\n", cmd->seq, cmdstr) < 0)
return IMAP_CMD_BAD;
return 0;
}
/**
* cmd_handle_fatal - When ImapData is in fatal state, do what we can
* @param idata Server data
*/
static void cmd_handle_fatal(struct ImapData *idata)
{
idata->status = IMAP_FATAL;
if ((idata->state >= IMAP_SELECTED) && (idata->reopen & IMAP_REOPEN_ALLOW))
{
mx_fastclose_mailbox(idata->ctx);
mutt_socket_close(idata->conn);
mutt_error(_("Mailbox %s@%s closed"), idata->conn->account.login,
idata->conn->account.host);
idata->state = IMAP_DISCONNECTED;
}
imap_close_connection(idata);
if (!idata->recovering)
{
idata->recovering = true;
if (imap_conn_find(&idata->conn->account, 0))
mutt_clear_error();
idata->recovering = false;
}
}
/**
* cmd_start - Start a new IMAP command
* @param idata Server data
* @param cmdstr Command string
* @param flags Command flags, e.g. #IMAP_CMD_QUEUE
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_start(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return -1;
}
if (cmdstr && ((rc = cmd_queue(idata, cmdstr, flags)) < 0))
return rc;
if (flags & IMAP_CMD_QUEUE)
return 0;
if (idata->cmdbuf->dptr == idata->cmdbuf->data)
return IMAP_CMD_BAD;
rc = mutt_socket_send_d(idata->conn, idata->cmdbuf->data,
(flags & IMAP_CMD_PASS) ? IMAP_LOG_PASS : IMAP_LOG_CMD);
idata->cmdbuf->dptr = idata->cmdbuf->data;
/* unidle when command queue is flushed */
if (idata->state == IMAP_IDLE)
idata->state = IMAP_SELECTED;
return (rc < 0) ? IMAP_CMD_BAD : 0;
}
/**
* cmd_status - parse response line for tagged OK/NO/BAD
* @param s Status string from server
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
static int cmd_status(const char *s)
{
s = imap_next_word((char *) s);
if (mutt_str_strncasecmp("OK", s, 2) == 0)
return IMAP_CMD_OK;
if (mutt_str_strncasecmp("NO", s, 2) == 0)
return IMAP_CMD_NO;
return IMAP_CMD_BAD;
}
/**
* cmd_parse_expunge - Parse expunge command
* @param idata Server data
* @param s String containing MSN of message to expunge
*
* cmd_parse_expunge: mark headers with new sequence ID and mark idata to be
* reopened at our earliest convenience
*/
static void cmd_parse_expunge(struct ImapData *idata, const char *s)
{
unsigned int exp_msn;
struct Header *h = NULL;
mutt_debug(2, "Handling EXPUNGE\n");
if (mutt_str_atoui(s, &exp_msn) < 0 || exp_msn < 1 || exp_msn > idata->max_msn)
return;
h = idata->msn_index[exp_msn - 1];
if (h)
{
/* imap_expunge_mailbox() will rewrite h->index.
* It needs to resort using SORT_ORDER anyway, so setting to INT_MAX
* makes the code simpler and possibly more efficient. */
h->index = INT_MAX;
HEADER_DATA(h)->msn = 0;
}
/* decrement seqno of those above. */
for (unsigned int cur = exp_msn; cur < idata->max_msn; cur++)
{
h = idata->msn_index[cur];
if (h)
HEADER_DATA(h)->msn--;
idata->msn_index[cur - 1] = h;
}
idata->msn_index[idata->max_msn - 1] = NULL;
idata->max_msn--;
idata->reopen |= IMAP_EXPUNGE_PENDING;
}
/**
* cmd_parse_fetch - Load fetch response into ImapData
* @param idata Server data
* @param s String containing MSN of message to fetch
*
* Currently only handles unanticipated FETCH responses, and only FLAGS data.
* We get these if another client has changed flags for a mailbox we've
* selected. Of course, a lot of code here duplicates code in message.c.
*/
static void cmd_parse_fetch(struct ImapData *idata, char *s)
{
unsigned int msn, uid;
struct Header *h = NULL;
int server_changes = 0;
mutt_debug(3, "Handling FETCH\n");
if (mutt_str_atoui(s, &msn) < 0 || msn < 1 || msn > idata->max_msn)
{
mutt_debug(3, "#1 FETCH response ignored for this message\n");
return;
}
h = idata->msn_index[msn - 1];
if (!h || !h->active)
{
mutt_debug(3, "#2 FETCH response ignored for this message\n");
return;
}
mutt_debug(2, "Message UID %u updated\n", HEADER_DATA(h)->uid);
/* skip FETCH */
s = imap_next_word(s);
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Malformed FETCH response\n");
return;
}
s++;
while (*s)
{
SKIPWS(s);
if (mutt_str_strncasecmp("FLAGS", s, 5) == 0)
{
imap_set_flags(idata, h, s, &server_changes);
if (server_changes)
{
/* If server flags could conflict with neomutt's flags, reopen the mailbox. */
if (h->changed)
idata->reopen |= IMAP_EXPUNGE_PENDING;
else
idata->check_status = IMAP_FLAGS_PENDING;
}
return;
}
else if (mutt_str_strncasecmp("UID", s, 3) == 0)
{
s += 3;
SKIPWS(s);
if (mutt_str_atoui(s, &uid) < 0)
{
mutt_debug(2, "Illegal UID. Skipping update.\n");
return;
}
if (uid != HEADER_DATA(h)->uid)
{
mutt_debug(2, "FETCH UID vs MSN mismatch. Skipping update.\n");
return;
}
s = imap_next_word(s);
}
else if (*s == ')')
s++; /* end of request */
else if (*s)
{
mutt_debug(2, "Only handle FLAGS updates\n");
return;
}
}
}
/**
* cmd_parse_capability - set capability bits according to CAPABILITY response
* @param idata Server data
* @param s Command string with capabilities
*/
static void cmd_parse_capability(struct ImapData *idata, char *s)
{
mutt_debug(3, "Handling CAPABILITY\n");
s = imap_next_word(s);
char *bracket = strchr(s, ']');
if (bracket)
*bracket = '\0';
FREE(&idata->capstr);
idata->capstr = mutt_str_strdup(s);
memset(idata->capabilities, 0, sizeof(idata->capabilities));
while (*s)
{
for (int i = 0; i < CAPMAX; i++)
{
if (mutt_str_word_casecmp(Capabilities[i], s) == 0)
{
mutt_bit_set(idata->capabilities, i);
mutt_debug(4, " Found capability \"%s\": %d\n", Capabilities[i], i);
break;
}
}
s = imap_next_word(s);
}
}
/**
* cmd_parse_list - Parse a server LIST command (list mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_list(struct ImapData *idata, char *s)
{
struct ImapList *list = NULL;
struct ImapList lb;
char delimbuf[5]; /* worst case: "\\"\0 */
unsigned int litlen;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
list = (struct ImapList *) idata->cmddata;
else
list = &lb;
memset(list, 0, sizeof(struct ImapList));
/* flags */
s = imap_next_word(s);
if (*s != '(')
{
mutt_debug(1, "Bad LIST response\n");
return;
}
s++;
while (*s)
{
if (mutt_str_strncasecmp(s, "\\NoSelect", 9) == 0)
list->noselect = true;
else if (mutt_str_strncasecmp(s, "\\NoInferiors", 12) == 0)
list->noinferiors = true;
/* See draft-gahrns-imap-child-mailbox-?? */
else if (mutt_str_strncasecmp(s, "\\HasNoChildren", 14) == 0)
list->noinferiors = true;
s = imap_next_word(s);
if (*(s - 2) == ')')
break;
}
/* Delimiter */
if (mutt_str_strncasecmp(s, "NIL", 3) != 0)
{
delimbuf[0] = '\0';
mutt_str_strcat(delimbuf, 5, s);
imap_unquote_string(delimbuf);
list->delim = delimbuf[0];
}
/* Name */
s = imap_next_word(s);
/* Notes often responds with literals here. We need a real tokenizer. */
if (imap_get_literal_count(s, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
list->name = idata->buf;
}
else
{
imap_unmunge_mbox_name(idata, s);
list->name = s;
}
if (list->name[0] == '\0')
{
idata->delim = list->delim;
mutt_debug(3, "Root delimiter: %c\n", idata->delim);
}
}
/**
* cmd_parse_lsub - Parse a server LSUB (list subscribed mailboxes)
* @param idata Server data
* @param s Command string with folder list
*/
static void cmd_parse_lsub(struct ImapData *idata, char *s)
{
char buf[STRING];
char errstr[STRING];
struct Buffer err, token;
struct Url url;
struct ImapList list;
if (idata->cmddata && idata->cmdtype == IMAP_CT_LIST)
{
/* caller will handle response itself */
cmd_parse_list(idata, s);
return;
}
if (!ImapCheckSubscribed)
return;
idata->cmdtype = IMAP_CT_LIST;
idata->cmddata = &list;
cmd_parse_list(idata, s);
idata->cmddata = NULL;
/* noselect is for a gmail quirk (#3445) */
if (!list.name || list.noselect)
return;
mutt_debug(3, "Subscribing to %s\n", list.name);
mutt_str_strfcpy(buf, "mailboxes \"", sizeof(buf));
mutt_account_tourl(&idata->conn->account, &url);
/* escape \ and " */
imap_quote_string(errstr, sizeof(errstr), list.name, true);
url.path = errstr + 1;
url.path[strlen(url.path) - 1] = '\0';
if (mutt_str_strcmp(url.user, ImapUser) == 0)
url.user = NULL;
url_tostring(&url, buf + 11, sizeof(buf) - 11, 0);
mutt_str_strcat(buf, sizeof(buf), "\"");
mutt_buffer_init(&token);
mutt_buffer_init(&err);
err.data = errstr;
err.dsize = sizeof(errstr);
if (mutt_parse_rc_line(buf, &token, &err))
mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr);
FREE(&token.data);
}
/**
* cmd_parse_myrights - Set rights bits according to MYRIGHTS response
* @param idata Server data
* @param s Command string with rights info
*/
static void cmd_parse_myrights(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling MYRIGHTS\n");
s = imap_next_word((char *) s);
s = imap_next_word((char *) s);
/* zero out current rights set */
memset(idata->ctx->rights, 0, sizeof(idata->ctx->rights));
while (*s && !isspace((unsigned char) *s))
{
switch (*s)
{
case 'a':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_ADMIN);
break;
case 'e':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
case 'i':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_INSERT);
break;
case 'k':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
break;
case 'l':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_LOOKUP);
break;
case 'p':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_POST);
break;
case 'r':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_READ);
break;
case 's':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_SEEN);
break;
case 't':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
break;
case 'w':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_WRITE);
break;
case 'x':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
/* obsolete rights */
case 'c':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_CREATE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELMX);
break;
case 'd':
mutt_bit_set(idata->ctx->rights, MUTT_ACL_DELETE);
mutt_bit_set(idata->ctx->rights, MUTT_ACL_EXPUNGE);
break;
default:
mutt_debug(1, "Unknown right: %c\n", *s);
}
s++;
}
}
/**
* cmd_parse_search - store SEARCH response for later use
* @param idata Server data
* @param s Command string with search results
*/
static void cmd_parse_search(struct ImapData *idata, const char *s)
{
unsigned int uid;
struct Header *h = NULL;
mutt_debug(2, "Handling SEARCH\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if (mutt_str_atoui(s, &uid) < 0)
continue;
h = (struct Header *) mutt_hash_int_find(idata->uid_hash, uid);
if (h)
h->matched = true;
}
}
/**
* cmd_parse_status - Parse status from server
* @param idata Server data
* @param s Command string with status info
*
* first cut: just do buffy update. Later we may wish to cache all mailbox
* information, even that not desired by buffy
*/
static void cmd_parse_status(struct ImapData *idata, char *s)
{
char *value = NULL;
struct Buffy *inc = NULL;
struct ImapMbox mx;
struct ImapStatus *status = NULL;
unsigned int olduv, oldun;
unsigned int litlen;
short new = 0;
short new_msg_count = 0;
char *mailbox = imap_next_word(s);
/* We need a real tokenizer. */
if (imap_get_literal_count(mailbox, &litlen) == 0)
{
if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE)
{
idata->status = IMAP_FATAL;
return;
}
mailbox = idata->buf;
s = mailbox + litlen;
*s = '\0';
s++;
SKIPWS(s);
}
else
{
s = imap_next_word(mailbox);
*(s - 1) = '\0';
imap_unmunge_mbox_name(idata, mailbox);
}
status = imap_mboxcache_get(idata, mailbox, 1);
olduv = status->uidvalidity;
oldun = status->uidnext;
if (*s++ != '(')
{
mutt_debug(1, "Error parsing STATUS\n");
return;
}
while (*s && *s != ')')
{
value = imap_next_word(s);
errno = 0;
const unsigned long ulcount = strtoul(value, &value, 10);
if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount))
{
mutt_debug(1, "Error parsing STATUS number\n");
return;
}
const unsigned int count = (unsigned int) ulcount;
if (mutt_str_strncmp("MESSAGES", s, 8) == 0)
{
status->messages = count;
new_msg_count = 1;
}
else if (mutt_str_strncmp("RECENT", s, 6) == 0)
status->recent = count;
else if (mutt_str_strncmp("UIDNEXT", s, 7) == 0)
status->uidnext = count;
else if (mutt_str_strncmp("UIDVALIDITY", s, 11) == 0)
status->uidvalidity = count;
else if (mutt_str_strncmp("UNSEEN", s, 6) == 0)
status->unseen = count;
s = value;
if (*s && *s != ')')
s = imap_next_word(s);
}
mutt_debug(3, "%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n",
status->name, status->uidvalidity, status->uidnext,
status->messages, status->recent, status->unseen);
/* caller is prepared to handle the result herself */
if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS)
{
memcpy(idata->cmddata, status, sizeof(struct ImapStatus));
return;
}
mutt_debug(3, "Running default STATUS handler\n");
/* should perhaps move this code back to imap_buffy_check */
for (inc = Incoming; inc; inc = inc->next)
{
if (inc->magic != MUTT_IMAP)
continue;
if (imap_parse_path(inc->path, &mx) < 0)
{
mutt_debug(1, "Error parsing mailbox %s, skipping\n", inc->path);
continue;
}
if (imap_account_match(&idata->conn->account, &mx.account))
{
if (mx.mbox)
{
value = mutt_str_strdup(mx.mbox);
imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1);
FREE(&mx.mbox);
}
else
value = mutt_str_strdup("INBOX");
if (value && (imap_mxcmp(mailbox, value) == 0))
{
mutt_debug(3, "Found %s in buffy list (OV: %u ON: %u U: %d)\n", mailbox,
olduv, oldun, status->unseen);
if (MailCheckRecent)
{
if (olduv && olduv == status->uidvalidity)
{
if (oldun < status->uidnext)
new = (status->unseen > 0);
}
else if (!olduv && !oldun)
{
/* first check per session, use recent. might need a flag for this. */
new = (status->recent > 0);
}
else
new = (status->unseen > 0);
}
else
new = (status->unseen > 0);
#ifdef USE_SIDEBAR
if ((inc->new != new) || (inc->msg_count != status->messages) ||
(inc->msg_unread != status->unseen))
{
mutt_menu_set_current_redraw(REDRAW_SIDEBAR);
}
#endif
inc->new = new;
if (new_msg_count)
inc->msg_count = status->messages;
inc->msg_unread = status->unseen;
if (inc->new)
{
/* force back to keep detecting new mail until the mailbox is
opened */
status->uidnext = oldun;
}
FREE(&value);
return;
}
FREE(&value);
}
FREE(&mx.mbox);
}
}
/**
* cmd_parse_enabled - Record what the server has enabled
* @param idata Server data
* @param s Command string containing acceptable encodings
*/
static void cmd_parse_enabled(struct ImapData *idata, const char *s)
{
mutt_debug(2, "Handling ENABLED\n");
while ((s = imap_next_word((char *) s)) && *s != '\0')
{
if ((mutt_str_strncasecmp(s, "UTF8=ACCEPT", 11) == 0) ||
(mutt_str_strncasecmp(s, "UTF8=ONLY", 9) == 0))
{
idata->unicode = 1;
}
}
}
/**
* cmd_handle_untagged - fallback parser for otherwise unhandled messages
* @param idata Server data
* @retval 0 Success
* @retval -1 Failure
*/
static int cmd_handle_untagged(struct ImapData *idata)
{
unsigned int count = 0;
char *s = imap_next_word(idata->buf);
char *pn = imap_next_word(s);
if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s))
{
pn = s;
s = imap_next_word(s);
/* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the
* connection, so update that one.
*/
if (mutt_str_strncasecmp("EXISTS", s, 6) == 0)
{
mutt_debug(2, "Handling EXISTS\n");
/* new mail arrived */
if (mutt_str_atoui(pn, &count) < 0)
{
mutt_debug(1, "Malformed EXISTS: '%s'\n", pn);
}
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn)
{
/* Notes 6.0.3 has a tendency to report fewer messages exist than
* it should. */
mutt_debug(1, "Message count is out of sync\n");
return 0;
}
/* at least the InterChange server sends EXISTS messages freely,
* even when there is no new mail */
else if (count == idata->max_msn)
mutt_debug(3, "superfluous EXISTS message.\n");
else
{
if (!(idata->reopen & IMAP_EXPUNGE_PENDING))
{
mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count);
idata->reopen |= IMAP_NEWMAIL_PENDING;
}
idata->new_mail_count = count;
}
}
/* pn vs. s: need initial seqno */
else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0)
cmd_parse_expunge(idata, pn);
else if (mutt_str_strncasecmp("FETCH", s, 5) == 0)
cmd_parse_fetch(idata, pn);
}
else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0)
cmd_parse_capability(idata, s);
else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0)
cmd_parse_capability(idata, pn);
else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0)
cmd_parse_capability(idata, imap_next_word(pn));
else if (mutt_str_strncasecmp("LIST", s, 4) == 0)
cmd_parse_list(idata, s);
else if (mutt_str_strncasecmp("LSUB", s, 4) == 0)
cmd_parse_lsub(idata, s);
else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0)
cmd_parse_myrights(idata, s);
else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0)
cmd_parse_search(idata, s);
else if (mutt_str_strncasecmp("STATUS", s, 6) == 0)
cmd_parse_status(idata, s);
else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0)
cmd_parse_enabled(idata, s);
else if (mutt_str_strncasecmp("BYE", s, 3) == 0)
{
mutt_debug(2, "Handling BYE\n");
/* check if we're logging out */
if (idata->status == IMAP_BYE)
return 0;
/* server shut down our connection */
s += 3;
SKIPWS(s);
mutt_error("%s", s);
cmd_handle_fatal(idata);
return -1;
}
else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0))
{
mutt_debug(2, "Handling untagged NO\n");
/* Display the warning message from the server */
mutt_error("%s", s + 2);
}
return 0;
}
/**
* imap_cmd_start - Given an IMAP command, send it to the server
* @param idata Server data
* @param cmdstr Command string to send
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* If cmdstr is NULL, sends queued commands.
*/
int imap_cmd_start(struct ImapData *idata, const char *cmdstr)
{
return cmd_start(idata, cmdstr, 0);
}
/**
* imap_cmd_step - Reads server responses from an IMAP command
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*
* detects tagged completion response, handles untagged messages, can read
* arbitrarily large strings (using malloc, so don't make it _too_ large!).
*/
int imap_cmd_step(struct ImapData *idata)
{
size_t len = 0;
int c;
int rc;
int stillrunning = 0;
struct ImapCommand *cmd = NULL;
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
/* read into buffer, expanding buffer as necessary until we have a full
* line */
do
{
if (len == idata->blen)
{
mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE);
idata->blen = idata->blen + IMAP_CMD_BUFSIZE;
mutt_debug(3, "grew buffer to %u bytes\n", idata->blen);
}
/* back up over '\0' */
if (len)
len--;
c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn);
if (c <= 0)
{
mutt_debug(1, "Error reading server response.\n");
cmd_handle_fatal(idata);
return IMAP_CMD_BAD;
}
len += c;
}
/* if we've read all the way to the end of the buffer, we haven't read a
* full line (mutt_socket_readln strips the \r, so we always have at least
* one character free when we've read a full line) */
while (len == idata->blen);
/* don't let one large string make cmd->buf hog memory forever */
if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE))
{
mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE);
idata->blen = IMAP_CMD_BUFSIZE;
mutt_debug(3, "shrank buffer to %u bytes\n", idata->blen);
}
idata->lastread = time(NULL);
/* handle untagged messages. The caller still gets its shot afterwards. */
if (((mutt_str_strncmp(idata->buf, "* ", 2) == 0) ||
(mutt_str_strncmp(imap_next_word(idata->buf), "OK [", 4) == 0)) &&
cmd_handle_untagged(idata))
{
return IMAP_CMD_BAD;
}
/* server demands a continuation response from us */
if (idata->buf[0] == '+')
return IMAP_CMD_RESPOND;
/* Look for tagged command completions.
*
* Some response handlers can end up recursively calling
* imap_cmd_step() and end up handling all tagged command
* completions.
* (e.g. FETCH->set_flag->set_header_color->~h pattern match.)
*
* Other callers don't even create an idata->cmds entry.
*
* For both these cases, we default to returning OK */
rc = IMAP_CMD_OK;
c = idata->lastcmd;
do
{
cmd = &idata->cmds[c];
if (cmd->state == IMAP_CMD_NEW)
{
if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0)
{
if (!stillrunning)
{
/* first command in queue has finished - move queue pointer up */
idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots;
}
cmd->state = cmd_status(idata->buf);
/* bogus - we don't know which command result to return here. Caller
* should provide a tag. */
rc = cmd->state;
}
else
stillrunning++;
}
c = (c + 1) % idata->cmdslots;
} while (c != idata->nextcmd);
if (stillrunning)
rc = IMAP_CMD_CONTINUE;
else
{
mutt_debug(3, "IMAP queue drained\n");
imap_cmd_finish(idata);
}
return rc;
}
/**
* imap_code - Was the command successful
* @param s IMAP command status
* @retval 1 Command result was OK
* @retval 0 If NO or BAD
*/
bool imap_code(const char *s)
{
return (cmd_status(s) == IMAP_CMD_OK);
}
/**
* imap_cmd_trailer - Extra information after tagged command response if any
* @param idata Server data
* @retval ptr Extra command information (pointer into idata->buf)
* @retval "" Error (static string)
*/
const char *imap_cmd_trailer(struct ImapData *idata)
{
static const char *notrailer = "";
const char *s = idata->buf;
if (!s)
{
mutt_debug(2, "not a tagged response\n");
return notrailer;
}
s = imap_next_word((char *) s);
if (!s || ((mutt_str_strncasecmp(s, "OK", 2) != 0) &&
(mutt_str_strncasecmp(s, "NO", 2) != 0) &&
(mutt_str_strncasecmp(s, "BAD", 3) != 0)))
{
mutt_debug(2, "not a command completion: %s\n", idata->buf);
return notrailer;
}
s = imap_next_word((char *) s);
if (!s)
return notrailer;
return s;
}
/**
* imap_exec - Execute a command and wait for the response from the server
* @param idata IMAP data
* @param cmdstr Command to execute
* @param flags Flags (see below)
* @retval 0 Success
* @retval -1 Failure
* @retval -2 OK Failure
*
* Also, handle untagged responses.
*
* Flags:
* * IMAP_CMD_FAIL_OK: the calling procedure can handle failure.
* This is used for checking for a mailbox on append and login
* * IMAP_CMD_PASS: command contains a password. Suppress logging.
* * IMAP_CMD_QUEUE: only queue command, do not execute.
* * IMAP_CMD_POLL: poll the socket for a response before running imap_cmd_step.
*/
int imap_exec(struct ImapData *idata, const char *cmdstr, int flags)
{
int rc;
rc = cmd_start(idata, cmdstr, flags);
if (rc < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if (flags & IMAP_CMD_QUEUE)
return 0;
if ((flags & IMAP_CMD_POLL) && (ImapPollTimeout > 0) &&
(mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
/* Allow interruptions, particularly useful if there are network problems. */
mutt_sig_allow_interrupt(1);
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
mutt_sig_allow_interrupt(0);
if (rc == IMAP_CMD_NO && (flags & IMAP_CMD_FAIL_OK))
return -2;
if (rc != IMAP_CMD_OK)
{
if ((flags & IMAP_CMD_FAIL_OK) && idata->status != IMAP_FATAL)
return -2;
mutt_debug(1, "command failed: %s\n", idata->buf);
return -1;
}
return 0;
}
/**
* imap_cmd_finish - Attempt to perform cleanup
* @param idata Server data
*
* Attempts to perform cleanup (eg fetch new mail if detected, do expunge).
* Called automatically by imap_cmd_step(), but may be called at any time.
* Called by imap_check_mailbox() just before the index is refreshed, for
* instance.
*/
void imap_cmd_finish(struct ImapData *idata)
{
if (idata->status == IMAP_FATAL)
{
cmd_handle_fatal(idata);
return;
}
if (!(idata->state >= IMAP_SELECTED) || idata->ctx->closing)
return;
if (idata->reopen & IMAP_REOPEN_ALLOW)
{
unsigned int count = idata->new_mail_count;
if (!(idata->reopen & IMAP_EXPUNGE_PENDING) &&
(idata->reopen & IMAP_NEWMAIL_PENDING) && count > idata->max_msn)
{
/* read new mail messages */
mutt_debug(2, "Fetching new mail\n");
/* check_status: curs_main uses imap_check_mailbox to detect
* whether the index needs updating */
idata->check_status = IMAP_NEWMAIL_PENDING;
imap_read_headers(idata, idata->max_msn + 1, count);
}
else if (idata->reopen & IMAP_EXPUNGE_PENDING)
{
mutt_debug(2, "Expunging mailbox\n");
imap_expunge_mailbox(idata);
/* Detect whether we've gotten unexpected EXPUNGE messages */
if ((idata->reopen & IMAP_EXPUNGE_PENDING) && !(idata->reopen & IMAP_EXPUNGE_EXPECTED))
idata->check_status = IMAP_EXPUNGE_PENDING;
idata->reopen &=
~(IMAP_EXPUNGE_PENDING | IMAP_NEWMAIL_PENDING | IMAP_EXPUNGE_EXPECTED);
}
}
idata->status = false;
}
/**
* imap_cmd_idle - Enter the IDLE state
* @param idata Server data
* @retval 0 Success
* @retval <0 Failure, e.g. #IMAP_CMD_BAD
*/
int imap_cmd_idle(struct ImapData *idata)
{
int rc;
if (cmd_start(idata, "IDLE", IMAP_CMD_POLL) < 0)
{
cmd_handle_fatal(idata);
return -1;
}
if ((ImapPollTimeout > 0) && (mutt_socket_poll(idata->conn, ImapPollTimeout)) == 0)
{
mutt_error(_("Connection to %s timed out"), idata->conn->account.host);
cmd_handle_fatal(idata);
return -1;
}
do
rc = imap_cmd_step(idata);
while (rc == IMAP_CMD_CONTINUE);
if (rc == IMAP_CMD_RESPOND)
{
/* successfully entered IDLE state */
idata->state = IMAP_IDLE;
/* queue automatic exit when next command is issued */
mutt_buffer_printf(idata->cmdbuf, "DONE\r\n");
rc = IMAP_CMD_OK;
}
if (rc != IMAP_CMD_OK)
{
mutt_debug(1, "error starting IDLE\n");
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_245_0 |
crossvul-cpp_data_good_3988_1 | #include "clar_libgit2.h"
#include "path.h"
static char *gitmodules_altnames[] = {
".gitmodules",
/*
* Equivalent to the ".git\u200cmodules" string from git but hard-coded
* as a UTF-8 sequence
*/
".git\xe2\x80\x8cmodules",
".Gitmodules",
".gitmoduleS",
".gitmodules ",
".gitmodules.",
".gitmodules ",
".gitmodules. ",
".gitmodules .",
".gitmodules..",
".gitmodules ",
".gitmodules. ",
".gitmodules . ",
".gitmodules .",
".Gitmodules ",
".Gitmodules.",
".Gitmodules ",
".Gitmodules. ",
".Gitmodules .",
".Gitmodules..",
".Gitmodules ",
".Gitmodules. ",
".Gitmodules . ",
".Gitmodules .",
"GITMOD~1",
"gitmod~1",
"GITMOD~2",
"gitmod~3",
"GITMOD~4",
"GITMOD~1 ",
"gitmod~2.",
"GITMOD~3 ",
"gitmod~4. ",
"GITMOD~1 .",
"gitmod~2 ",
"GITMOD~3. ",
"gitmod~4 . ",
"GI7EBA~1",
"gi7eba~9",
"GI7EB~10",
"GI7EB~11",
"GI7EB~99",
"GI7EB~10",
"GI7E~100",
"GI7E~101",
"GI7E~999",
"~1000000",
"~9999999",
};
static char *gitmodules_not_altnames[] = {
".gitmodules x",
".gitmodules .x",
" .gitmodules",
"..gitmodules",
"gitmodules",
".gitmodule",
".gitmodules x ",
".gitmodules .x",
"GI7EBA~",
"GI7EBA~0",
"GI7EBA~~1",
"GI7EBA~X",
"Gx7EBA~1",
"GI7EBX~1",
"GI7EB~1",
"GI7EB~01",
"GI7EB~1",
};
void test_path_dotgit__dotgit_modules(void)
{
size_t i;
cl_assert_equal_i(1, git_path_is_gitfile(".gitmodules", strlen(".gitmodules"), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC));
cl_assert_equal_i(1, git_path_is_gitfile(".git\xe2\x80\x8cmodules", strlen(".git\xe2\x80\x8cmodules"), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC));
for (i = 0; i < ARRAY_SIZE(gitmodules_altnames); i++) {
const char *name = gitmodules_altnames[i];
if (!git_path_is_gitfile(name, strlen(name), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC))
cl_fail(name);
}
for (i = 0; i < ARRAY_SIZE(gitmodules_not_altnames); i++) {
const char *name = gitmodules_not_altnames[i];
if (git_path_is_gitfile(name, strlen(name), GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_GENERIC))
cl_fail(name);
}
}
void test_path_dotgit__dotgit_modules_symlink(void)
{
cl_assert_equal_b(true, git_path_isvalid(NULL, ".gitmodules", 0, GIT_PATH_REJECT_DOT_GIT_HFS|GIT_PATH_REJECT_DOT_GIT_NTFS));
cl_assert_equal_b(false, git_path_isvalid(NULL, ".gitmodules", S_IFLNK, GIT_PATH_REJECT_DOT_GIT_HFS));
cl_assert_equal_b(false, git_path_isvalid(NULL, ".gitmodules", S_IFLNK, GIT_PATH_REJECT_DOT_GIT_NTFS));
cl_assert_equal_b(false, git_path_isvalid(NULL, ".gitmodules . .::$DATA", S_IFLNK, GIT_PATH_REJECT_DOT_GIT_NTFS));
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3988_1 |
crossvul-cpp_data_good_5845_3 | /** -*- linux-c -*- ***********************************************************
* Linux PPP over Ethernet (PPPoX/PPPoE) Sockets
*
* PPPoX --- Generic PPP encapsulation socket family
* PPPoE --- PPP over Ethernet (RFC 2516)
*
*
* Version: 0.7.0
*
* 070228 : Fix to allow multiple sessions with same remote MAC and same
* session id by including the local device ifindex in the
* tuple identifying a session. This also ensures packets can't
* be injected into a session from interfaces other than the one
* specified by userspace. Florian Zumbiehl <florz@florz.de>
* (Oh, BTW, this one is YYMMDD, in case you were wondering ...)
* 220102 : Fix module use count on failure in pppoe_create, pppox_sk -acme
* 030700 : Fixed connect logic to allow for disconnect.
* 270700 : Fixed potential SMP problems; we must protect against
* simultaneous invocation of ppp_input
* and ppp_unregister_channel.
* 040800 : Respect reference count mechanisms on net-devices.
* 200800 : fix kfree(skb) in pppoe_rcv (acme)
* Module reference count is decremented in the right spot now,
* guards against sock_put not actually freeing the sk
* in pppoe_release.
* 051000 : Initialization cleanup.
* 111100 : Fix recvmsg.
* 050101 : Fix PADT procesing.
* 140501 : Use pppoe_rcv_core to handle all backlog. (Alexey)
* 170701 : Do not lock_sock with rwlock held. (DaveM)
* Ignore discovery frames if user has socket
* locked. (DaveM)
* Ignore return value of dev_queue_xmit in __pppoe_xmit
* or else we may kfree an SKB twice. (DaveM)
* 190701 : When doing copies of skb's in __pppoe_xmit, always delete
* the original skb that was passed in on success, never on
* failure. Delete the copy of the skb on failure to avoid
* a memory leak.
* 081001 : Misc. cleanup (licence string, non-blocking, prevent
* reference of device on close).
* 121301 : New ppp channels interface; cannot unregister a channel
* from interrupts. Thus, we mark the socket as a ZOMBIE
* and do the unregistration later.
* 081002 : seq_file support for proc stuff -acme
* 111602 : Merge all 2.4 fixes into 2.5/2.6 tree. Label 2.5/2.6
* as version 0.7. Spacing cleanup.
* Author: Michal Ostrowski <mostrows@speakeasy.net>
* Contributors:
* Arnaldo Carvalho de Melo <acme@conectiva.com.br>
* David S. Miller (davem@redhat.com)
*
* License:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <linux/string.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/netdevice.h>
#include <linux/net.h>
#include <linux/inetdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/if_ether.h>
#include <linux/if_pppox.h>
#include <linux/ppp_channel.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/notifier.h>
#include <linux/file.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/nsproxy.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#define PPPOE_HASH_BITS 4
#define PPPOE_HASH_SIZE (1 << PPPOE_HASH_BITS)
#define PPPOE_HASH_MASK (PPPOE_HASH_SIZE - 1)
static int __pppoe_xmit(struct sock *sk, struct sk_buff *skb);
static const struct proto_ops pppoe_ops;
static const struct ppp_channel_ops pppoe_chan_ops;
/* per-net private data for this module */
static int pppoe_net_id __read_mostly;
struct pppoe_net {
/*
* we could use _single_ hash table for all
* nets by injecting net id into the hash but
* it would increase hash chains and add
* a few additional math comparations messy
* as well, moreover in case of SMP less locking
* controversy here
*/
struct pppox_sock *hash_table[PPPOE_HASH_SIZE];
rwlock_t hash_lock;
};
/*
* PPPoE could be in the following stages:
* 1) Discovery stage (to obtain remote MAC and Session ID)
* 2) Session stage (MAC and SID are known)
*
* Ethernet frames have a special tag for this but
* we use simpler approach based on session id
*/
static inline bool stage_session(__be16 sid)
{
return sid != 0;
}
static inline struct pppoe_net *pppoe_pernet(struct net *net)
{
BUG_ON(!net);
return net_generic(net, pppoe_net_id);
}
static inline int cmp_2_addr(struct pppoe_addr *a, struct pppoe_addr *b)
{
return a->sid == b->sid && !memcmp(a->remote, b->remote, ETH_ALEN);
}
static inline int cmp_addr(struct pppoe_addr *a, __be16 sid, char *addr)
{
return a->sid == sid && !memcmp(a->remote, addr, ETH_ALEN);
}
#if 8 % PPPOE_HASH_BITS
#error 8 must be a multiple of PPPOE_HASH_BITS
#endif
static int hash_item(__be16 sid, unsigned char *addr)
{
unsigned char hash = 0;
unsigned int i;
for (i = 0; i < ETH_ALEN; i++)
hash ^= addr[i];
for (i = 0; i < sizeof(sid_t) * 8; i += 8)
hash ^= (__force __u32)sid >> i;
for (i = 8; (i >>= 1) >= PPPOE_HASH_BITS;)
hash ^= hash >> i;
return hash & PPPOE_HASH_MASK;
}
/**********************************************************************
*
* Set/get/delete/rehash items (internal versions)
*
**********************************************************************/
static struct pppox_sock *__get_item(struct pppoe_net *pn, __be16 sid,
unsigned char *addr, int ifindex)
{
int hash = hash_item(sid, addr);
struct pppox_sock *ret;
ret = pn->hash_table[hash];
while (ret) {
if (cmp_addr(&ret->pppoe_pa, sid, addr) &&
ret->pppoe_ifindex == ifindex)
return ret;
ret = ret->next;
}
return NULL;
}
static int __set_item(struct pppoe_net *pn, struct pppox_sock *po)
{
int hash = hash_item(po->pppoe_pa.sid, po->pppoe_pa.remote);
struct pppox_sock *ret;
ret = pn->hash_table[hash];
while (ret) {
if (cmp_2_addr(&ret->pppoe_pa, &po->pppoe_pa) &&
ret->pppoe_ifindex == po->pppoe_ifindex)
return -EALREADY;
ret = ret->next;
}
po->next = pn->hash_table[hash];
pn->hash_table[hash] = po;
return 0;
}
static void __delete_item(struct pppoe_net *pn, __be16 sid,
char *addr, int ifindex)
{
int hash = hash_item(sid, addr);
struct pppox_sock *ret, **src;
ret = pn->hash_table[hash];
src = &pn->hash_table[hash];
while (ret) {
if (cmp_addr(&ret->pppoe_pa, sid, addr) &&
ret->pppoe_ifindex == ifindex) {
*src = ret->next;
break;
}
src = &ret->next;
ret = ret->next;
}
}
/**********************************************************************
*
* Set/get/delete/rehash items
*
**********************************************************************/
static inline struct pppox_sock *get_item(struct pppoe_net *pn, __be16 sid,
unsigned char *addr, int ifindex)
{
struct pppox_sock *po;
read_lock_bh(&pn->hash_lock);
po = __get_item(pn, sid, addr, ifindex);
if (po)
sock_hold(sk_pppox(po));
read_unlock_bh(&pn->hash_lock);
return po;
}
static inline struct pppox_sock *get_item_by_addr(struct net *net,
struct sockaddr_pppox *sp)
{
struct net_device *dev;
struct pppoe_net *pn;
struct pppox_sock *pppox_sock = NULL;
int ifindex;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, sp->sa_addr.pppoe.dev);
if (dev) {
ifindex = dev->ifindex;
pn = pppoe_pernet(net);
pppox_sock = get_item(pn, sp->sa_addr.pppoe.sid,
sp->sa_addr.pppoe.remote, ifindex);
}
rcu_read_unlock();
return pppox_sock;
}
static inline void delete_item(struct pppoe_net *pn, __be16 sid,
char *addr, int ifindex)
{
write_lock_bh(&pn->hash_lock);
__delete_item(pn, sid, addr, ifindex);
write_unlock_bh(&pn->hash_lock);
}
/***************************************************************************
*
* Handler for device events.
* Certain device events require that sockets be unconnected.
*
**************************************************************************/
static void pppoe_flush_dev(struct net_device *dev)
{
struct pppoe_net *pn;
int i;
pn = pppoe_pernet(dev_net(dev));
write_lock_bh(&pn->hash_lock);
for (i = 0; i < PPPOE_HASH_SIZE; i++) {
struct pppox_sock *po = pn->hash_table[i];
struct sock *sk;
while (po) {
while (po && po->pppoe_dev != dev) {
po = po->next;
}
if (!po)
break;
sk = sk_pppox(po);
/* We always grab the socket lock, followed by the
* hash_lock, in that order. Since we should hold the
* sock lock while doing any unbinding, we need to
* release the lock we're holding. Hold a reference to
* the sock so it doesn't disappear as we're jumping
* between locks.
*/
sock_hold(sk);
write_unlock_bh(&pn->hash_lock);
lock_sock(sk);
if (po->pppoe_dev == dev &&
sk->sk_state & (PPPOX_CONNECTED | PPPOX_BOUND | PPPOX_ZOMBIE)) {
pppox_unbind_sock(sk);
sk->sk_state = PPPOX_ZOMBIE;
sk->sk_state_change(sk);
po->pppoe_dev = NULL;
dev_put(dev);
}
release_sock(sk);
sock_put(sk);
/* Restart the process from the start of the current
* hash chain. We dropped locks so the world may have
* change from underneath us.
*/
BUG_ON(pppoe_pernet(dev_net(dev)) == NULL);
write_lock_bh(&pn->hash_lock);
po = pn->hash_table[i];
}
}
write_unlock_bh(&pn->hash_lock);
}
static int pppoe_device_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
/* Only look at sockets that are using this specific device. */
switch (event) {
case NETDEV_CHANGEADDR:
case NETDEV_CHANGEMTU:
/* A change in mtu or address is a bad thing, requiring
* LCP re-negotiation.
*/
case NETDEV_GOING_DOWN:
case NETDEV_DOWN:
/* Find every socket on this device and kill it. */
pppoe_flush_dev(dev);
break;
default:
break;
}
return NOTIFY_DONE;
}
static struct notifier_block pppoe_notifier = {
.notifier_call = pppoe_device_event,
};
/************************************************************************
*
* Do the real work of receiving a PPPoE Session frame.
*
***********************************************************************/
static int pppoe_rcv_core(struct sock *sk, struct sk_buff *skb)
{
struct pppox_sock *po = pppox_sk(sk);
struct pppox_sock *relay_po;
/* Backlog receive. Semantics of backlog rcv preclude any code from
* executing in lock_sock()/release_sock() bounds; meaning sk->sk_state
* can't change.
*/
if (sk->sk_state & PPPOX_BOUND) {
ppp_input(&po->chan, skb);
} else if (sk->sk_state & PPPOX_RELAY) {
relay_po = get_item_by_addr(sock_net(sk),
&po->pppoe_relay);
if (relay_po == NULL)
goto abort_kfree;
if ((sk_pppox(relay_po)->sk_state & PPPOX_CONNECTED) == 0)
goto abort_put;
if (!__pppoe_xmit(sk_pppox(relay_po), skb))
goto abort_put;
} else {
if (sock_queue_rcv_skb(sk, skb))
goto abort_kfree;
}
return NET_RX_SUCCESS;
abort_put:
sock_put(sk_pppox(relay_po));
abort_kfree:
kfree_skb(skb);
return NET_RX_DROP;
}
/************************************************************************
*
* Receive wrapper called in BH context.
*
***********************************************************************/
static int pppoe_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct pppoe_hdr *ph;
struct pppox_sock *po;
struct pppoe_net *pn;
int len;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
goto out;
if (!pskb_may_pull(skb, sizeof(struct pppoe_hdr)))
goto drop;
ph = pppoe_hdr(skb);
len = ntohs(ph->length);
skb_pull_rcsum(skb, sizeof(*ph));
if (skb->len < len)
goto drop;
if (pskb_trim_rcsum(skb, len))
goto drop;
pn = pppoe_pernet(dev_net(dev));
/* Note that get_item does a sock_hold(), so sk_pppox(po)
* is known to be safe.
*/
po = get_item(pn, ph->sid, eth_hdr(skb)->h_source, dev->ifindex);
if (!po)
goto drop;
return sk_receive_skb(sk_pppox(po), skb, 0);
drop:
kfree_skb(skb);
out:
return NET_RX_DROP;
}
/************************************************************************
*
* Receive a PPPoE Discovery frame.
* This is solely for detection of PADT frames
*
***********************************************************************/
static int pppoe_disc_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct pppoe_hdr *ph;
struct pppox_sock *po;
struct pppoe_net *pn;
skb = skb_share_check(skb, GFP_ATOMIC);
if (!skb)
goto out;
if (!pskb_may_pull(skb, sizeof(struct pppoe_hdr)))
goto abort;
ph = pppoe_hdr(skb);
if (ph->code != PADT_CODE)
goto abort;
pn = pppoe_pernet(dev_net(dev));
po = get_item(pn, ph->sid, eth_hdr(skb)->h_source, dev->ifindex);
if (po) {
struct sock *sk = sk_pppox(po);
bh_lock_sock(sk);
/* If the user has locked the socket, just ignore
* the packet. With the way two rcv protocols hook into
* one socket family type, we cannot (easily) distinguish
* what kind of SKB it is during backlog rcv.
*/
if (sock_owned_by_user(sk) == 0) {
/* We're no longer connect at the PPPOE layer,
* and must wait for ppp channel to disconnect us.
*/
sk->sk_state = PPPOX_ZOMBIE;
}
bh_unlock_sock(sk);
sock_put(sk);
}
abort:
kfree_skb(skb);
out:
return NET_RX_SUCCESS; /* Lies... :-) */
}
static struct packet_type pppoes_ptype __read_mostly = {
.type = cpu_to_be16(ETH_P_PPP_SES),
.func = pppoe_rcv,
};
static struct packet_type pppoed_ptype __read_mostly = {
.type = cpu_to_be16(ETH_P_PPP_DISC),
.func = pppoe_disc_rcv,
};
static struct proto pppoe_sk_proto __read_mostly = {
.name = "PPPOE",
.owner = THIS_MODULE,
.obj_size = sizeof(struct pppox_sock),
};
/***********************************************************************
*
* Initialize a new struct sock.
*
**********************************************************************/
static int pppoe_create(struct net *net, struct socket *sock)
{
struct sock *sk;
sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pppoe_sk_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->state = SS_UNCONNECTED;
sock->ops = &pppoe_ops;
sk->sk_backlog_rcv = pppoe_rcv_core;
sk->sk_state = PPPOX_NONE;
sk->sk_type = SOCK_STREAM;
sk->sk_family = PF_PPPOX;
sk->sk_protocol = PX_PROTO_OE;
return 0;
}
static int pppoe_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct pppox_sock *po;
struct pppoe_net *pn;
struct net *net = NULL;
if (!sk)
return 0;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD)) {
release_sock(sk);
return -EBADF;
}
po = pppox_sk(sk);
if (sk->sk_state & (PPPOX_CONNECTED | PPPOX_BOUND | PPPOX_ZOMBIE)) {
dev_put(po->pppoe_dev);
po->pppoe_dev = NULL;
}
pppox_unbind_sock(sk);
/* Signal the death of the socket. */
sk->sk_state = PPPOX_DEAD;
net = sock_net(sk);
pn = pppoe_pernet(net);
/*
* protect "po" from concurrent updates
* on pppoe_flush_dev
*/
delete_item(pn, po->pppoe_pa.sid, po->pppoe_pa.remote,
po->pppoe_ifindex);
sock_orphan(sk);
sock->sk = NULL;
skb_queue_purge(&sk->sk_receive_queue);
release_sock(sk);
sock_put(sk);
return 0;
}
static int pppoe_connect(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_pppox *sp = (struct sockaddr_pppox *)uservaddr;
struct pppox_sock *po = pppox_sk(sk);
struct net_device *dev = NULL;
struct pppoe_net *pn;
struct net *net = NULL;
int error;
lock_sock(sk);
error = -EINVAL;
if (sp->sa_protocol != PX_PROTO_OE)
goto end;
/* Check for already bound sockets */
error = -EBUSY;
if ((sk->sk_state & PPPOX_CONNECTED) &&
stage_session(sp->sa_addr.pppoe.sid))
goto end;
/* Check for already disconnected sockets, on attempts to disconnect */
error = -EALREADY;
if ((sk->sk_state & PPPOX_DEAD) &&
!stage_session(sp->sa_addr.pppoe.sid))
goto end;
error = 0;
/* Delete the old binding */
if (stage_session(po->pppoe_pa.sid)) {
pppox_unbind_sock(sk);
pn = pppoe_pernet(sock_net(sk));
delete_item(pn, po->pppoe_pa.sid,
po->pppoe_pa.remote, po->pppoe_ifindex);
if (po->pppoe_dev) {
dev_put(po->pppoe_dev);
po->pppoe_dev = NULL;
}
memset(sk_pppox(po) + 1, 0,
sizeof(struct pppox_sock) - sizeof(struct sock));
sk->sk_state = PPPOX_NONE;
}
/* Re-bind in session stage only */
if (stage_session(sp->sa_addr.pppoe.sid)) {
error = -ENODEV;
net = sock_net(sk);
dev = dev_get_by_name(net, sp->sa_addr.pppoe.dev);
if (!dev)
goto err_put;
po->pppoe_dev = dev;
po->pppoe_ifindex = dev->ifindex;
pn = pppoe_pernet(net);
if (!(dev->flags & IFF_UP)) {
goto err_put;
}
memcpy(&po->pppoe_pa,
&sp->sa_addr.pppoe,
sizeof(struct pppoe_addr));
write_lock_bh(&pn->hash_lock);
error = __set_item(pn, po);
write_unlock_bh(&pn->hash_lock);
if (error < 0)
goto err_put;
po->chan.hdrlen = (sizeof(struct pppoe_hdr) +
dev->hard_header_len);
po->chan.mtu = dev->mtu - sizeof(struct pppoe_hdr);
po->chan.private = sk;
po->chan.ops = &pppoe_chan_ops;
error = ppp_register_net_channel(dev_net(dev), &po->chan);
if (error) {
delete_item(pn, po->pppoe_pa.sid,
po->pppoe_pa.remote, po->pppoe_ifindex);
goto err_put;
}
sk->sk_state = PPPOX_CONNECTED;
}
po->num = sp->sa_addr.pppoe.sid;
end:
release_sock(sk);
return error;
err_put:
if (po->pppoe_dev) {
dev_put(po->pppoe_dev);
po->pppoe_dev = NULL;
}
goto end;
}
static int pppoe_getname(struct socket *sock, struct sockaddr *uaddr,
int *usockaddr_len, int peer)
{
int len = sizeof(struct sockaddr_pppox);
struct sockaddr_pppox sp;
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OE;
memcpy(&sp.sa_addr.pppoe, &pppox_sk(sock->sk)->pppoe_pa,
sizeof(struct pppoe_addr));
memcpy(uaddr, &sp, len);
*usockaddr_len = len;
return 0;
}
static int pppoe_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
struct pppox_sock *po = pppox_sk(sk);
int val;
int err;
switch (cmd) {
case PPPIOCGMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (put_user(po->pppoe_dev->mtu -
sizeof(struct pppoe_hdr) -
PPP_HDRLEN,
(int __user *)arg))
break;
err = 0;
break;
case PPPIOCSMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (get_user(val, (int __user *)arg))
break;
if (val < (po->pppoe_dev->mtu
- sizeof(struct pppoe_hdr)
- PPP_HDRLEN))
err = 0;
else
err = -EINVAL;
break;
case PPPIOCSFLAGS:
err = -EFAULT;
if (get_user(val, (int __user *)arg))
break;
err = 0;
break;
case PPPOEIOCSFWD:
{
struct pppox_sock *relay_po;
err = -EBUSY;
if (sk->sk_state & (PPPOX_BOUND | PPPOX_ZOMBIE | PPPOX_DEAD))
break;
err = -ENOTCONN;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
/* PPPoE address from the user specifies an outbound
PPPoE address which frames are forwarded to */
err = -EFAULT;
if (copy_from_user(&po->pppoe_relay,
(void __user *)arg,
sizeof(struct sockaddr_pppox)))
break;
err = -EINVAL;
if (po->pppoe_relay.sa_family != AF_PPPOX ||
po->pppoe_relay.sa_protocol != PX_PROTO_OE)
break;
/* Check that the socket referenced by the address
actually exists. */
relay_po = get_item_by_addr(sock_net(sk), &po->pppoe_relay);
if (!relay_po)
break;
sock_put(sk_pppox(relay_po));
sk->sk_state |= PPPOX_RELAY;
err = 0;
break;
}
case PPPOEIOCDFWD:
err = -EALREADY;
if (!(sk->sk_state & PPPOX_RELAY))
break;
sk->sk_state &= ~PPPOX_RELAY;
err = 0;
break;
default:
err = -ENOTTY;
}
return err;
}
static int pppoe_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len)
{
struct sk_buff *skb;
struct sock *sk = sock->sk;
struct pppox_sock *po = pppox_sk(sk);
int error;
struct pppoe_hdr hdr;
struct pppoe_hdr *ph;
struct net_device *dev;
char *start;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED)) {
error = -ENOTCONN;
goto end;
}
hdr.ver = 1;
hdr.type = 1;
hdr.code = 0;
hdr.sid = po->num;
dev = po->pppoe_dev;
error = -EMSGSIZE;
if (total_len > (dev->mtu + dev->hard_header_len))
goto end;
skb = sock_wmalloc(sk, total_len + dev->hard_header_len + 32,
0, GFP_KERNEL);
if (!skb) {
error = -ENOMEM;
goto end;
}
/* Reserve space for headers. */
skb_reserve(skb, dev->hard_header_len);
skb_reset_network_header(skb);
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->protocol = cpu_to_be16(ETH_P_PPP_SES);
ph = (struct pppoe_hdr *)skb_put(skb, total_len + sizeof(struct pppoe_hdr));
start = (char *)&ph->tag[0];
error = memcpy_fromiovec(start, m->msg_iov, total_len);
if (error < 0) {
kfree_skb(skb);
goto end;
}
error = total_len;
dev_hard_header(skb, dev, ETH_P_PPP_SES,
po->pppoe_pa.remote, NULL, total_len);
memcpy(ph, &hdr, sizeof(struct pppoe_hdr));
ph->length = htons(total_len);
dev_queue_xmit(skb);
end:
release_sock(sk);
return error;
}
/************************************************************************
*
* xmit function for internal use.
*
***********************************************************************/
static int __pppoe_xmit(struct sock *sk, struct sk_buff *skb)
{
struct pppox_sock *po = pppox_sk(sk);
struct net_device *dev = po->pppoe_dev;
struct pppoe_hdr *ph;
int data_len = skb->len;
/* The higher-level PPP code (ppp_unregister_channel()) ensures the PPP
* xmit operations conclude prior to an unregistration call. Thus
* sk->sk_state cannot change, so we don't need to do lock_sock().
* But, we also can't do a lock_sock since that introduces a potential
* deadlock as we'd reverse the lock ordering used when calling
* ppp_unregister_channel().
*/
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto abort;
if (!dev)
goto abort;
/* Copy the data if there is no space for the header or if it's
* read-only.
*/
if (skb_cow_head(skb, sizeof(*ph) + dev->hard_header_len))
goto abort;
__skb_push(skb, sizeof(*ph));
skb_reset_network_header(skb);
ph = pppoe_hdr(skb);
ph->ver = 1;
ph->type = 1;
ph->code = 0;
ph->sid = po->num;
ph->length = htons(data_len);
skb->protocol = cpu_to_be16(ETH_P_PPP_SES);
skb->dev = dev;
dev_hard_header(skb, dev, ETH_P_PPP_SES,
po->pppoe_pa.remote, NULL, data_len);
dev_queue_xmit(skb);
return 1;
abort:
kfree_skb(skb);
return 1;
}
/************************************************************************
*
* xmit function called by generic PPP driver
* sends PPP frame over PPPoE socket
*
***********************************************************************/
static int pppoe_xmit(struct ppp_channel *chan, struct sk_buff *skb)
{
struct sock *sk = (struct sock *)chan->private;
return __pppoe_xmit(sk, skb);
}
static const struct ppp_channel_ops pppoe_chan_ops = {
.start_xmit = pppoe_xmit,
};
static int pppoe_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *m, size_t total_len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int error = 0;
if (sk->sk_state & PPPOX_BOUND) {
error = -EIO;
goto end;
}
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &error);
if (error < 0)
goto end;
if (skb) {
total_len = min_t(size_t, total_len, skb->len);
error = skb_copy_datagram_iovec(skb, 0, m->msg_iov, total_len);
if (error == 0) {
consume_skb(skb);
return total_len;
}
}
kfree_skb(skb);
end:
return error;
}
#ifdef CONFIG_PROC_FS
static int pppoe_seq_show(struct seq_file *seq, void *v)
{
struct pppox_sock *po;
char *dev_name;
if (v == SEQ_START_TOKEN) {
seq_puts(seq, "Id Address Device\n");
goto out;
}
po = v;
dev_name = po->pppoe_pa.dev;
seq_printf(seq, "%08X %pM %8s\n",
po->pppoe_pa.sid, po->pppoe_pa.remote, dev_name);
out:
return 0;
}
static inline struct pppox_sock *pppoe_get_idx(struct pppoe_net *pn, loff_t pos)
{
struct pppox_sock *po;
int i;
for (i = 0; i < PPPOE_HASH_SIZE; i++) {
po = pn->hash_table[i];
while (po) {
if (!pos--)
goto out;
po = po->next;
}
}
out:
return po;
}
static void *pppoe_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(pn->hash_lock)
{
struct pppoe_net *pn = pppoe_pernet(seq_file_net(seq));
loff_t l = *pos;
read_lock_bh(&pn->hash_lock);
return l ? pppoe_get_idx(pn, --l) : SEQ_START_TOKEN;
}
static void *pppoe_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct pppoe_net *pn = pppoe_pernet(seq_file_net(seq));
struct pppox_sock *po;
++*pos;
if (v == SEQ_START_TOKEN) {
po = pppoe_get_idx(pn, 0);
goto out;
}
po = v;
if (po->next)
po = po->next;
else {
int hash = hash_item(po->pppoe_pa.sid, po->pppoe_pa.remote);
po = NULL;
while (++hash < PPPOE_HASH_SIZE) {
po = pn->hash_table[hash];
if (po)
break;
}
}
out:
return po;
}
static void pppoe_seq_stop(struct seq_file *seq, void *v)
__releases(pn->hash_lock)
{
struct pppoe_net *pn = pppoe_pernet(seq_file_net(seq));
read_unlock_bh(&pn->hash_lock);
}
static const struct seq_operations pppoe_seq_ops = {
.start = pppoe_seq_start,
.next = pppoe_seq_next,
.stop = pppoe_seq_stop,
.show = pppoe_seq_show,
};
static int pppoe_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pppoe_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations pppoe_seq_fops = {
.owner = THIS_MODULE,
.open = pppoe_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif /* CONFIG_PROC_FS */
static const struct proto_ops pppoe_ops = {
.family = AF_PPPOX,
.owner = THIS_MODULE,
.release = pppoe_release,
.bind = sock_no_bind,
.connect = pppoe_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = pppoe_getname,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = pppoe_sendmsg,
.recvmsg = pppoe_recvmsg,
.mmap = sock_no_mmap,
.ioctl = pppox_ioctl,
};
static const struct pppox_proto pppoe_proto = {
.create = pppoe_create,
.ioctl = pppoe_ioctl,
.owner = THIS_MODULE,
};
static __net_init int pppoe_init_net(struct net *net)
{
struct pppoe_net *pn = pppoe_pernet(net);
struct proc_dir_entry *pde;
rwlock_init(&pn->hash_lock);
pde = proc_create("pppoe", S_IRUGO, net->proc_net, &pppoe_seq_fops);
#ifdef CONFIG_PROC_FS
if (!pde)
return -ENOMEM;
#endif
return 0;
}
static __net_exit void pppoe_exit_net(struct net *net)
{
remove_proc_entry("pppoe", net->proc_net);
}
static struct pernet_operations pppoe_net_ops = {
.init = pppoe_init_net,
.exit = pppoe_exit_net,
.id = &pppoe_net_id,
.size = sizeof(struct pppoe_net),
};
static int __init pppoe_init(void)
{
int err;
err = register_pernet_device(&pppoe_net_ops);
if (err)
goto out;
err = proto_register(&pppoe_sk_proto, 0);
if (err)
goto out_unregister_net_ops;
err = register_pppox_proto(PX_PROTO_OE, &pppoe_proto);
if (err)
goto out_unregister_pppoe_proto;
dev_add_pack(&pppoes_ptype);
dev_add_pack(&pppoed_ptype);
register_netdevice_notifier(&pppoe_notifier);
return 0;
out_unregister_pppoe_proto:
proto_unregister(&pppoe_sk_proto);
out_unregister_net_ops:
unregister_pernet_device(&pppoe_net_ops);
out:
return err;
}
static void __exit pppoe_exit(void)
{
unregister_netdevice_notifier(&pppoe_notifier);
dev_remove_pack(&pppoed_ptype);
dev_remove_pack(&pppoes_ptype);
unregister_pppox_proto(PX_PROTO_OE);
proto_unregister(&pppoe_sk_proto);
unregister_pernet_device(&pppoe_net_ops);
}
module_init(pppoe_init);
module_exit(pppoe_exit);
MODULE_AUTHOR("Michal Ostrowski <mostrows@speakeasy.net>");
MODULE_DESCRIPTION("PPP over Ethernet driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_PPPOX);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_3 |
crossvul-cpp_data_bad_3012_1 | /*
* fs/f2fs/segment.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/fs.h>
#include <linux/f2fs_fs.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/prefetch.h>
#include <linux/kthread.h>
#include <linux/swap.h>
#include <linux/timer.h>
#include <linux/freezer.h>
#include <linux/sched/signal.h>
#include "f2fs.h"
#include "segment.h"
#include "node.h"
#include "gc.h"
#include "trace.h"
#include <trace/events/f2fs.h>
#define __reverse_ffz(x) __reverse_ffs(~(x))
static struct kmem_cache *discard_entry_slab;
static struct kmem_cache *discard_cmd_slab;
static struct kmem_cache *sit_entry_set_slab;
static struct kmem_cache *inmem_entry_slab;
static unsigned long __reverse_ulong(unsigned char *str)
{
unsigned long tmp = 0;
int shift = 24, idx = 0;
#if BITS_PER_LONG == 64
shift = 56;
#endif
while (shift >= 0) {
tmp |= (unsigned long)str[idx++] << shift;
shift -= BITS_PER_BYTE;
}
return tmp;
}
/*
* __reverse_ffs is copied from include/asm-generic/bitops/__ffs.h since
* MSB and LSB are reversed in a byte by f2fs_set_bit.
*/
static inline unsigned long __reverse_ffs(unsigned long word)
{
int num = 0;
#if BITS_PER_LONG == 64
if ((word & 0xffffffff00000000UL) == 0)
num += 32;
else
word >>= 32;
#endif
if ((word & 0xffff0000) == 0)
num += 16;
else
word >>= 16;
if ((word & 0xff00) == 0)
num += 8;
else
word >>= 8;
if ((word & 0xf0) == 0)
num += 4;
else
word >>= 4;
if ((word & 0xc) == 0)
num += 2;
else
word >>= 2;
if ((word & 0x2) == 0)
num += 1;
return num;
}
/*
* __find_rev_next(_zero)_bit is copied from lib/find_next_bit.c because
* f2fs_set_bit makes MSB and LSB reversed in a byte.
* @size must be integral times of unsigned long.
* Example:
* MSB <--> LSB
* f2fs_set_bit(0, bitmap) => 1000 0000
* f2fs_set_bit(7, bitmap) => 0000 0001
*/
static unsigned long __find_rev_next_bit(const unsigned long *addr,
unsigned long size, unsigned long offset)
{
const unsigned long *p = addr + BIT_WORD(offset);
unsigned long result = size;
unsigned long tmp;
if (offset >= size)
return size;
size -= (offset & ~(BITS_PER_LONG - 1));
offset %= BITS_PER_LONG;
while (1) {
if (*p == 0)
goto pass;
tmp = __reverse_ulong((unsigned char *)p);
tmp &= ~0UL >> offset;
if (size < BITS_PER_LONG)
tmp &= (~0UL << (BITS_PER_LONG - size));
if (tmp)
goto found;
pass:
if (size <= BITS_PER_LONG)
break;
size -= BITS_PER_LONG;
offset = 0;
p++;
}
return result;
found:
return result - size + __reverse_ffs(tmp);
}
static unsigned long __find_rev_next_zero_bit(const unsigned long *addr,
unsigned long size, unsigned long offset)
{
const unsigned long *p = addr + BIT_WORD(offset);
unsigned long result = size;
unsigned long tmp;
if (offset >= size)
return size;
size -= (offset & ~(BITS_PER_LONG - 1));
offset %= BITS_PER_LONG;
while (1) {
if (*p == ~0UL)
goto pass;
tmp = __reverse_ulong((unsigned char *)p);
if (offset)
tmp |= ~0UL << (BITS_PER_LONG - offset);
if (size < BITS_PER_LONG)
tmp |= ~0UL >> size;
if (tmp != ~0UL)
goto found;
pass:
if (size <= BITS_PER_LONG)
break;
size -= BITS_PER_LONG;
offset = 0;
p++;
}
return result;
found:
return result - size + __reverse_ffz(tmp);
}
bool need_SSR(struct f2fs_sb_info *sbi)
{
int node_secs = get_blocktype_secs(sbi, F2FS_DIRTY_NODES);
int dent_secs = get_blocktype_secs(sbi, F2FS_DIRTY_DENTS);
int imeta_secs = get_blocktype_secs(sbi, F2FS_DIRTY_IMETA);
if (test_opt(sbi, LFS))
return false;
if (sbi->gc_thread && sbi->gc_thread->gc_urgent)
return true;
return free_sections(sbi) <= (node_secs + 2 * dent_secs + imeta_secs +
2 * reserved_sections(sbi));
}
void register_inmem_page(struct inode *inode, struct page *page)
{
struct f2fs_inode_info *fi = F2FS_I(inode);
struct inmem_pages *new;
f2fs_trace_pid(page);
set_page_private(page, (unsigned long)ATOMIC_WRITTEN_PAGE);
SetPagePrivate(page);
new = f2fs_kmem_cache_alloc(inmem_entry_slab, GFP_NOFS);
/* add atomic page indices to the list */
new->page = page;
INIT_LIST_HEAD(&new->list);
/* increase reference count with clean state */
mutex_lock(&fi->inmem_lock);
get_page(page);
list_add_tail(&new->list, &fi->inmem_pages);
inc_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
mutex_unlock(&fi->inmem_lock);
trace_f2fs_register_inmem_page(page, INMEM);
}
static int __revoke_inmem_pages(struct inode *inode,
struct list_head *head, bool drop, bool recover)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct inmem_pages *cur, *tmp;
int err = 0;
list_for_each_entry_safe(cur, tmp, head, list) {
struct page *page = cur->page;
if (drop)
trace_f2fs_commit_inmem_page(page, INMEM_DROP);
lock_page(page);
if (recover) {
struct dnode_of_data dn;
struct node_info ni;
trace_f2fs_commit_inmem_page(page, INMEM_REVOKE);
retry:
set_new_dnode(&dn, inode, NULL, NULL, 0);
err = get_dnode_of_data(&dn, page->index, LOOKUP_NODE);
if (err) {
if (err == -ENOMEM) {
congestion_wait(BLK_RW_ASYNC, HZ/50);
cond_resched();
goto retry;
}
err = -EAGAIN;
goto next;
}
get_node_info(sbi, dn.nid, &ni);
f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
cur->old_addr, ni.version, true, true);
f2fs_put_dnode(&dn);
}
next:
/* we don't need to invalidate this in the sccessful status */
if (drop || recover)
ClearPageUptodate(page);
set_page_private(page, 0);
ClearPagePrivate(page);
f2fs_put_page(page, 1);
list_del(&cur->list);
kmem_cache_free(inmem_entry_slab, cur);
dec_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
}
return err;
}
void drop_inmem_pages(struct inode *inode)
{
struct f2fs_inode_info *fi = F2FS_I(inode);
mutex_lock(&fi->inmem_lock);
__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
mutex_unlock(&fi->inmem_lock);
clear_inode_flag(inode, FI_ATOMIC_FILE);
clear_inode_flag(inode, FI_HOT_DATA);
stat_dec_atomic_write(inode);
}
void drop_inmem_page(struct inode *inode, struct page *page)
{
struct f2fs_inode_info *fi = F2FS_I(inode);
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct list_head *head = &fi->inmem_pages;
struct inmem_pages *cur = NULL;
f2fs_bug_on(sbi, !IS_ATOMIC_WRITTEN_PAGE(page));
mutex_lock(&fi->inmem_lock);
list_for_each_entry(cur, head, list) {
if (cur->page == page)
break;
}
f2fs_bug_on(sbi, !cur || cur->page != page);
list_del(&cur->list);
mutex_unlock(&fi->inmem_lock);
dec_page_count(sbi, F2FS_INMEM_PAGES);
kmem_cache_free(inmem_entry_slab, cur);
ClearPageUptodate(page);
set_page_private(page, 0);
ClearPagePrivate(page);
f2fs_put_page(page, 0);
trace_f2fs_commit_inmem_page(page, INMEM_INVALIDATE);
}
static int __commit_inmem_pages(struct inode *inode,
struct list_head *revoke_list)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct f2fs_inode_info *fi = F2FS_I(inode);
struct inmem_pages *cur, *tmp;
struct f2fs_io_info fio = {
.sbi = sbi,
.type = DATA,
.op = REQ_OP_WRITE,
.op_flags = REQ_SYNC | REQ_PRIO,
.io_type = FS_DATA_IO,
};
pgoff_t last_idx = ULONG_MAX;
int err = 0;
list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) {
struct page *page = cur->page;
lock_page(page);
if (page->mapping == inode->i_mapping) {
trace_f2fs_commit_inmem_page(page, INMEM);
set_page_dirty(page);
f2fs_wait_on_page_writeback(page, DATA, true);
if (clear_page_dirty_for_io(page)) {
inode_dec_dirty_pages(inode);
remove_dirty_inode(inode);
}
retry:
fio.page = page;
fio.old_blkaddr = NULL_ADDR;
fio.encrypted_page = NULL;
fio.need_lock = LOCK_DONE;
err = do_write_data_page(&fio);
if (err) {
if (err == -ENOMEM) {
congestion_wait(BLK_RW_ASYNC, HZ/50);
cond_resched();
goto retry;
}
unlock_page(page);
break;
}
/* record old blkaddr for revoking */
cur->old_addr = fio.old_blkaddr;
last_idx = page->index;
}
unlock_page(page);
list_move_tail(&cur->list, revoke_list);
}
if (last_idx != ULONG_MAX)
f2fs_submit_merged_write_cond(sbi, inode, 0, last_idx, DATA);
if (!err)
__revoke_inmem_pages(inode, revoke_list, false, false);
return err;
}
int commit_inmem_pages(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct f2fs_inode_info *fi = F2FS_I(inode);
struct list_head revoke_list;
int err;
INIT_LIST_HEAD(&revoke_list);
f2fs_balance_fs(sbi, true);
f2fs_lock_op(sbi);
set_inode_flag(inode, FI_ATOMIC_COMMIT);
mutex_lock(&fi->inmem_lock);
err = __commit_inmem_pages(inode, &revoke_list);
if (err) {
int ret;
/*
* try to revoke all committed pages, but still we could fail
* due to no memory or other reason, if that happened, EAGAIN
* will be returned, which means in such case, transaction is
* already not integrity, caller should use journal to do the
* recovery or rewrite & commit last transaction. For other
* error number, revoking was done by filesystem itself.
*/
ret = __revoke_inmem_pages(inode, &revoke_list, false, true);
if (ret)
err = ret;
/* drop all uncommitted pages */
__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
}
mutex_unlock(&fi->inmem_lock);
clear_inode_flag(inode, FI_ATOMIC_COMMIT);
f2fs_unlock_op(sbi);
return err;
}
/*
* This function balances dirty node and dentry pages.
* In addition, it controls garbage collection.
*/
void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need)
{
#ifdef CONFIG_F2FS_FAULT_INJECTION
if (time_to_inject(sbi, FAULT_CHECKPOINT)) {
f2fs_show_injection_info(FAULT_CHECKPOINT);
f2fs_stop_checkpoint(sbi, false);
}
#endif
/* balance_fs_bg is able to be pending */
if (need && excess_cached_nats(sbi))
f2fs_balance_fs_bg(sbi);
/*
* We should do GC or end up with checkpoint, if there are so many dirty
* dir/node pages without enough free segments.
*/
if (has_not_enough_free_secs(sbi, 0, 0)) {
mutex_lock(&sbi->gc_mutex);
f2fs_gc(sbi, false, false, NULL_SEGNO);
}
}
void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi)
{
/* try to shrink extent cache when there is no enough memory */
if (!available_free_memory(sbi, EXTENT_CACHE))
f2fs_shrink_extent_tree(sbi, EXTENT_CACHE_SHRINK_NUMBER);
/* check the # of cached NAT entries */
if (!available_free_memory(sbi, NAT_ENTRIES))
try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK);
if (!available_free_memory(sbi, FREE_NIDS))
try_to_free_nids(sbi, MAX_FREE_NIDS);
else
build_free_nids(sbi, false, false);
if (!is_idle(sbi) && !excess_dirty_nats(sbi))
return;
/* checkpoint is the only way to shrink partial cached entries */
if (!available_free_memory(sbi, NAT_ENTRIES) ||
!available_free_memory(sbi, INO_ENTRIES) ||
excess_prefree_segs(sbi) ||
excess_dirty_nats(sbi) ||
f2fs_time_over(sbi, CP_TIME)) {
if (test_opt(sbi, DATA_FLUSH)) {
struct blk_plug plug;
blk_start_plug(&plug);
sync_dirty_inodes(sbi, FILE_INODE);
blk_finish_plug(&plug);
}
f2fs_sync_fs(sbi->sb, true);
stat_inc_bg_cp_count(sbi->stat_info);
}
}
static int __submit_flush_wait(struct f2fs_sb_info *sbi,
struct block_device *bdev)
{
struct bio *bio = f2fs_bio_alloc(0);
int ret;
bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
bio_set_dev(bio, bdev);
ret = submit_bio_wait(bio);
bio_put(bio);
trace_f2fs_issue_flush(bdev, test_opt(sbi, NOBARRIER),
test_opt(sbi, FLUSH_MERGE), ret);
return ret;
}
static int submit_flush_wait(struct f2fs_sb_info *sbi)
{
int ret = __submit_flush_wait(sbi, sbi->sb->s_bdev);
int i;
if (!sbi->s_ndevs || ret)
return ret;
for (i = 1; i < sbi->s_ndevs; i++) {
ret = __submit_flush_wait(sbi, FDEV(i).bdev);
if (ret)
break;
}
return ret;
}
static int issue_flush_thread(void *data)
{
struct f2fs_sb_info *sbi = data;
struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
wait_queue_head_t *q = &fcc->flush_wait_queue;
repeat:
if (kthread_should_stop())
return 0;
sb_start_intwrite(sbi->sb);
if (!llist_empty(&fcc->issue_list)) {
struct flush_cmd *cmd, *next;
int ret;
fcc->dispatch_list = llist_del_all(&fcc->issue_list);
fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush);
llist_for_each_entry_safe(cmd, next,
fcc->dispatch_list, llnode) {
cmd->ret = ret;
complete(&cmd->wait);
}
fcc->dispatch_list = NULL;
}
sb_end_intwrite(sbi->sb);
wait_event_interruptible(*q,
kthread_should_stop() || !llist_empty(&fcc->issue_list));
goto repeat;
}
int f2fs_issue_flush(struct f2fs_sb_info *sbi)
{
struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
struct flush_cmd cmd;
int ret;
if (test_opt(sbi, NOBARRIER))
return 0;
if (!test_opt(sbi, FLUSH_MERGE)) {
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush);
return ret;
}
if (atomic_inc_return(&fcc->issing_flush) == 1) {
ret = submit_flush_wait(sbi);
atomic_dec(&fcc->issing_flush);
atomic_inc(&fcc->issued_flush);
return ret;
}
init_completion(&cmd.wait);
llist_add(&cmd.llnode, &fcc->issue_list);
/* update issue_list before we wake up issue_flush thread */
smp_mb();
if (waitqueue_active(&fcc->flush_wait_queue))
wake_up(&fcc->flush_wait_queue);
if (fcc->f2fs_issue_flush) {
wait_for_completion(&cmd.wait);
atomic_dec(&fcc->issing_flush);
} else {
struct llist_node *list;
list = llist_del_all(&fcc->issue_list);
if (!list) {
wait_for_completion(&cmd.wait);
atomic_dec(&fcc->issing_flush);
} else {
struct flush_cmd *tmp, *next;
ret = submit_flush_wait(sbi);
llist_for_each_entry_safe(tmp, next, list, llnode) {
if (tmp == &cmd) {
cmd.ret = ret;
atomic_dec(&fcc->issing_flush);
continue;
}
tmp->ret = ret;
complete(&tmp->wait);
}
}
}
return cmd.ret;
}
int create_flush_cmd_control(struct f2fs_sb_info *sbi)
{
dev_t dev = sbi->sb->s_bdev->bd_dev;
struct flush_cmd_control *fcc;
int err = 0;
if (SM_I(sbi)->fcc_info) {
fcc = SM_I(sbi)->fcc_info;
if (fcc->f2fs_issue_flush)
return err;
goto init_thread;
}
fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL);
if (!fcc)
return -ENOMEM;
atomic_set(&fcc->issued_flush, 0);
atomic_set(&fcc->issing_flush, 0);
init_waitqueue_head(&fcc->flush_wait_queue);
init_llist_head(&fcc->issue_list);
SM_I(sbi)->fcc_info = fcc;
if (!test_opt(sbi, FLUSH_MERGE))
return err;
init_thread:
fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
"f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
if (IS_ERR(fcc->f2fs_issue_flush)) {
err = PTR_ERR(fcc->f2fs_issue_flush);
kfree(fcc);
SM_I(sbi)->fcc_info = NULL;
return err;
}
return err;
}
void destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free)
{
struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
if (fcc && fcc->f2fs_issue_flush) {
struct task_struct *flush_thread = fcc->f2fs_issue_flush;
fcc->f2fs_issue_flush = NULL;
kthread_stop(flush_thread);
}
if (free) {
kfree(fcc);
SM_I(sbi)->fcc_info = NULL;
}
}
static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
enum dirty_type dirty_type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
/* need not be added */
if (IS_CURSEG(sbi, segno))
return;
if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
dirty_i->nr_dirty[dirty_type]++;
if (dirty_type == DIRTY) {
struct seg_entry *sentry = get_seg_entry(sbi, segno);
enum dirty_type t = sentry->type;
if (unlikely(t >= DIRTY)) {
f2fs_bug_on(sbi, 1);
return;
}
if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
dirty_i->nr_dirty[t]++;
}
}
static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
enum dirty_type dirty_type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
dirty_i->nr_dirty[dirty_type]--;
if (dirty_type == DIRTY) {
struct seg_entry *sentry = get_seg_entry(sbi, segno);
enum dirty_type t = sentry->type;
if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
dirty_i->nr_dirty[t]--;
if (get_valid_blocks(sbi, segno, true) == 0)
clear_bit(GET_SEC_FROM_SEG(sbi, segno),
dirty_i->victim_secmap);
}
}
/*
* Should not occur error such as -ENOMEM.
* Adding dirty entry into seglist is not critical operation.
* If a given segment is one of current working segments, it won't be added.
*/
static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned short valid_blocks;
if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
return;
mutex_lock(&dirty_i->seglist_lock);
valid_blocks = get_valid_blocks(sbi, segno, false);
if (valid_blocks == 0) {
__locate_dirty_segment(sbi, segno, PRE);
__remove_dirty_segment(sbi, segno, DIRTY);
} else if (valid_blocks < sbi->blocks_per_seg) {
__locate_dirty_segment(sbi, segno, DIRTY);
} else {
/* Recovery routine with SSR needs this */
__remove_dirty_segment(sbi, segno, DIRTY);
}
mutex_unlock(&dirty_i->seglist_lock);
}
static struct discard_cmd *__create_discard_cmd(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *pend_list;
struct discard_cmd *dc;
f2fs_bug_on(sbi, !len);
pend_list = &dcc->pend_list[plist_idx(len)];
dc = f2fs_kmem_cache_alloc(discard_cmd_slab, GFP_NOFS);
INIT_LIST_HEAD(&dc->list);
dc->bdev = bdev;
dc->lstart = lstart;
dc->start = start;
dc->len = len;
dc->ref = 0;
dc->state = D_PREP;
dc->error = 0;
init_completion(&dc->wait);
list_add_tail(&dc->list, pend_list);
atomic_inc(&dcc->discard_cmd_cnt);
dcc->undiscard_blks += len;
return dc;
}
static struct discard_cmd *__attach_discard_cmd(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len,
struct rb_node *parent, struct rb_node **p)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_cmd *dc;
dc = __create_discard_cmd(sbi, bdev, lstart, start, len);
rb_link_node(&dc->rb_node, parent, p);
rb_insert_color(&dc->rb_node, &dcc->root);
return dc;
}
static void __detach_discard_cmd(struct discard_cmd_control *dcc,
struct discard_cmd *dc)
{
if (dc->state == D_DONE)
atomic_dec(&dcc->issing_discard);
list_del(&dc->list);
rb_erase(&dc->rb_node, &dcc->root);
dcc->undiscard_blks -= dc->len;
kmem_cache_free(discard_cmd_slab, dc);
atomic_dec(&dcc->discard_cmd_cnt);
}
static void __remove_discard_cmd(struct f2fs_sb_info *sbi,
struct discard_cmd *dc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
f2fs_bug_on(sbi, dc->ref);
if (dc->error == -EOPNOTSUPP)
dc->error = 0;
if (dc->error)
f2fs_msg(sbi->sb, KERN_INFO,
"Issue discard(%u, %u, %u) failed, ret: %d",
dc->lstart, dc->start, dc->len, dc->error);
__detach_discard_cmd(dcc, dc);
}
static void f2fs_submit_discard_endio(struct bio *bio)
{
struct discard_cmd *dc = (struct discard_cmd *)bio->bi_private;
dc->error = blk_status_to_errno(bio->bi_status);
dc->state = D_DONE;
complete_all(&dc->wait);
bio_put(bio);
}
void __check_sit_bitmap(struct f2fs_sb_info *sbi,
block_t start, block_t end)
{
#ifdef CONFIG_F2FS_CHECK_FS
struct seg_entry *sentry;
unsigned int segno;
block_t blk = start;
unsigned long offset, size, max_blocks = sbi->blocks_per_seg;
unsigned long *map;
while (blk < end) {
segno = GET_SEGNO(sbi, blk);
sentry = get_seg_entry(sbi, segno);
offset = GET_BLKOFF_FROM_SEG0(sbi, blk);
if (end < START_BLOCK(sbi, segno + 1))
size = GET_BLKOFF_FROM_SEG0(sbi, end);
else
size = max_blocks;
map = (unsigned long *)(sentry->cur_valid_map);
offset = __find_rev_next_bit(map, size, offset);
f2fs_bug_on(sbi, offset != size);
blk = START_BLOCK(sbi, segno + 1);
}
#endif
}
/* this function is copied from blkdev_issue_discard from block/blk-lib.c */
static void __submit_discard_cmd(struct f2fs_sb_info *sbi,
struct discard_cmd *dc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct bio *bio = NULL;
if (dc->state != D_PREP)
return;
trace_f2fs_issue_discard(dc->bdev, dc->start, dc->len);
dc->error = __blkdev_issue_discard(dc->bdev,
SECTOR_FROM_BLOCK(dc->start),
SECTOR_FROM_BLOCK(dc->len),
GFP_NOFS, 0, &bio);
if (!dc->error) {
/* should keep before submission to avoid D_DONE right away */
dc->state = D_SUBMIT;
atomic_inc(&dcc->issued_discard);
atomic_inc(&dcc->issing_discard);
if (bio) {
bio->bi_private = dc;
bio->bi_end_io = f2fs_submit_discard_endio;
bio->bi_opf |= REQ_SYNC;
submit_bio(bio);
list_move_tail(&dc->list, &dcc->wait_list);
__check_sit_bitmap(sbi, dc->start, dc->start + dc->len);
f2fs_update_iostat(sbi, FS_DISCARD, 1);
}
} else {
__remove_discard_cmd(sbi, dc);
}
}
static struct discard_cmd *__insert_discard_tree(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len,
struct rb_node **insert_p,
struct rb_node *insert_parent)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct rb_node **p = &dcc->root.rb_node;
struct rb_node *parent = NULL;
struct discard_cmd *dc = NULL;
if (insert_p && insert_parent) {
parent = insert_parent;
p = insert_p;
goto do_insert;
}
p = __lookup_rb_tree_for_insert(sbi, &dcc->root, &parent, lstart);
do_insert:
dc = __attach_discard_cmd(sbi, bdev, lstart, start, len, parent, p);
if (!dc)
return NULL;
return dc;
}
static void __relocate_discard_cmd(struct discard_cmd_control *dcc,
struct discard_cmd *dc)
{
list_move_tail(&dc->list, &dcc->pend_list[plist_idx(dc->len)]);
}
static void __punch_discard_cmd(struct f2fs_sb_info *sbi,
struct discard_cmd *dc, block_t blkaddr)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_info di = dc->di;
bool modified = false;
if (dc->state == D_DONE || dc->len == 1) {
__remove_discard_cmd(sbi, dc);
return;
}
dcc->undiscard_blks -= di.len;
if (blkaddr > di.lstart) {
dc->len = blkaddr - dc->lstart;
dcc->undiscard_blks += dc->len;
__relocate_discard_cmd(dcc, dc);
modified = true;
}
if (blkaddr < di.lstart + di.len - 1) {
if (modified) {
__insert_discard_tree(sbi, dc->bdev, blkaddr + 1,
di.start + blkaddr + 1 - di.lstart,
di.lstart + di.len - 1 - blkaddr,
NULL, NULL);
} else {
dc->lstart++;
dc->len--;
dc->start++;
dcc->undiscard_blks += dc->len;
__relocate_discard_cmd(dcc, dc);
}
}
}
static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
struct discard_cmd *dc;
struct discard_info di = {0};
struct rb_node **insert_p = NULL, *insert_parent = NULL;
block_t end = lstart + len;
mutex_lock(&dcc->cmd_lock);
dc = (struct discard_cmd *)__lookup_rb_tree_ret(&dcc->root,
NULL, lstart,
(struct rb_entry **)&prev_dc,
(struct rb_entry **)&next_dc,
&insert_p, &insert_parent, true);
if (dc)
prev_dc = dc;
if (!prev_dc) {
di.lstart = lstart;
di.len = next_dc ? next_dc->lstart - lstart : len;
di.len = min(di.len, len);
di.start = start;
}
while (1) {
struct rb_node *node;
bool merged = false;
struct discard_cmd *tdc = NULL;
if (prev_dc) {
di.lstart = prev_dc->lstart + prev_dc->len;
if (di.lstart < lstart)
di.lstart = lstart;
if (di.lstart >= end)
break;
if (!next_dc || next_dc->lstart > end)
di.len = end - di.lstart;
else
di.len = next_dc->lstart - di.lstart;
di.start = start + di.lstart - lstart;
}
if (!di.len)
goto next;
if (prev_dc && prev_dc->state == D_PREP &&
prev_dc->bdev == bdev &&
__is_discard_back_mergeable(&di, &prev_dc->di)) {
prev_dc->di.len += di.len;
dcc->undiscard_blks += di.len;
__relocate_discard_cmd(dcc, prev_dc);
di = prev_dc->di;
tdc = prev_dc;
merged = true;
}
if (next_dc && next_dc->state == D_PREP &&
next_dc->bdev == bdev &&
__is_discard_front_mergeable(&di, &next_dc->di)) {
next_dc->di.lstart = di.lstart;
next_dc->di.len += di.len;
next_dc->di.start = di.start;
dcc->undiscard_blks += di.len;
__relocate_discard_cmd(dcc, next_dc);
if (tdc)
__remove_discard_cmd(sbi, tdc);
merged = true;
}
if (!merged) {
__insert_discard_tree(sbi, bdev, di.lstart, di.start,
di.len, NULL, NULL);
}
next:
prev_dc = next_dc;
if (!prev_dc)
break;
node = rb_next(&prev_dc->rb_node);
next_dc = rb_entry_safe(node, struct discard_cmd, rb_node);
}
mutex_unlock(&dcc->cmd_lock);
}
static int __queue_discard_cmd(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t blkstart, block_t blklen)
{
block_t lblkstart = blkstart;
trace_f2fs_queue_discard(bdev, blkstart, blklen);
if (sbi->s_ndevs) {
int devi = f2fs_target_device_index(sbi, blkstart);
blkstart -= FDEV(devi).start_blk;
}
__update_discard_tree_range(sbi, bdev, lblkstart, blkstart, blklen);
return 0;
}
static int __issue_discard_cmd(struct f2fs_sb_info *sbi, bool issue_cond)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *pend_list;
struct discard_cmd *dc, *tmp;
struct blk_plug plug;
int iter = 0, issued = 0;
int i;
bool io_interrupted = false;
mutex_lock(&dcc->cmd_lock);
f2fs_bug_on(sbi,
!__check_rb_tree_consistence(sbi, &dcc->root));
blk_start_plug(&plug);
for (i = MAX_PLIST_NUM - 1;
i >= 0 && plist_issue(dcc->pend_list_tag[i]); i--) {
pend_list = &dcc->pend_list[i];
list_for_each_entry_safe(dc, tmp, pend_list, list) {
f2fs_bug_on(sbi, dc->state != D_PREP);
/* Hurry up to finish fstrim */
if (dcc->pend_list_tag[i] & P_TRIM) {
__submit_discard_cmd(sbi, dc);
issued++;
if (fatal_signal_pending(current))
break;
continue;
}
if (!issue_cond) {
__submit_discard_cmd(sbi, dc);
issued++;
continue;
}
if (is_idle(sbi)) {
__submit_discard_cmd(sbi, dc);
issued++;
} else {
io_interrupted = true;
}
if (++iter >= DISCARD_ISSUE_RATE)
goto out;
}
if (list_empty(pend_list) && dcc->pend_list_tag[i] & P_TRIM)
dcc->pend_list_tag[i] &= (~P_TRIM);
}
out:
blk_finish_plug(&plug);
mutex_unlock(&dcc->cmd_lock);
if (!issued && io_interrupted)
issued = -1;
return issued;
}
static void __drop_discard_cmd(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *pend_list;
struct discard_cmd *dc, *tmp;
int i;
mutex_lock(&dcc->cmd_lock);
for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
pend_list = &dcc->pend_list[i];
list_for_each_entry_safe(dc, tmp, pend_list, list) {
f2fs_bug_on(sbi, dc->state != D_PREP);
__remove_discard_cmd(sbi, dc);
}
}
mutex_unlock(&dcc->cmd_lock);
}
static void __wait_one_discard_bio(struct f2fs_sb_info *sbi,
struct discard_cmd *dc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
wait_for_completion_io(&dc->wait);
mutex_lock(&dcc->cmd_lock);
f2fs_bug_on(sbi, dc->state != D_DONE);
dc->ref--;
if (!dc->ref)
__remove_discard_cmd(sbi, dc);
mutex_unlock(&dcc->cmd_lock);
}
static void __wait_discard_cmd(struct f2fs_sb_info *sbi, bool wait_cond)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *wait_list = &(dcc->wait_list);
struct discard_cmd *dc, *tmp;
bool need_wait;
next:
need_wait = false;
mutex_lock(&dcc->cmd_lock);
list_for_each_entry_safe(dc, tmp, wait_list, list) {
if (!wait_cond || (dc->state == D_DONE && !dc->ref)) {
wait_for_completion_io(&dc->wait);
__remove_discard_cmd(sbi, dc);
} else {
dc->ref++;
need_wait = true;
break;
}
}
mutex_unlock(&dcc->cmd_lock);
if (need_wait) {
__wait_one_discard_bio(sbi, dc);
goto next;
}
}
/* This should be covered by global mutex, &sit_i->sentry_lock */
void f2fs_wait_discard_bio(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_cmd *dc;
bool need_wait = false;
mutex_lock(&dcc->cmd_lock);
dc = (struct discard_cmd *)__lookup_rb_tree(&dcc->root, NULL, blkaddr);
if (dc) {
if (dc->state == D_PREP) {
__punch_discard_cmd(sbi, dc, blkaddr);
} else {
dc->ref++;
need_wait = true;
}
}
mutex_unlock(&dcc->cmd_lock);
if (need_wait)
__wait_one_discard_bio(sbi, dc);
}
void stop_discard_thread(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
if (dcc && dcc->f2fs_issue_discard) {
struct task_struct *discard_thread = dcc->f2fs_issue_discard;
dcc->f2fs_issue_discard = NULL;
kthread_stop(discard_thread);
}
}
/* This comes from f2fs_put_super and f2fs_trim_fs */
void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi)
{
__issue_discard_cmd(sbi, false);
__drop_discard_cmd(sbi);
__wait_discard_cmd(sbi, false);
}
static void mark_discard_range_all(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
int i;
mutex_lock(&dcc->cmd_lock);
for (i = 0; i < MAX_PLIST_NUM; i++)
dcc->pend_list_tag[i] |= P_TRIM;
mutex_unlock(&dcc->cmd_lock);
}
static int issue_discard_thread(void *data)
{
struct f2fs_sb_info *sbi = data;
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
wait_queue_head_t *q = &dcc->discard_wait_queue;
unsigned int wait_ms = DEF_MIN_DISCARD_ISSUE_TIME;
int issued;
set_freezable();
do {
wait_event_interruptible_timeout(*q,
kthread_should_stop() || freezing(current) ||
dcc->discard_wake,
msecs_to_jiffies(wait_ms));
if (try_to_freeze())
continue;
if (kthread_should_stop())
return 0;
if (dcc->discard_wake) {
dcc->discard_wake = 0;
if (sbi->gc_thread && sbi->gc_thread->gc_urgent)
mark_discard_range_all(sbi);
}
sb_start_intwrite(sbi->sb);
issued = __issue_discard_cmd(sbi, true);
if (issued) {
__wait_discard_cmd(sbi, true);
wait_ms = DEF_MIN_DISCARD_ISSUE_TIME;
} else {
wait_ms = DEF_MAX_DISCARD_ISSUE_TIME;
}
sb_end_intwrite(sbi->sb);
} while (!kthread_should_stop());
return 0;
}
#ifdef CONFIG_BLK_DEV_ZONED
static int __f2fs_issue_discard_zone(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t blkstart, block_t blklen)
{
sector_t sector, nr_sects;
block_t lblkstart = blkstart;
int devi = 0;
if (sbi->s_ndevs) {
devi = f2fs_target_device_index(sbi, blkstart);
blkstart -= FDEV(devi).start_blk;
}
/*
* We need to know the type of the zone: for conventional zones,
* use regular discard if the drive supports it. For sequential
* zones, reset the zone write pointer.
*/
switch (get_blkz_type(sbi, bdev, blkstart)) {
case BLK_ZONE_TYPE_CONVENTIONAL:
if (!blk_queue_discard(bdev_get_queue(bdev)))
return 0;
return __queue_discard_cmd(sbi, bdev, lblkstart, blklen);
case BLK_ZONE_TYPE_SEQWRITE_REQ:
case BLK_ZONE_TYPE_SEQWRITE_PREF:
sector = SECTOR_FROM_BLOCK(blkstart);
nr_sects = SECTOR_FROM_BLOCK(blklen);
if (sector & (bdev_zone_sectors(bdev) - 1) ||
nr_sects != bdev_zone_sectors(bdev)) {
f2fs_msg(sbi->sb, KERN_INFO,
"(%d) %s: Unaligned discard attempted (block %x + %x)",
devi, sbi->s_ndevs ? FDEV(devi).path: "",
blkstart, blklen);
return -EIO;
}
trace_f2fs_issue_reset_zone(bdev, blkstart);
return blkdev_reset_zones(bdev, sector,
nr_sects, GFP_NOFS);
default:
/* Unknown zone type: broken device ? */
return -EIO;
}
}
#endif
static int __issue_discard_async(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t blkstart, block_t blklen)
{
#ifdef CONFIG_BLK_DEV_ZONED
if (f2fs_sb_mounted_blkzoned(sbi->sb) &&
bdev_zoned_model(bdev) != BLK_ZONED_NONE)
return __f2fs_issue_discard_zone(sbi, bdev, blkstart, blklen);
#endif
return __queue_discard_cmd(sbi, bdev, blkstart, blklen);
}
static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
block_t blkstart, block_t blklen)
{
sector_t start = blkstart, len = 0;
struct block_device *bdev;
struct seg_entry *se;
unsigned int offset;
block_t i;
int err = 0;
bdev = f2fs_target_device(sbi, blkstart, NULL);
for (i = blkstart; i < blkstart + blklen; i++, len++) {
if (i != start) {
struct block_device *bdev2 =
f2fs_target_device(sbi, i, NULL);
if (bdev2 != bdev) {
err = __issue_discard_async(sbi, bdev,
start, len);
if (err)
return err;
bdev = bdev2;
start = i;
len = 0;
}
}
se = get_seg_entry(sbi, GET_SEGNO(sbi, i));
offset = GET_BLKOFF_FROM_SEG0(sbi, i);
if (!f2fs_test_and_set_bit(offset, se->discard_map))
sbi->discard_blks--;
}
if (len)
err = __issue_discard_async(sbi, bdev, start, len);
return err;
}
static bool add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc,
bool check_only)
{
int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
int max_blocks = sbi->blocks_per_seg;
struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
unsigned long *discard_map = (unsigned long *)se->discard_map;
unsigned long *dmap = SIT_I(sbi)->tmp_map;
unsigned int start = 0, end = -1;
bool force = (cpc->reason & CP_DISCARD);
struct discard_entry *de = NULL;
struct list_head *head = &SM_I(sbi)->dcc_info->entry_list;
int i;
if (se->valid_blocks == max_blocks || !f2fs_discard_en(sbi))
return false;
if (!force) {
if (!test_opt(sbi, DISCARD) || !se->valid_blocks ||
SM_I(sbi)->dcc_info->nr_discards >=
SM_I(sbi)->dcc_info->max_discards)
return false;
}
/* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
for (i = 0; i < entries; i++)
dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
(cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
while (force || SM_I(sbi)->dcc_info->nr_discards <=
SM_I(sbi)->dcc_info->max_discards) {
start = __find_rev_next_bit(dmap, max_blocks, end + 1);
if (start >= max_blocks)
break;
end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
if (force && start && end != max_blocks
&& (end - start) < cpc->trim_minlen)
continue;
if (check_only)
return true;
if (!de) {
de = f2fs_kmem_cache_alloc(discard_entry_slab,
GFP_F2FS_ZERO);
de->start_blkaddr = START_BLOCK(sbi, cpc->trim_start);
list_add_tail(&de->list, head);
}
for (i = start; i < end; i++)
__set_bit_le(i, (void *)de->discard_map);
SM_I(sbi)->dcc_info->nr_discards += end - start;
}
return false;
}
void release_discard_addrs(struct f2fs_sb_info *sbi)
{
struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
struct discard_entry *entry, *this;
/* drop caches */
list_for_each_entry_safe(entry, this, head, list) {
list_del(&entry->list);
kmem_cache_free(discard_entry_slab, entry);
}
}
/*
* Should call clear_prefree_segments after checkpoint is done.
*/
static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned int segno;
mutex_lock(&dirty_i->seglist_lock);
for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
__set_test_and_free(sbi, segno);
mutex_unlock(&dirty_i->seglist_lock);
}
void clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *head = &dcc->entry_list;
struct discard_entry *entry, *this;
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
unsigned int start = 0, end = -1;
unsigned int secno, start_segno;
bool force = (cpc->reason & CP_DISCARD);
mutex_lock(&dirty_i->seglist_lock);
while (1) {
int i;
start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
if (start >= MAIN_SEGS(sbi))
break;
end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
start + 1);
for (i = start; i < end; i++)
clear_bit(i, prefree_map);
dirty_i->nr_dirty[PRE] -= end - start;
if (!test_opt(sbi, DISCARD))
continue;
if (force && start >= cpc->trim_start &&
(end - 1) <= cpc->trim_end)
continue;
if (!test_opt(sbi, LFS) || sbi->segs_per_sec == 1) {
f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
(end - start) << sbi->log_blocks_per_seg);
continue;
}
next:
secno = GET_SEC_FROM_SEG(sbi, start);
start_segno = GET_SEG_FROM_SEC(sbi, secno);
if (!IS_CURSEC(sbi, secno) &&
!get_valid_blocks(sbi, start, true))
f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
sbi->segs_per_sec << sbi->log_blocks_per_seg);
start = start_segno + sbi->segs_per_sec;
if (start < end)
goto next;
else
end = start - 1;
}
mutex_unlock(&dirty_i->seglist_lock);
/* send small discards */
list_for_each_entry_safe(entry, this, head, list) {
unsigned int cur_pos = 0, next_pos, len, total_len = 0;
bool is_valid = test_bit_le(0, entry->discard_map);
find_next:
if (is_valid) {
next_pos = find_next_zero_bit_le(entry->discard_map,
sbi->blocks_per_seg, cur_pos);
len = next_pos - cur_pos;
if (f2fs_sb_mounted_blkzoned(sbi->sb) ||
(force && len < cpc->trim_minlen))
goto skip;
f2fs_issue_discard(sbi, entry->start_blkaddr + cur_pos,
len);
cpc->trimmed += len;
total_len += len;
} else {
next_pos = find_next_bit_le(entry->discard_map,
sbi->blocks_per_seg, cur_pos);
}
skip:
cur_pos = next_pos;
is_valid = !is_valid;
if (cur_pos < sbi->blocks_per_seg)
goto find_next;
list_del(&entry->list);
dcc->nr_discards -= total_len;
kmem_cache_free(discard_entry_slab, entry);
}
wake_up_discard_thread(sbi, false);
}
static int create_discard_cmd_control(struct f2fs_sb_info *sbi)
{
dev_t dev = sbi->sb->s_bdev->bd_dev;
struct discard_cmd_control *dcc;
int err = 0, i;
if (SM_I(sbi)->dcc_info) {
dcc = SM_I(sbi)->dcc_info;
goto init_thread;
}
dcc = kzalloc(sizeof(struct discard_cmd_control), GFP_KERNEL);
if (!dcc)
return -ENOMEM;
dcc->discard_granularity = DEFAULT_DISCARD_GRANULARITY;
INIT_LIST_HEAD(&dcc->entry_list);
for (i = 0; i < MAX_PLIST_NUM; i++) {
INIT_LIST_HEAD(&dcc->pend_list[i]);
if (i >= dcc->discard_granularity - 1)
dcc->pend_list_tag[i] |= P_ACTIVE;
}
INIT_LIST_HEAD(&dcc->wait_list);
mutex_init(&dcc->cmd_lock);
atomic_set(&dcc->issued_discard, 0);
atomic_set(&dcc->issing_discard, 0);
atomic_set(&dcc->discard_cmd_cnt, 0);
dcc->nr_discards = 0;
dcc->max_discards = MAIN_SEGS(sbi) << sbi->log_blocks_per_seg;
dcc->undiscard_blks = 0;
dcc->root = RB_ROOT;
init_waitqueue_head(&dcc->discard_wait_queue);
SM_I(sbi)->dcc_info = dcc;
init_thread:
dcc->f2fs_issue_discard = kthread_run(issue_discard_thread, sbi,
"f2fs_discard-%u:%u", MAJOR(dev), MINOR(dev));
if (IS_ERR(dcc->f2fs_issue_discard)) {
err = PTR_ERR(dcc->f2fs_issue_discard);
kfree(dcc);
SM_I(sbi)->dcc_info = NULL;
return err;
}
return err;
}
static void destroy_discard_cmd_control(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
if (!dcc)
return;
stop_discard_thread(sbi);
kfree(dcc);
SM_I(sbi)->dcc_info = NULL;
}
static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
{
struct sit_info *sit_i = SIT_I(sbi);
if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
sit_i->dirty_sentries++;
return false;
}
return true;
}
static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
unsigned int segno, int modified)
{
struct seg_entry *se = get_seg_entry(sbi, segno);
se->type = type;
if (modified)
__mark_sit_entry_dirty(sbi, segno);
}
static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
{
struct seg_entry *se;
unsigned int segno, offset;
long int new_vblocks;
bool exist;
#ifdef CONFIG_F2FS_CHECK_FS
bool mir_exist;
#endif
segno = GET_SEGNO(sbi, blkaddr);
se = get_seg_entry(sbi, segno);
new_vblocks = se->valid_blocks + del;
offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
f2fs_bug_on(sbi, (new_vblocks >> (sizeof(unsigned short) << 3) ||
(new_vblocks > sbi->blocks_per_seg)));
se->valid_blocks = new_vblocks;
se->mtime = get_mtime(sbi);
SIT_I(sbi)->max_mtime = se->mtime;
/* Update valid block bitmap */
if (del > 0) {
exist = f2fs_test_and_set_bit(offset, se->cur_valid_map);
#ifdef CONFIG_F2FS_CHECK_FS
mir_exist = f2fs_test_and_set_bit(offset,
se->cur_valid_map_mir);
if (unlikely(exist != mir_exist)) {
f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
"when setting bitmap, blk:%u, old bit:%d",
blkaddr, exist);
f2fs_bug_on(sbi, 1);
}
#endif
if (unlikely(exist)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Bitmap was wrongly set, blk:%u", blkaddr);
f2fs_bug_on(sbi, 1);
se->valid_blocks--;
del = 0;
}
if (f2fs_discard_en(sbi) &&
!f2fs_test_and_set_bit(offset, se->discard_map))
sbi->discard_blks--;
/* don't overwrite by SSR to keep node chain */
if (se->type == CURSEG_WARM_NODE) {
if (!f2fs_test_and_set_bit(offset, se->ckpt_valid_map))
se->ckpt_valid_blocks++;
}
} else {
exist = f2fs_test_and_clear_bit(offset, se->cur_valid_map);
#ifdef CONFIG_F2FS_CHECK_FS
mir_exist = f2fs_test_and_clear_bit(offset,
se->cur_valid_map_mir);
if (unlikely(exist != mir_exist)) {
f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
"when clearing bitmap, blk:%u, old bit:%d",
blkaddr, exist);
f2fs_bug_on(sbi, 1);
}
#endif
if (unlikely(!exist)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Bitmap was wrongly cleared, blk:%u", blkaddr);
f2fs_bug_on(sbi, 1);
se->valid_blocks++;
del = 0;
}
if (f2fs_discard_en(sbi) &&
f2fs_test_and_clear_bit(offset, se->discard_map))
sbi->discard_blks++;
}
if (!f2fs_test_bit(offset, se->ckpt_valid_map))
se->ckpt_valid_blocks += del;
__mark_sit_entry_dirty(sbi, segno);
/* update total number of valid blocks to be written in ckpt area */
SIT_I(sbi)->written_valid_blocks += del;
if (sbi->segs_per_sec > 1)
get_sec_entry(sbi, segno)->valid_blocks += del;
}
void refresh_sit_entry(struct f2fs_sb_info *sbi, block_t old, block_t new)
{
update_sit_entry(sbi, new, 1);
if (GET_SEGNO(sbi, old) != NULL_SEGNO)
update_sit_entry(sbi, old, -1);
locate_dirty_segment(sbi, GET_SEGNO(sbi, old));
locate_dirty_segment(sbi, GET_SEGNO(sbi, new));
}
void invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
{
unsigned int segno = GET_SEGNO(sbi, addr);
struct sit_info *sit_i = SIT_I(sbi);
f2fs_bug_on(sbi, addr == NULL_ADDR);
if (addr == NEW_ADDR)
return;
/* add it into sit main buffer */
mutex_lock(&sit_i->sentry_lock);
update_sit_entry(sbi, addr, -1);
/* add it into dirty seglist */
locate_dirty_segment(sbi, segno);
mutex_unlock(&sit_i->sentry_lock);
}
bool is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned int segno, offset;
struct seg_entry *se;
bool is_cp = false;
if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
return true;
mutex_lock(&sit_i->sentry_lock);
segno = GET_SEGNO(sbi, blkaddr);
se = get_seg_entry(sbi, segno);
offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
if (f2fs_test_bit(offset, se->ckpt_valid_map))
is_cp = true;
mutex_unlock(&sit_i->sentry_lock);
return is_cp;
}
/*
* This function should be resided under the curseg_mutex lock
*/
static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
struct f2fs_summary *sum)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
void *addr = curseg->sum_blk;
addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
memcpy(addr, sum, sizeof(struct f2fs_summary));
}
/*
* Calculate the number of current summary pages for writing
*/
int npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra)
{
int valid_sum_count = 0;
int i, sum_in_page;
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
if (sbi->ckpt->alloc_type[i] == SSR)
valid_sum_count += sbi->blocks_per_seg;
else {
if (for_ra)
valid_sum_count += le16_to_cpu(
F2FS_CKPT(sbi)->cur_data_blkoff[i]);
else
valid_sum_count += curseg_blkoff(sbi, i);
}
}
sum_in_page = (PAGE_SIZE - 2 * SUM_JOURNAL_SIZE -
SUM_FOOTER_SIZE) / SUMMARY_SIZE;
if (valid_sum_count <= sum_in_page)
return 1;
else if ((valid_sum_count - sum_in_page) <=
(PAGE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
return 2;
return 3;
}
/*
* Caller should put this summary page
*/
struct page *get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
{
return get_meta_page(sbi, GET_SUM_BLOCK(sbi, segno));
}
void update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr)
{
struct page *page = grab_meta_page(sbi, blk_addr);
void *dst = page_address(page);
if (src)
memcpy(dst, src, PAGE_SIZE);
else
memset(dst, 0, PAGE_SIZE);
set_page_dirty(page);
f2fs_put_page(page, 1);
}
static void write_sum_page(struct f2fs_sb_info *sbi,
struct f2fs_summary_block *sum_blk, block_t blk_addr)
{
update_meta_page(sbi, (void *)sum_blk, blk_addr);
}
static void write_current_sum_page(struct f2fs_sb_info *sbi,
int type, block_t blk_addr)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
struct page *page = grab_meta_page(sbi, blk_addr);
struct f2fs_summary_block *src = curseg->sum_blk;
struct f2fs_summary_block *dst;
dst = (struct f2fs_summary_block *)page_address(page);
mutex_lock(&curseg->curseg_mutex);
down_read(&curseg->journal_rwsem);
memcpy(&dst->journal, curseg->journal, SUM_JOURNAL_SIZE);
up_read(&curseg->journal_rwsem);
memcpy(dst->entries, src->entries, SUM_ENTRY_SIZE);
memcpy(&dst->footer, &src->footer, SUM_FOOTER_SIZE);
mutex_unlock(&curseg->curseg_mutex);
set_page_dirty(page);
f2fs_put_page(page, 1);
}
static int is_next_segment_free(struct f2fs_sb_info *sbi, int type)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int segno = curseg->segno + 1;
struct free_segmap_info *free_i = FREE_I(sbi);
if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
return !test_bit(segno, free_i->free_segmap);
return 0;
}
/*
* Find a new segment from the free segments bitmap to right order
* This function should be returned with success, otherwise BUG
*/
static void get_new_segment(struct f2fs_sb_info *sbi,
unsigned int *newseg, bool new_sec, int dir)
{
struct free_segmap_info *free_i = FREE_I(sbi);
unsigned int segno, secno, zoneno;
unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
unsigned int hint = GET_SEC_FROM_SEG(sbi, *newseg);
unsigned int old_zoneno = GET_ZONE_FROM_SEG(sbi, *newseg);
unsigned int left_start = hint;
bool init = true;
int go_left = 0;
int i;
spin_lock(&free_i->segmap_lock);
if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
segno = find_next_zero_bit(free_i->free_segmap,
GET_SEG_FROM_SEC(sbi, hint + 1), *newseg + 1);
if (segno < GET_SEG_FROM_SEC(sbi, hint + 1))
goto got_it;
}
find_other_zone:
secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
if (secno >= MAIN_SECS(sbi)) {
if (dir == ALLOC_RIGHT) {
secno = find_next_zero_bit(free_i->free_secmap,
MAIN_SECS(sbi), 0);
f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
} else {
go_left = 1;
left_start = hint - 1;
}
}
if (go_left == 0)
goto skip_left;
while (test_bit(left_start, free_i->free_secmap)) {
if (left_start > 0) {
left_start--;
continue;
}
left_start = find_next_zero_bit(free_i->free_secmap,
MAIN_SECS(sbi), 0);
f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
break;
}
secno = left_start;
skip_left:
hint = secno;
segno = GET_SEG_FROM_SEC(sbi, secno);
zoneno = GET_ZONE_FROM_SEC(sbi, secno);
/* give up on finding another zone */
if (!init)
goto got_it;
if (sbi->secs_per_zone == 1)
goto got_it;
if (zoneno == old_zoneno)
goto got_it;
if (dir == ALLOC_LEFT) {
if (!go_left && zoneno + 1 >= total_zones)
goto got_it;
if (go_left && zoneno == 0)
goto got_it;
}
for (i = 0; i < NR_CURSEG_TYPE; i++)
if (CURSEG_I(sbi, i)->zone == zoneno)
break;
if (i < NR_CURSEG_TYPE) {
/* zone is in user, try another */
if (go_left)
hint = zoneno * sbi->secs_per_zone - 1;
else if (zoneno + 1 >= total_zones)
hint = 0;
else
hint = (zoneno + 1) * sbi->secs_per_zone;
init = false;
goto find_other_zone;
}
got_it:
/* set it as dirty segment in free segmap */
f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
__set_inuse(sbi, segno);
*newseg = segno;
spin_unlock(&free_i->segmap_lock);
}
static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
struct summary_footer *sum_footer;
curseg->segno = curseg->next_segno;
curseg->zone = GET_ZONE_FROM_SEG(sbi, curseg->segno);
curseg->next_blkoff = 0;
curseg->next_segno = NULL_SEGNO;
sum_footer = &(curseg->sum_blk->footer);
memset(sum_footer, 0, sizeof(struct summary_footer));
if (IS_DATASEG(type))
SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
if (IS_NODESEG(type))
SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
__set_sit_entry_type(sbi, type, curseg->segno, modified);
}
static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
{
/* if segs_per_sec is large than 1, we need to keep original policy. */
if (sbi->segs_per_sec != 1)
return CURSEG_I(sbi, type)->segno;
if (type == CURSEG_HOT_DATA || IS_NODESEG(type))
return 0;
if (SIT_I(sbi)->last_victim[ALLOC_NEXT])
return SIT_I(sbi)->last_victim[ALLOC_NEXT];
return CURSEG_I(sbi, type)->segno;
}
/*
* Allocate a current working segment.
* This function always allocates a free segment in LFS manner.
*/
static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int segno = curseg->segno;
int dir = ALLOC_LEFT;
write_sum_page(sbi, curseg->sum_blk,
GET_SUM_BLOCK(sbi, segno));
if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
dir = ALLOC_RIGHT;
if (test_opt(sbi, NOHEAP))
dir = ALLOC_RIGHT;
segno = __get_next_segno(sbi, type);
get_new_segment(sbi, &segno, new_sec, dir);
curseg->next_segno = segno;
reset_curseg(sbi, type, 1);
curseg->alloc_type = LFS;
}
static void __next_free_blkoff(struct f2fs_sb_info *sbi,
struct curseg_info *seg, block_t start)
{
struct seg_entry *se = get_seg_entry(sbi, seg->segno);
int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
unsigned long *target_map = SIT_I(sbi)->tmp_map;
unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
int i, pos;
for (i = 0; i < entries; i++)
target_map[i] = ckpt_map[i] | cur_map[i];
pos = __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
seg->next_blkoff = pos;
}
/*
* If a segment is written by LFS manner, next block offset is just obtained
* by increasing the current block offset. However, if a segment is written by
* SSR manner, next block offset obtained by calling __next_free_blkoff
*/
static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
struct curseg_info *seg)
{
if (seg->alloc_type == SSR)
__next_free_blkoff(sbi, seg, seg->next_blkoff + 1);
else
seg->next_blkoff++;
}
/*
* This function always allocates a used segment(from dirty seglist) by SSR
* manner, so it should recover the existing segment information of valid blocks
*/
static void change_curseg(struct f2fs_sb_info *sbi, int type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int new_segno = curseg->next_segno;
struct f2fs_summary_block *sum_node;
struct page *sum_page;
write_sum_page(sbi, curseg->sum_blk,
GET_SUM_BLOCK(sbi, curseg->segno));
__set_test_and_inuse(sbi, new_segno);
mutex_lock(&dirty_i->seglist_lock);
__remove_dirty_segment(sbi, new_segno, PRE);
__remove_dirty_segment(sbi, new_segno, DIRTY);
mutex_unlock(&dirty_i->seglist_lock);
reset_curseg(sbi, type, 1);
curseg->alloc_type = SSR;
__next_free_blkoff(sbi, curseg, 0);
sum_page = get_sum_page(sbi, new_segno);
sum_node = (struct f2fs_summary_block *)page_address(sum_page);
memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
f2fs_put_page(sum_page, 1);
}
static int get_ssr_segment(struct f2fs_sb_info *sbi, int type)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
unsigned segno = NULL_SEGNO;
int i, cnt;
bool reversed = false;
/* need_SSR() already forces to do this */
if (v_ops->get_victim(sbi, &segno, BG_GC, type, SSR)) {
curseg->next_segno = segno;
return 1;
}
/* For node segments, let's do SSR more intensively */
if (IS_NODESEG(type)) {
if (type >= CURSEG_WARM_NODE) {
reversed = true;
i = CURSEG_COLD_NODE;
} else {
i = CURSEG_HOT_NODE;
}
cnt = NR_CURSEG_NODE_TYPE;
} else {
if (type >= CURSEG_WARM_DATA) {
reversed = true;
i = CURSEG_COLD_DATA;
} else {
i = CURSEG_HOT_DATA;
}
cnt = NR_CURSEG_DATA_TYPE;
}
for (; cnt-- > 0; reversed ? i-- : i++) {
if (i == type)
continue;
if (v_ops->get_victim(sbi, &segno, BG_GC, i, SSR)) {
curseg->next_segno = segno;
return 1;
}
}
return 0;
}
/*
* flush out current segment and replace it with new segment
* This function should be returned with success, otherwise BUG
*/
static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
int type, bool force)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
if (force)
new_curseg(sbi, type, true);
else if (!is_set_ckpt_flags(sbi, CP_CRC_RECOVERY_FLAG) &&
type == CURSEG_WARM_NODE)
new_curseg(sbi, type, false);
else if (curseg->alloc_type == LFS && is_next_segment_free(sbi, type))
new_curseg(sbi, type, false);
else if (need_SSR(sbi) && get_ssr_segment(sbi, type))
change_curseg(sbi, type);
else
new_curseg(sbi, type, false);
stat_inc_seg_type(sbi, curseg);
}
void allocate_new_segments(struct f2fs_sb_info *sbi)
{
struct curseg_info *curseg;
unsigned int old_segno;
int i;
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
curseg = CURSEG_I(sbi, i);
old_segno = curseg->segno;
SIT_I(sbi)->s_ops->allocate_segment(sbi, i, true);
locate_dirty_segment(sbi, old_segno);
}
}
static const struct segment_allocation default_salloc_ops = {
.allocate_segment = allocate_segment_by_default,
};
bool exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc)
{
__u64 trim_start = cpc->trim_start;
bool has_candidate = false;
mutex_lock(&SIT_I(sbi)->sentry_lock);
for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++) {
if (add_discard_addrs(sbi, cpc, true)) {
has_candidate = true;
break;
}
}
mutex_unlock(&SIT_I(sbi)->sentry_lock);
cpc->trim_start = trim_start;
return has_candidate;
}
int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
{
__u64 start = F2FS_BYTES_TO_BLK(range->start);
__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
unsigned int start_segno, end_segno;
struct cp_control cpc;
int err = 0;
if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
return -EINVAL;
cpc.trimmed = 0;
if (end <= MAIN_BLKADDR(sbi))
goto out;
if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
f2fs_msg(sbi->sb, KERN_WARNING,
"Found FS corruption, run fsck to fix.");
goto out;
}
/* start/end segment number in main_area */
start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
GET_SEGNO(sbi, end);
cpc.reason = CP_DISCARD;
cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
/* do checkpoint to issue discard commands safely */
for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {
cpc.trim_start = start_segno;
if (sbi->discard_blks == 0)
break;
else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))
cpc.trim_end = end_segno;
else
cpc.trim_end = min_t(unsigned int,
rounddown(start_segno +
BATCHED_TRIM_SEGMENTS(sbi),
sbi->segs_per_sec) - 1, end_segno);
mutex_lock(&sbi->gc_mutex);
err = write_checkpoint(sbi, &cpc);
mutex_unlock(&sbi->gc_mutex);
if (err)
break;
schedule();
}
/* It's time to issue all the filed discards */
mark_discard_range_all(sbi);
f2fs_wait_discard_bios(sbi);
out:
range->len = F2FS_BLK_TO_BYTES(cpc.trimmed);
return err;
}
static bool __has_curseg_space(struct f2fs_sb_info *sbi, int type)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
if (curseg->next_blkoff < sbi->blocks_per_seg)
return true;
return false;
}
static int __get_segment_type_2(struct f2fs_io_info *fio)
{
if (fio->type == DATA)
return CURSEG_HOT_DATA;
else
return CURSEG_HOT_NODE;
}
static int __get_segment_type_4(struct f2fs_io_info *fio)
{
if (fio->type == DATA) {
struct inode *inode = fio->page->mapping->host;
if (S_ISDIR(inode->i_mode))
return CURSEG_HOT_DATA;
else
return CURSEG_COLD_DATA;
} else {
if (IS_DNODE(fio->page) && is_cold_node(fio->page))
return CURSEG_WARM_NODE;
else
return CURSEG_COLD_NODE;
}
}
static int __get_segment_type_6(struct f2fs_io_info *fio)
{
if (fio->type == DATA) {
struct inode *inode = fio->page->mapping->host;
if (is_cold_data(fio->page) || file_is_cold(inode))
return CURSEG_COLD_DATA;
if (is_inode_flag_set(inode, FI_HOT_DATA))
return CURSEG_HOT_DATA;
return CURSEG_WARM_DATA;
} else {
if (IS_DNODE(fio->page))
return is_cold_node(fio->page) ? CURSEG_WARM_NODE :
CURSEG_HOT_NODE;
return CURSEG_COLD_NODE;
}
}
static int __get_segment_type(struct f2fs_io_info *fio)
{
int type = 0;
switch (fio->sbi->active_logs) {
case 2:
type = __get_segment_type_2(fio);
break;
case 4:
type = __get_segment_type_4(fio);
break;
case 6:
type = __get_segment_type_6(fio);
break;
default:
f2fs_bug_on(fio->sbi, true);
}
if (IS_HOT(type))
fio->temp = HOT;
else if (IS_WARM(type))
fio->temp = WARM;
else
fio->temp = COLD;
return type;
}
void allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
block_t old_blkaddr, block_t *new_blkaddr,
struct f2fs_summary *sum, int type,
struct f2fs_io_info *fio, bool add_list)
{
struct sit_info *sit_i = SIT_I(sbi);
struct curseg_info *curseg = CURSEG_I(sbi, type);
mutex_lock(&curseg->curseg_mutex);
mutex_lock(&sit_i->sentry_lock);
*new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
f2fs_wait_discard_bio(sbi, *new_blkaddr);
/*
* __add_sum_entry should be resided under the curseg_mutex
* because, this function updates a summary entry in the
* current summary block.
*/
__add_sum_entry(sbi, type, sum);
__refresh_next_blkoff(sbi, curseg);
stat_inc_block_count(sbi, curseg);
if (!__has_curseg_space(sbi, type))
sit_i->s_ops->allocate_segment(sbi, type, false);
/*
* SIT information should be updated after segment allocation,
* since we need to keep dirty segments precisely under SSR.
*/
refresh_sit_entry(sbi, old_blkaddr, *new_blkaddr);
mutex_unlock(&sit_i->sentry_lock);
if (page && IS_NODESEG(type)) {
fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
f2fs_inode_chksum_set(sbi, page);
}
if (add_list) {
struct f2fs_bio_info *io;
INIT_LIST_HEAD(&fio->list);
fio->in_list = true;
io = sbi->write_io[fio->type] + fio->temp;
spin_lock(&io->io_lock);
list_add_tail(&fio->list, &io->io_list);
spin_unlock(&io->io_lock);
}
mutex_unlock(&curseg->curseg_mutex);
}
static void do_write_page(struct f2fs_summary *sum, struct f2fs_io_info *fio)
{
int type = __get_segment_type(fio);
int err;
reallocate:
allocate_data_block(fio->sbi, fio->page, fio->old_blkaddr,
&fio->new_blkaddr, sum, type, fio, true);
/* writeout dirty page into bdev */
err = f2fs_submit_page_write(fio);
if (err == -EAGAIN) {
fio->old_blkaddr = fio->new_blkaddr;
goto reallocate;
}
}
void write_meta_page(struct f2fs_sb_info *sbi, struct page *page,
enum iostat_type io_type)
{
struct f2fs_io_info fio = {
.sbi = sbi,
.type = META,
.op = REQ_OP_WRITE,
.op_flags = REQ_SYNC | REQ_META | REQ_PRIO,
.old_blkaddr = page->index,
.new_blkaddr = page->index,
.page = page,
.encrypted_page = NULL,
.in_list = false,
};
if (unlikely(page->index >= MAIN_BLKADDR(sbi)))
fio.op_flags &= ~REQ_META;
set_page_writeback(page);
f2fs_submit_page_write(&fio);
f2fs_update_iostat(sbi, io_type, F2FS_BLKSIZE);
}
void write_node_page(unsigned int nid, struct f2fs_io_info *fio)
{
struct f2fs_summary sum;
set_summary(&sum, nid, 0, 0);
do_write_page(&sum, fio);
f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
}
void write_data_page(struct dnode_of_data *dn, struct f2fs_io_info *fio)
{
struct f2fs_sb_info *sbi = fio->sbi;
struct f2fs_summary sum;
struct node_info ni;
f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
get_node_info(sbi, dn->nid, &ni);
set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
do_write_page(&sum, fio);
f2fs_update_data_blkaddr(dn, fio->new_blkaddr);
f2fs_update_iostat(sbi, fio->io_type, F2FS_BLKSIZE);
}
int rewrite_data_page(struct f2fs_io_info *fio)
{
int err;
fio->new_blkaddr = fio->old_blkaddr;
stat_inc_inplace_blocks(fio->sbi);
err = f2fs_submit_page_bio(fio);
f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
return err;
}
void __f2fs_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
block_t old_blkaddr, block_t new_blkaddr,
bool recover_curseg, bool recover_newaddr)
{
struct sit_info *sit_i = SIT_I(sbi);
struct curseg_info *curseg;
unsigned int segno, old_cursegno;
struct seg_entry *se;
int type;
unsigned short old_blkoff;
segno = GET_SEGNO(sbi, new_blkaddr);
se = get_seg_entry(sbi, segno);
type = se->type;
if (!recover_curseg) {
/* for recovery flow */
if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
if (old_blkaddr == NULL_ADDR)
type = CURSEG_COLD_DATA;
else
type = CURSEG_WARM_DATA;
}
} else {
if (!IS_CURSEG(sbi, segno))
type = CURSEG_WARM_DATA;
}
curseg = CURSEG_I(sbi, type);
mutex_lock(&curseg->curseg_mutex);
mutex_lock(&sit_i->sentry_lock);
old_cursegno = curseg->segno;
old_blkoff = curseg->next_blkoff;
/* change the current segment */
if (segno != curseg->segno) {
curseg->next_segno = segno;
change_curseg(sbi, type);
}
curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
__add_sum_entry(sbi, type, sum);
if (!recover_curseg || recover_newaddr)
update_sit_entry(sbi, new_blkaddr, 1);
if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
update_sit_entry(sbi, old_blkaddr, -1);
locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr));
locate_dirty_segment(sbi, old_cursegno);
if (recover_curseg) {
if (old_cursegno != curseg->segno) {
curseg->next_segno = old_cursegno;
change_curseg(sbi, type);
}
curseg->next_blkoff = old_blkoff;
}
mutex_unlock(&sit_i->sentry_lock);
mutex_unlock(&curseg->curseg_mutex);
}
void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn,
block_t old_addr, block_t new_addr,
unsigned char version, bool recover_curseg,
bool recover_newaddr)
{
struct f2fs_summary sum;
set_summary(&sum, dn->nid, dn->ofs_in_node, version);
__f2fs_replace_block(sbi, &sum, old_addr, new_addr,
recover_curseg, recover_newaddr);
f2fs_update_data_blkaddr(dn, new_addr);
}
void f2fs_wait_on_page_writeback(struct page *page,
enum page_type type, bool ordered)
{
if (PageWriteback(page)) {
struct f2fs_sb_info *sbi = F2FS_P_SB(page);
f2fs_submit_merged_write_cond(sbi, page->mapping->host,
0, page->index, type);
if (ordered)
wait_on_page_writeback(page);
else
wait_for_stable_page(page);
}
}
void f2fs_wait_on_block_writeback(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct page *cpage;
if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
return;
cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
if (cpage) {
f2fs_wait_on_page_writeback(cpage, DATA, true);
f2fs_put_page(cpage, 1);
}
}
static int read_compacted_summaries(struct f2fs_sb_info *sbi)
{
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct curseg_info *seg_i;
unsigned char *kaddr;
struct page *page;
block_t start;
int i, j, offset;
start = start_sum_block(sbi);
page = get_meta_page(sbi, start++);
kaddr = (unsigned char *)page_address(page);
/* Step 1: restore nat cache */
seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
memcpy(seg_i->journal, kaddr, SUM_JOURNAL_SIZE);
/* Step 2: restore sit cache */
seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
memcpy(seg_i->journal, kaddr + SUM_JOURNAL_SIZE, SUM_JOURNAL_SIZE);
offset = 2 * SUM_JOURNAL_SIZE;
/* Step 3: restore summary entries */
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
unsigned short blk_off;
unsigned int segno;
seg_i = CURSEG_I(sbi, i);
segno = le32_to_cpu(ckpt->cur_data_segno[i]);
blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
seg_i->next_segno = segno;
reset_curseg(sbi, i, 0);
seg_i->alloc_type = ckpt->alloc_type[i];
seg_i->next_blkoff = blk_off;
if (seg_i->alloc_type == SSR)
blk_off = sbi->blocks_per_seg;
for (j = 0; j < blk_off; j++) {
struct f2fs_summary *s;
s = (struct f2fs_summary *)(kaddr + offset);
seg_i->sum_blk->entries[j] = *s;
offset += SUMMARY_SIZE;
if (offset + SUMMARY_SIZE <= PAGE_SIZE -
SUM_FOOTER_SIZE)
continue;
f2fs_put_page(page, 1);
page = NULL;
page = get_meta_page(sbi, start++);
kaddr = (unsigned char *)page_address(page);
offset = 0;
}
}
f2fs_put_page(page, 1);
return 0;
}
static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
{
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_summary_block *sum;
struct curseg_info *curseg;
struct page *new;
unsigned short blk_off;
unsigned int segno = 0;
block_t blk_addr = 0;
/* get segment number and block addr */
if (IS_DATASEG(type)) {
segno = le32_to_cpu(ckpt->cur_data_segno[type]);
blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
CURSEG_HOT_DATA]);
if (__exist_node_summaries(sbi))
blk_addr = sum_blk_addr(sbi, NR_CURSEG_TYPE, type);
else
blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
} else {
segno = le32_to_cpu(ckpt->cur_node_segno[type -
CURSEG_HOT_NODE]);
blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
CURSEG_HOT_NODE]);
if (__exist_node_summaries(sbi))
blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
type - CURSEG_HOT_NODE);
else
blk_addr = GET_SUM_BLOCK(sbi, segno);
}
new = get_meta_page(sbi, blk_addr);
sum = (struct f2fs_summary_block *)page_address(new);
if (IS_NODESEG(type)) {
if (__exist_node_summaries(sbi)) {
struct f2fs_summary *ns = &sum->entries[0];
int i;
for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
ns->version = 0;
ns->ofs_in_node = 0;
}
} else {
int err;
err = restore_node_summary(sbi, segno, sum);
if (err) {
f2fs_put_page(new, 1);
return err;
}
}
}
/* set uncompleted segment to curseg */
curseg = CURSEG_I(sbi, type);
mutex_lock(&curseg->curseg_mutex);
/* update journal info */
down_write(&curseg->journal_rwsem);
memcpy(curseg->journal, &sum->journal, SUM_JOURNAL_SIZE);
up_write(&curseg->journal_rwsem);
memcpy(curseg->sum_blk->entries, sum->entries, SUM_ENTRY_SIZE);
memcpy(&curseg->sum_blk->footer, &sum->footer, SUM_FOOTER_SIZE);
curseg->next_segno = segno;
reset_curseg(sbi, type, 0);
curseg->alloc_type = ckpt->alloc_type[type];
curseg->next_blkoff = blk_off;
mutex_unlock(&curseg->curseg_mutex);
f2fs_put_page(new, 1);
return 0;
}
static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
{
struct f2fs_journal *sit_j = CURSEG_I(sbi, CURSEG_COLD_DATA)->journal;
struct f2fs_journal *nat_j = CURSEG_I(sbi, CURSEG_HOT_DATA)->journal;
int type = CURSEG_HOT_DATA;
int err;
if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG)) {
int npages = npages_for_summary_flush(sbi, true);
if (npages >= 2)
ra_meta_pages(sbi, start_sum_block(sbi), npages,
META_CP, true);
/* restore for compacted data summary */
if (read_compacted_summaries(sbi))
return -EINVAL;
type = CURSEG_HOT_NODE;
}
if (__exist_node_summaries(sbi))
ra_meta_pages(sbi, sum_blk_addr(sbi, NR_CURSEG_TYPE, type),
NR_CURSEG_TYPE - type, META_CP, true);
for (; type <= CURSEG_COLD_NODE; type++) {
err = read_normal_summaries(sbi, type);
if (err)
return err;
}
/* sanity check for summary blocks */
if (nats_in_cursum(nat_j) > NAT_JOURNAL_ENTRIES ||
sits_in_cursum(sit_j) > SIT_JOURNAL_ENTRIES)
return -EINVAL;
return 0;
}
static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct page *page;
unsigned char *kaddr;
struct f2fs_summary *summary;
struct curseg_info *seg_i;
int written_size = 0;
int i, j;
page = grab_meta_page(sbi, blkaddr++);
kaddr = (unsigned char *)page_address(page);
/* Step 1: write nat cache */
seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
memcpy(kaddr, seg_i->journal, SUM_JOURNAL_SIZE);
written_size += SUM_JOURNAL_SIZE;
/* Step 2: write sit cache */
seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
memcpy(kaddr + written_size, seg_i->journal, SUM_JOURNAL_SIZE);
written_size += SUM_JOURNAL_SIZE;
/* Step 3: write summary entries */
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
unsigned short blkoff;
seg_i = CURSEG_I(sbi, i);
if (sbi->ckpt->alloc_type[i] == SSR)
blkoff = sbi->blocks_per_seg;
else
blkoff = curseg_blkoff(sbi, i);
for (j = 0; j < blkoff; j++) {
if (!page) {
page = grab_meta_page(sbi, blkaddr++);
kaddr = (unsigned char *)page_address(page);
written_size = 0;
}
summary = (struct f2fs_summary *)(kaddr + written_size);
*summary = seg_i->sum_blk->entries[j];
written_size += SUMMARY_SIZE;
if (written_size + SUMMARY_SIZE <= PAGE_SIZE -
SUM_FOOTER_SIZE)
continue;
set_page_dirty(page);
f2fs_put_page(page, 1);
page = NULL;
}
}
if (page) {
set_page_dirty(page);
f2fs_put_page(page, 1);
}
}
static void write_normal_summaries(struct f2fs_sb_info *sbi,
block_t blkaddr, int type)
{
int i, end;
if (IS_DATASEG(type))
end = type + NR_CURSEG_DATA_TYPE;
else
end = type + NR_CURSEG_NODE_TYPE;
for (i = type; i < end; i++)
write_current_sum_page(sbi, i, blkaddr + (i - type));
}
void write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
{
if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG))
write_compacted_summaries(sbi, start_blk);
else
write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
}
void write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
{
write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
}
int lookup_journal_in_cursum(struct f2fs_journal *journal, int type,
unsigned int val, int alloc)
{
int i;
if (type == NAT_JOURNAL) {
for (i = 0; i < nats_in_cursum(journal); i++) {
if (le32_to_cpu(nid_in_journal(journal, i)) == val)
return i;
}
if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL))
return update_nats_in_cursum(journal, 1);
} else if (type == SIT_JOURNAL) {
for (i = 0; i < sits_in_cursum(journal); i++)
if (le32_to_cpu(segno_in_journal(journal, i)) == val)
return i;
if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL))
return update_sits_in_cursum(journal, 1);
}
return -1;
}
static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
unsigned int segno)
{
return get_meta_page(sbi, current_sit_addr(sbi, segno));
}
static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
unsigned int start)
{
struct sit_info *sit_i = SIT_I(sbi);
struct page *src_page, *dst_page;
pgoff_t src_off, dst_off;
void *src_addr, *dst_addr;
src_off = current_sit_addr(sbi, start);
dst_off = next_sit_addr(sbi, src_off);
/* get current sit block page without lock */
src_page = get_meta_page(sbi, src_off);
dst_page = grab_meta_page(sbi, dst_off);
f2fs_bug_on(sbi, PageDirty(src_page));
src_addr = page_address(src_page);
dst_addr = page_address(dst_page);
memcpy(dst_addr, src_addr, PAGE_SIZE);
set_page_dirty(dst_page);
f2fs_put_page(src_page, 1);
set_to_next_sit(sit_i, start);
return dst_page;
}
static struct sit_entry_set *grab_sit_entry_set(void)
{
struct sit_entry_set *ses =
f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_NOFS);
ses->entry_cnt = 0;
INIT_LIST_HEAD(&ses->set_list);
return ses;
}
static void release_sit_entry_set(struct sit_entry_set *ses)
{
list_del(&ses->set_list);
kmem_cache_free(sit_entry_set_slab, ses);
}
static void adjust_sit_entry_set(struct sit_entry_set *ses,
struct list_head *head)
{
struct sit_entry_set *next = ses;
if (list_is_last(&ses->set_list, head))
return;
list_for_each_entry_continue(next, head, set_list)
if (ses->entry_cnt <= next->entry_cnt)
break;
list_move_tail(&ses->set_list, &next->set_list);
}
static void add_sit_entry(unsigned int segno, struct list_head *head)
{
struct sit_entry_set *ses;
unsigned int start_segno = START_SEGNO(segno);
list_for_each_entry(ses, head, set_list) {
if (ses->start_segno == start_segno) {
ses->entry_cnt++;
adjust_sit_entry_set(ses, head);
return;
}
}
ses = grab_sit_entry_set();
ses->start_segno = start_segno;
ses->entry_cnt++;
list_add(&ses->set_list, head);
}
static void add_sits_in_set(struct f2fs_sb_info *sbi)
{
struct f2fs_sm_info *sm_info = SM_I(sbi);
struct list_head *set_list = &sm_info->sit_entry_set;
unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
unsigned int segno;
for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
add_sit_entry(segno, set_list);
}
static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
{
struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
struct f2fs_journal *journal = curseg->journal;
int i;
down_write(&curseg->journal_rwsem);
for (i = 0; i < sits_in_cursum(journal); i++) {
unsigned int segno;
bool dirtied;
segno = le32_to_cpu(segno_in_journal(journal, i));
dirtied = __mark_sit_entry_dirty(sbi, segno);
if (!dirtied)
add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
}
update_sits_in_cursum(journal, -i);
up_write(&curseg->journal_rwsem);
}
/*
* CP calls this function, which flushes SIT entries including sit_journal,
* and moves prefree segs to free segs.
*/
void flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
struct f2fs_journal *journal = curseg->journal;
struct sit_entry_set *ses, *tmp;
struct list_head *head = &SM_I(sbi)->sit_entry_set;
bool to_journal = true;
struct seg_entry *se;
mutex_lock(&sit_i->sentry_lock);
if (!sit_i->dirty_sentries)
goto out;
/*
* add and account sit entries of dirty bitmap in sit entry
* set temporarily
*/
add_sits_in_set(sbi);
/*
* if there are no enough space in journal to store dirty sit
* entries, remove all entries from journal and add and account
* them in sit entry set.
*/
if (!__has_cursum_space(journal, sit_i->dirty_sentries, SIT_JOURNAL))
remove_sits_in_journal(sbi);
/*
* there are two steps to flush sit entries:
* #1, flush sit entries to journal in current cold data summary block.
* #2, flush sit entries to sit page.
*/
list_for_each_entry_safe(ses, tmp, head, set_list) {
struct page *page = NULL;
struct f2fs_sit_block *raw_sit = NULL;
unsigned int start_segno = ses->start_segno;
unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
(unsigned long)MAIN_SEGS(sbi));
unsigned int segno = start_segno;
if (to_journal &&
!__has_cursum_space(journal, ses->entry_cnt, SIT_JOURNAL))
to_journal = false;
if (to_journal) {
down_write(&curseg->journal_rwsem);
} else {
page = get_next_sit_page(sbi, start_segno);
raw_sit = page_address(page);
}
/* flush dirty sit entries in region of current sit set */
for_each_set_bit_from(segno, bitmap, end) {
int offset, sit_offset;
se = get_seg_entry(sbi, segno);
/* add discard candidates */
if (!(cpc->reason & CP_DISCARD)) {
cpc->trim_start = segno;
add_discard_addrs(sbi, cpc, false);
}
if (to_journal) {
offset = lookup_journal_in_cursum(journal,
SIT_JOURNAL, segno, 1);
f2fs_bug_on(sbi, offset < 0);
segno_in_journal(journal, offset) =
cpu_to_le32(segno);
seg_info_to_raw_sit(se,
&sit_in_journal(journal, offset));
} else {
sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
seg_info_to_raw_sit(se,
&raw_sit->entries[sit_offset]);
}
__clear_bit(segno, bitmap);
sit_i->dirty_sentries--;
ses->entry_cnt--;
}
if (to_journal)
up_write(&curseg->journal_rwsem);
else
f2fs_put_page(page, 1);
f2fs_bug_on(sbi, ses->entry_cnt);
release_sit_entry_set(ses);
}
f2fs_bug_on(sbi, !list_empty(head));
f2fs_bug_on(sbi, sit_i->dirty_sentries);
out:
if (cpc->reason & CP_DISCARD) {
__u64 trim_start = cpc->trim_start;
for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
add_discard_addrs(sbi, cpc, false);
cpc->trim_start = trim_start;
}
mutex_unlock(&sit_i->sentry_lock);
set_prefree_as_free_segments(sbi);
}
static int build_sit_info(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct sit_info *sit_i;
unsigned int sit_segs, start;
char *src_bitmap;
unsigned int bitmap_size;
/* allocate memory for SIT information */
sit_i = kzalloc(sizeof(struct sit_info), GFP_KERNEL);
if (!sit_i)
return -ENOMEM;
SM_I(sbi)->sit_info = sit_i;
sit_i->sentries = kvzalloc(MAIN_SEGS(sbi) *
sizeof(struct seg_entry), GFP_KERNEL);
if (!sit_i->sentries)
return -ENOMEM;
bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
sit_i->dirty_sentries_bitmap = kvzalloc(bitmap_size, GFP_KERNEL);
if (!sit_i->dirty_sentries_bitmap)
return -ENOMEM;
for (start = 0; start < MAIN_SEGS(sbi); start++) {
sit_i->sentries[start].cur_valid_map
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
sit_i->sentries[start].ckpt_valid_map
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->sentries[start].cur_valid_map ||
!sit_i->sentries[start].ckpt_valid_map)
return -ENOMEM;
#ifdef CONFIG_F2FS_CHECK_FS
sit_i->sentries[start].cur_valid_map_mir
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->sentries[start].cur_valid_map_mir)
return -ENOMEM;
#endif
if (f2fs_discard_en(sbi)) {
sit_i->sentries[start].discard_map
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->sentries[start].discard_map)
return -ENOMEM;
}
}
sit_i->tmp_map = kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->tmp_map)
return -ENOMEM;
if (sbi->segs_per_sec > 1) {
sit_i->sec_entries = kvzalloc(MAIN_SECS(sbi) *
sizeof(struct sec_entry), GFP_KERNEL);
if (!sit_i->sec_entries)
return -ENOMEM;
}
/* get information related with SIT */
sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
/* setup SIT bitmap from ckeckpoint pack */
bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
sit_i->sit_bitmap = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
if (!sit_i->sit_bitmap)
return -ENOMEM;
#ifdef CONFIG_F2FS_CHECK_FS
sit_i->sit_bitmap_mir = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
if (!sit_i->sit_bitmap_mir)
return -ENOMEM;
#endif
/* init SIT information */
sit_i->s_ops = &default_salloc_ops;
sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
sit_i->written_valid_blocks = 0;
sit_i->bitmap_size = bitmap_size;
sit_i->dirty_sentries = 0;
sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
sit_i->mounted_time = ktime_get_real_seconds();
mutex_init(&sit_i->sentry_lock);
return 0;
}
static int build_free_segmap(struct f2fs_sb_info *sbi)
{
struct free_segmap_info *free_i;
unsigned int bitmap_size, sec_bitmap_size;
/* allocate memory for free segmap information */
free_i = kzalloc(sizeof(struct free_segmap_info), GFP_KERNEL);
if (!free_i)
return -ENOMEM;
SM_I(sbi)->free_info = free_i;
bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
free_i->free_segmap = kvmalloc(bitmap_size, GFP_KERNEL);
if (!free_i->free_segmap)
return -ENOMEM;
sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
free_i->free_secmap = kvmalloc(sec_bitmap_size, GFP_KERNEL);
if (!free_i->free_secmap)
return -ENOMEM;
/* set all segments as dirty temporarily */
memset(free_i->free_segmap, 0xff, bitmap_size);
memset(free_i->free_secmap, 0xff, sec_bitmap_size);
/* init free segmap information */
free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
free_i->free_segments = 0;
free_i->free_sections = 0;
spin_lock_init(&free_i->segmap_lock);
return 0;
}
static int build_curseg(struct f2fs_sb_info *sbi)
{
struct curseg_info *array;
int i;
array = kcalloc(NR_CURSEG_TYPE, sizeof(*array), GFP_KERNEL);
if (!array)
return -ENOMEM;
SM_I(sbi)->curseg_array = array;
for (i = 0; i < NR_CURSEG_TYPE; i++) {
mutex_init(&array[i].curseg_mutex);
array[i].sum_blk = kzalloc(PAGE_SIZE, GFP_KERNEL);
if (!array[i].sum_blk)
return -ENOMEM;
init_rwsem(&array[i].journal_rwsem);
array[i].journal = kzalloc(sizeof(struct f2fs_journal),
GFP_KERNEL);
if (!array[i].journal)
return -ENOMEM;
array[i].segno = NULL_SEGNO;
array[i].next_blkoff = 0;
}
return restore_curseg_summaries(sbi);
}
static void build_sit_entries(struct f2fs_sb_info *sbi)
{
struct sit_info *sit_i = SIT_I(sbi);
struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
struct f2fs_journal *journal = curseg->journal;
struct seg_entry *se;
struct f2fs_sit_entry sit;
int sit_blk_cnt = SIT_BLK_CNT(sbi);
unsigned int i, start, end;
unsigned int readed, start_blk = 0;
do {
readed = ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES,
META_SIT, true);
start = start_blk * sit_i->sents_per_block;
end = (start_blk + readed) * sit_i->sents_per_block;
for (; start < end && start < MAIN_SEGS(sbi); start++) {
struct f2fs_sit_block *sit_blk;
struct page *page;
se = &sit_i->sentries[start];
page = get_current_sit_page(sbi, start);
sit_blk = (struct f2fs_sit_block *)page_address(page);
sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
f2fs_put_page(page, 1);
check_block_count(sbi, start, &sit);
seg_info_from_raw_sit(se, &sit);
/* build discard map only one time */
if (f2fs_discard_en(sbi)) {
if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
memset(se->discard_map, 0xff,
SIT_VBLOCK_MAP_SIZE);
} else {
memcpy(se->discard_map,
se->cur_valid_map,
SIT_VBLOCK_MAP_SIZE);
sbi->discard_blks +=
sbi->blocks_per_seg -
se->valid_blocks;
}
}
if (sbi->segs_per_sec > 1)
get_sec_entry(sbi, start)->valid_blocks +=
se->valid_blocks;
}
start_blk += readed;
} while (start_blk < sit_blk_cnt);
down_read(&curseg->journal_rwsem);
for (i = 0; i < sits_in_cursum(journal); i++) {
unsigned int old_valid_blocks;
start = le32_to_cpu(segno_in_journal(journal, i));
se = &sit_i->sentries[start];
sit = sit_in_journal(journal, i);
old_valid_blocks = se->valid_blocks;
check_block_count(sbi, start, &sit);
seg_info_from_raw_sit(se, &sit);
if (f2fs_discard_en(sbi)) {
if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
memset(se->discard_map, 0xff,
SIT_VBLOCK_MAP_SIZE);
} else {
memcpy(se->discard_map, se->cur_valid_map,
SIT_VBLOCK_MAP_SIZE);
sbi->discard_blks += old_valid_blocks -
se->valid_blocks;
}
}
if (sbi->segs_per_sec > 1)
get_sec_entry(sbi, start)->valid_blocks +=
se->valid_blocks - old_valid_blocks;
}
up_read(&curseg->journal_rwsem);
}
static void init_free_segmap(struct f2fs_sb_info *sbi)
{
unsigned int start;
int type;
for (start = 0; start < MAIN_SEGS(sbi); start++) {
struct seg_entry *sentry = get_seg_entry(sbi, start);
if (!sentry->valid_blocks)
__set_free(sbi, start);
else
SIT_I(sbi)->written_valid_blocks +=
sentry->valid_blocks;
}
/* set use the current segments */
for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
struct curseg_info *curseg_t = CURSEG_I(sbi, type);
__set_test_and_inuse(sbi, curseg_t->segno);
}
}
static void init_dirty_segmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
struct free_segmap_info *free_i = FREE_I(sbi);
unsigned int segno = 0, offset = 0;
unsigned short valid_blocks;
while (1) {
/* find dirty segment based on free segmap */
segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
if (segno >= MAIN_SEGS(sbi))
break;
offset = segno + 1;
valid_blocks = get_valid_blocks(sbi, segno, false);
if (valid_blocks == sbi->blocks_per_seg || !valid_blocks)
continue;
if (valid_blocks > sbi->blocks_per_seg) {
f2fs_bug_on(sbi, 1);
continue;
}
mutex_lock(&dirty_i->seglist_lock);
__locate_dirty_segment(sbi, segno, DIRTY);
mutex_unlock(&dirty_i->seglist_lock);
}
}
static int init_victim_secmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
dirty_i->victim_secmap = kvzalloc(bitmap_size, GFP_KERNEL);
if (!dirty_i->victim_secmap)
return -ENOMEM;
return 0;
}
static int build_dirty_segmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i;
unsigned int bitmap_size, i;
/* allocate memory for dirty segments list information */
dirty_i = kzalloc(sizeof(struct dirty_seglist_info), GFP_KERNEL);
if (!dirty_i)
return -ENOMEM;
SM_I(sbi)->dirty_info = dirty_i;
mutex_init(&dirty_i->seglist_lock);
bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
for (i = 0; i < NR_DIRTY_TYPE; i++) {
dirty_i->dirty_segmap[i] = kvzalloc(bitmap_size, GFP_KERNEL);
if (!dirty_i->dirty_segmap[i])
return -ENOMEM;
}
init_dirty_segmap(sbi);
return init_victim_secmap(sbi);
}
/*
* Update min, max modified time for cost-benefit GC algorithm
*/
static void init_min_max_mtime(struct f2fs_sb_info *sbi)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned int segno;
mutex_lock(&sit_i->sentry_lock);
sit_i->min_mtime = LLONG_MAX;
for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
unsigned int i;
unsigned long long mtime = 0;
for (i = 0; i < sbi->segs_per_sec; i++)
mtime += get_seg_entry(sbi, segno + i)->mtime;
mtime = div_u64(mtime, sbi->segs_per_sec);
if (sit_i->min_mtime > mtime)
sit_i->min_mtime = mtime;
}
sit_i->max_mtime = get_mtime(sbi);
mutex_unlock(&sit_i->sentry_lock);
}
int build_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_sm_info *sm_info;
int err;
sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
if (!sm_info)
return -ENOMEM;
/* init sm info */
sbi->sm_info = sm_info;
sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
sm_info->rec_prefree_segments = sm_info->main_segments *
DEF_RECLAIM_PREFREE_SEGMENTS / 100;
if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
if (!test_opt(sbi, LFS))
sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
INIT_LIST_HEAD(&sm_info->sit_entry_set);
if (!f2fs_readonly(sbi->sb)) {
err = create_flush_cmd_control(sbi);
if (err)
return err;
}
err = create_discard_cmd_control(sbi);
if (err)
return err;
err = build_sit_info(sbi);
if (err)
return err;
err = build_free_segmap(sbi);
if (err)
return err;
err = build_curseg(sbi);
if (err)
return err;
/* reinit free segmap based on SIT */
build_sit_entries(sbi);
init_free_segmap(sbi);
err = build_dirty_segmap(sbi);
if (err)
return err;
init_min_max_mtime(sbi);
return 0;
}
static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
enum dirty_type dirty_type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
mutex_lock(&dirty_i->seglist_lock);
kvfree(dirty_i->dirty_segmap[dirty_type]);
dirty_i->nr_dirty[dirty_type] = 0;
mutex_unlock(&dirty_i->seglist_lock);
}
static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
kvfree(dirty_i->victim_secmap);
}
static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
int i;
if (!dirty_i)
return;
/* discard pre-free/dirty segments list */
for (i = 0; i < NR_DIRTY_TYPE; i++)
discard_dirty_segmap(sbi, i);
destroy_victim_secmap(sbi);
SM_I(sbi)->dirty_info = NULL;
kfree(dirty_i);
}
static void destroy_curseg(struct f2fs_sb_info *sbi)
{
struct curseg_info *array = SM_I(sbi)->curseg_array;
int i;
if (!array)
return;
SM_I(sbi)->curseg_array = NULL;
for (i = 0; i < NR_CURSEG_TYPE; i++) {
kfree(array[i].sum_blk);
kfree(array[i].journal);
}
kfree(array);
}
static void destroy_free_segmap(struct f2fs_sb_info *sbi)
{
struct free_segmap_info *free_i = SM_I(sbi)->free_info;
if (!free_i)
return;
SM_I(sbi)->free_info = NULL;
kvfree(free_i->free_segmap);
kvfree(free_i->free_secmap);
kfree(free_i);
}
static void destroy_sit_info(struct f2fs_sb_info *sbi)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned int start;
if (!sit_i)
return;
if (sit_i->sentries) {
for (start = 0; start < MAIN_SEGS(sbi); start++) {
kfree(sit_i->sentries[start].cur_valid_map);
#ifdef CONFIG_F2FS_CHECK_FS
kfree(sit_i->sentries[start].cur_valid_map_mir);
#endif
kfree(sit_i->sentries[start].ckpt_valid_map);
kfree(sit_i->sentries[start].discard_map);
}
}
kfree(sit_i->tmp_map);
kvfree(sit_i->sentries);
kvfree(sit_i->sec_entries);
kvfree(sit_i->dirty_sentries_bitmap);
SM_I(sbi)->sit_info = NULL;
kfree(sit_i->sit_bitmap);
#ifdef CONFIG_F2FS_CHECK_FS
kfree(sit_i->sit_bitmap_mir);
#endif
kfree(sit_i);
}
void destroy_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_sm_info *sm_info = SM_I(sbi);
if (!sm_info)
return;
destroy_flush_cmd_control(sbi, true);
destroy_discard_cmd_control(sbi);
destroy_dirty_segmap(sbi);
destroy_curseg(sbi);
destroy_free_segmap(sbi);
destroy_sit_info(sbi);
sbi->sm_info = NULL;
kfree(sm_info);
}
int __init create_segment_manager_caches(void)
{
discard_entry_slab = f2fs_kmem_cache_create("discard_entry",
sizeof(struct discard_entry));
if (!discard_entry_slab)
goto fail;
discard_cmd_slab = f2fs_kmem_cache_create("discard_cmd",
sizeof(struct discard_cmd));
if (!discard_cmd_slab)
goto destroy_discard_entry;
sit_entry_set_slab = f2fs_kmem_cache_create("sit_entry_set",
sizeof(struct sit_entry_set));
if (!sit_entry_set_slab)
goto destroy_discard_cmd;
inmem_entry_slab = f2fs_kmem_cache_create("inmem_page_entry",
sizeof(struct inmem_pages));
if (!inmem_entry_slab)
goto destroy_sit_entry_set;
return 0;
destroy_sit_entry_set:
kmem_cache_destroy(sit_entry_set_slab);
destroy_discard_cmd:
kmem_cache_destroy(discard_cmd_slab);
destroy_discard_entry:
kmem_cache_destroy(discard_entry_slab);
fail:
return -ENOMEM;
}
void destroy_segment_manager_caches(void)
{
kmem_cache_destroy(sit_entry_set_slab);
kmem_cache_destroy(discard_cmd_slab);
kmem_cache_destroy(discard_entry_slab);
kmem_cache_destroy(inmem_entry_slab);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3012_1 |
crossvul-cpp_data_good_3988_0 | /*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#include "path.h"
#include "posix.h"
#include "repository.h"
#ifdef GIT_WIN32
#include "win32/posix.h"
#include "win32/w32_buffer.h"
#include "win32/w32_util.h"
#include "win32/version.h"
#include <aclapi.h>
#else
#include <dirent.h>
#endif
#include <stdio.h>
#include <ctype.h>
#define LOOKS_LIKE_DRIVE_PREFIX(S) (git__isalpha((S)[0]) && (S)[1] == ':')
#ifdef GIT_WIN32
static bool looks_like_network_computer_name(const char *path, int pos)
{
if (pos < 3)
return false;
if (path[0] != '/' || path[1] != '/')
return false;
while (pos-- > 2) {
if (path[pos] == '/')
return false;
}
return true;
}
#endif
/*
* Based on the Android implementation, BSD licensed.
* http://android.git.kernel.org/
*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
int git_path_basename_r(git_buf *buffer, const char *path)
{
const char *endp, *startp;
int len, result;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
startp = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
/* All slashes becomes "/" */
if (endp == path && *endp == '/') {
startp = "/";
len = 1;
goto Exit;
}
/* Find the start of the base */
startp = endp;
while (startp > path && *(startp - 1) != '/')
startp--;
/* Cast is safe because max path < max int */
len = (int)(endp - startp + 1);
Exit:
result = len;
if (buffer != NULL && git_buf_set(buffer, startp, len) < 0)
return -1;
return result;
}
/*
* Determine if the path is a Windows prefix and, if so, returns
* its actual lentgh. If it is not a prefix, returns -1.
*/
static int win32_prefix_length(const char *path, int len)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
GIT_UNUSED(len);
#else
/*
* Mimic unix behavior where '/.git' returns '/': 'C:/.git' will return
* 'C:/' here
*/
if (len == 2 && LOOKS_LIKE_DRIVE_PREFIX(path))
return 2;
/*
* Similarly checks if we're dealing with a network computer name
* '//computername/.git' will return '//computername/'
*/
if (looks_like_network_computer_name(path, len))
return len;
#endif
return -1;
}
/*
* Based on the Android implementation, BSD licensed.
* Check http://android.git.kernel.org/
*/
int git_path_dirname_r(git_buf *buffer, const char *path)
{
const char *endp;
int is_prefix = 0, len;
/* Empty or NULL string gets treated as "." */
if (path == NULL || *path == '\0') {
path = ".";
len = 1;
goto Exit;
}
/* Strip trailing slashes */
endp = path + strlen(path) - 1;
while (endp > path && *endp == '/')
endp--;
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Find the start of the dir */
while (endp > path && *endp != '/')
endp--;
/* Either the dir is "/" or there are no slashes */
if (endp == path) {
path = (*endp == '/') ? "/" : ".";
len = 1;
goto Exit;
}
do {
endp--;
} while (endp > path && *endp == '/');
if (endp - path + 1 > INT_MAX) {
git_error_set(GIT_ERROR_INVALID, "path too long");
len = -1;
goto Exit;
}
if ((len = win32_prefix_length(path, (int)(endp - path + 1))) > 0) {
is_prefix = 1;
goto Exit;
}
/* Cast is safe because max path < max int */
len = (int)(endp - path + 1);
Exit:
if (buffer) {
if (git_buf_set(buffer, path, len) < 0)
return -1;
if (is_prefix && git_buf_putc(buffer, '/') < 0)
return -1;
}
return len;
}
char *git_path_dirname(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *dirname;
git_path_dirname_r(&buf, path);
dirname = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return dirname;
}
char *git_path_basename(const char *path)
{
git_buf buf = GIT_BUF_INIT;
char *basename;
git_path_basename_r(&buf, path);
basename = git_buf_detach(&buf);
git_buf_dispose(&buf); /* avoid memleak if error occurs */
return basename;
}
size_t git_path_basename_offset(git_buf *buffer)
{
ssize_t slash;
if (!buffer || buffer->size <= 0)
return 0;
slash = git_buf_rfind_next(buffer, '/');
if (slash >= 0 && buffer->ptr[slash] == '/')
return (size_t)(slash + 1);
return 0;
}
const char *git_path_topdir(const char *path)
{
size_t len;
ssize_t i;
assert(path);
len = strlen(path);
if (!len || path[len - 1] != '/')
return NULL;
for (i = (ssize_t)len - 2; i >= 0; --i)
if (path[i] == '/')
break;
return &path[i + 1];
}
int git_path_root(const char *path)
{
int offset = 0;
/* Does the root of the path look like a windows drive ? */
if (LOOKS_LIKE_DRIVE_PREFIX(path))
offset += 2;
#ifdef GIT_WIN32
/* Are we dealing with a windows network path? */
else if ((path[0] == '/' && path[1] == '/' && path[2] != '/') ||
(path[0] == '\\' && path[1] == '\\' && path[2] != '\\'))
{
offset += 2;
/* Skip the computer name segment */
while (path[offset] && path[offset] != '/' && path[offset] != '\\')
offset++;
}
if (path[offset] == '\\')
return offset;
#endif
if (path[offset] == '/')
return offset;
return -1; /* Not a real error - signals that path is not rooted */
}
void git_path_trim_slashes(git_buf *path)
{
int ceiling = git_path_root(path->ptr) + 1;
assert(ceiling >= 0);
while (path->size > (size_t)ceiling) {
if (path->ptr[path->size-1] != '/')
break;
path->ptr[path->size-1] = '\0';
path->size--;
}
}
int git_path_join_unrooted(
git_buf *path_out, const char *path, const char *base, ssize_t *root_at)
{
ssize_t root;
assert(path && path_out);
root = (ssize_t)git_path_root(path);
if (base != NULL && root < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
root = (ssize_t)strlen(base);
} else {
if (git_buf_sets(path_out, path) < 0)
return -1;
if (root < 0)
root = 0;
else if (base)
git_path_equal_or_prefixed(base, path, &root);
}
if (root_at)
*root_at = root;
return 0;
}
void git_path_squash_slashes(git_buf *path)
{
char *p, *q;
if (path->size == 0)
return;
for (p = path->ptr, q = path->ptr; *q; p++, q++) {
*p = *q;
while (*q == '/' && *(q+1) == '/') {
path->size--;
q++;
}
}
*p = '\0';
}
int git_path_prettify(git_buf *path_out, const char *path, const char *base)
{
char buf[GIT_PATH_MAX];
assert(path && path_out);
/* construct path if needed */
if (base != NULL && git_path_root(path) < 0) {
if (git_buf_joinpath(path_out, base, path) < 0)
return -1;
path = path_out->ptr;
}
if (p_realpath(path, buf) == NULL) {
/* git_error_set resets the errno when dealing with a GIT_ERROR_OS kind of error */
int error = (errno == ENOENT || errno == ENOTDIR) ? GIT_ENOTFOUND : -1;
git_error_set(GIT_ERROR_OS, "failed to resolve path '%s'", path);
git_buf_clear(path_out);
return error;
}
return git_buf_sets(path_out, buf);
}
int git_path_prettify_dir(git_buf *path_out, const char *path, const char *base)
{
int error = git_path_prettify(path_out, path, base);
return (error < 0) ? error : git_path_to_dir(path_out);
}
int git_path_to_dir(git_buf *path)
{
if (path->asize > 0 &&
git_buf_len(path) > 0 &&
path->ptr[git_buf_len(path) - 1] != '/')
git_buf_putc(path, '/');
return git_buf_oom(path) ? -1 : 0;
}
void git_path_string_to_dir(char* path, size_t size)
{
size_t end = strlen(path);
if (end && path[end - 1] != '/' && end < size) {
path[end] = '/';
path[end + 1] = '\0';
}
}
int git__percent_decode(git_buf *decoded_out, const char *input)
{
int len, hi, lo, i;
assert(decoded_out && input);
len = (int)strlen(input);
git_buf_clear(decoded_out);
for(i = 0; i < len; i++)
{
char c = input[i];
if (c != '%')
goto append;
if (i >= len - 2)
goto append;
hi = git__fromhex(input[i + 1]);
lo = git__fromhex(input[i + 2]);
if (hi < 0 || lo < 0)
goto append;
c = (char)(hi << 4 | lo);
i += 2;
append:
if (git_buf_putc(decoded_out, c) < 0)
return -1;
}
return 0;
}
static int error_invalid_local_file_uri(const char *uri)
{
git_error_set(GIT_ERROR_CONFIG, "'%s' is not a valid local file URI", uri);
return -1;
}
static int local_file_url_prefixlen(const char *file_url)
{
int len = -1;
if (git__prefixcmp(file_url, "file://") == 0) {
if (file_url[7] == '/')
len = 8;
else if (git__prefixcmp(file_url + 7, "localhost/") == 0)
len = 17;
}
return len;
}
bool git_path_is_local_file_url(const char *file_url)
{
return (local_file_url_prefixlen(file_url) > 0);
}
int git_path_fromurl(git_buf *local_path_out, const char *file_url)
{
int offset;
assert(local_path_out && file_url);
if ((offset = local_file_url_prefixlen(file_url)) < 0 ||
file_url[offset] == '\0' || file_url[offset] == '/')
return error_invalid_local_file_uri(file_url);
#ifndef GIT_WIN32
offset--; /* A *nix absolute path starts with a forward slash */
#endif
git_buf_clear(local_path_out);
return git__percent_decode(local_path_out, file_url + offset);
}
int git_path_walk_up(
git_buf *path,
const char *ceiling,
int (*cb)(void *data, const char *),
void *data)
{
int error = 0;
git_buf iter;
ssize_t stop = 0, scan;
char oldc = '\0';
assert(path && cb);
if (ceiling != NULL) {
if (git__prefixcmp(path->ptr, ceiling) == 0)
stop = (ssize_t)strlen(ceiling);
else
stop = git_buf_len(path);
}
scan = git_buf_len(path);
/* empty path: yield only once */
if (!scan) {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
return error;
}
iter.ptr = path->ptr;
iter.size = git_buf_len(path);
iter.asize = path->asize;
while (scan >= stop) {
error = cb(data, iter.ptr);
iter.ptr[scan] = oldc;
if (error) {
git_error_set_after_callback(error);
break;
}
scan = git_buf_rfind_next(&iter, '/');
if (scan >= 0) {
scan++;
oldc = iter.ptr[scan];
iter.size = scan;
iter.ptr[scan] = '\0';
}
}
if (scan >= 0)
iter.ptr[scan] = oldc;
/* relative path: yield for the last component */
if (!error && stop == 0 && iter.ptr[0] != '/') {
error = cb(data, "");
if (error)
git_error_set_after_callback(error);
}
return error;
}
bool git_path_exists(const char *path)
{
assert(path);
return p_access(path, F_OK) == 0;
}
bool git_path_isdir(const char *path)
{
struct stat st;
if (p_stat(path, &st) < 0)
return false;
return S_ISDIR(st.st_mode) != 0;
}
bool git_path_isfile(const char *path)
{
struct stat st;
assert(path);
if (p_stat(path, &st) < 0)
return false;
return S_ISREG(st.st_mode) != 0;
}
bool git_path_islink(const char *path)
{
struct stat st;
assert(path);
if (p_lstat(path, &st) < 0)
return false;
return S_ISLNK(st.st_mode) != 0;
}
#ifdef GIT_WIN32
bool git_path_is_empty_dir(const char *path)
{
git_win32_path filter_w;
bool empty = false;
if (git_win32__findfirstfile_filter(filter_w, path)) {
WIN32_FIND_DATAW findData;
HANDLE hFind = FindFirstFileW(filter_w, &findData);
/* FindFirstFile will fail if there are no children to the given
* path, which can happen if the given path is a file (and obviously
* has no children) or if the given path is an empty mount point.
* (Most directories have at least directory entries '.' and '..',
* but ridiculously another volume mounted in another drive letter's
* path space do not, and thus have nothing to enumerate.) If
* FindFirstFile fails, check if this is a directory-like thing
* (a mount point).
*/
if (hFind == INVALID_HANDLE_VALUE)
return git_path_isdir(path);
/* If the find handle was created successfully, then it's a directory */
empty = true;
do {
/* Allow the enumeration to return . and .. and still be considered
* empty. In the special case of drive roots (i.e. C:\) where . and
* .. do not occur, we can still consider the path to be an empty
* directory if there's nothing there. */
if (!git_path_is_dot_or_dotdotW(findData.cFileName)) {
empty = false;
break;
}
} while (FindNextFileW(hFind, &findData));
FindClose(hFind);
}
return empty;
}
#else
static int path_found_entry(void *payload, git_buf *path)
{
GIT_UNUSED(payload);
return !git_path_is_dot_or_dotdot(path->ptr);
}
bool git_path_is_empty_dir(const char *path)
{
int error;
git_buf dir = GIT_BUF_INIT;
if (!git_path_isdir(path))
return false;
if ((error = git_buf_sets(&dir, path)) != 0)
git_error_clear();
else
error = git_path_direach(&dir, 0, path_found_entry, NULL);
git_buf_dispose(&dir);
return !error;
}
#endif
int git_path_set_error(int errno_value, const char *path, const char *action)
{
switch (errno_value) {
case ENOENT:
case ENOTDIR:
git_error_set(GIT_ERROR_OS, "could not find '%s' to %s", path, action);
return GIT_ENOTFOUND;
case EINVAL:
case ENAMETOOLONG:
git_error_set(GIT_ERROR_OS, "invalid path for filesystem '%s'", path);
return GIT_EINVALIDSPEC;
case EEXIST:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' already exists", action, path);
return GIT_EEXISTS;
case EACCES:
git_error_set(GIT_ERROR_OS, "failed %s - '%s' is locked", action, path);
return GIT_ELOCKED;
default:
git_error_set(GIT_ERROR_OS, "could not %s '%s'", action, path);
return -1;
}
}
int git_path_lstat(const char *path, struct stat *st)
{
if (p_lstat(path, st) == 0)
return 0;
return git_path_set_error(errno, path, "stat");
}
static bool _check_dir_contents(
git_buf *dir,
const char *sub,
bool (*predicate)(const char *))
{
bool result;
size_t dir_size = git_buf_len(dir);
size_t sub_size = strlen(sub);
size_t alloc_size;
/* leave base valid even if we could not make space for subdir */
if (GIT_ADD_SIZET_OVERFLOW(&alloc_size, dir_size, sub_size) ||
GIT_ADD_SIZET_OVERFLOW(&alloc_size, alloc_size, 2) ||
git_buf_try_grow(dir, alloc_size, false) < 0)
return false;
/* save excursion */
if (git_buf_joinpath(dir, dir->ptr, sub) < 0)
return false;
result = predicate(dir->ptr);
/* restore path */
git_buf_truncate(dir, dir_size);
return result;
}
bool git_path_contains(git_buf *dir, const char *item)
{
return _check_dir_contents(dir, item, &git_path_exists);
}
bool git_path_contains_dir(git_buf *base, const char *subdir)
{
return _check_dir_contents(base, subdir, &git_path_isdir);
}
bool git_path_contains_file(git_buf *base, const char *file)
{
return _check_dir_contents(base, file, &git_path_isfile);
}
int git_path_find_dir(git_buf *dir, const char *path, const char *base)
{
int error = git_path_join_unrooted(dir, path, base, NULL);
if (!error) {
char buf[GIT_PATH_MAX];
if (p_realpath(dir->ptr, buf) != NULL)
error = git_buf_sets(dir, buf);
}
/* call dirname if this is not a directory */
if (!error) /* && git_path_isdir(dir->ptr) == false) */
error = (git_path_dirname_r(dir, dir->ptr) < 0) ? -1 : 0;
if (!error)
error = git_path_to_dir(dir);
return error;
}
int git_path_resolve_relative(git_buf *path, size_t ceiling)
{
char *base, *to, *from, *next;
size_t len;
GIT_ERROR_CHECK_ALLOC_BUF(path);
if (ceiling > path->size)
ceiling = path->size;
/* recognize drive prefixes, etc. that should not be backed over */
if (ceiling == 0)
ceiling = git_path_root(path->ptr) + 1;
/* recognize URL prefixes that should not be backed over */
if (ceiling == 0) {
for (next = path->ptr; *next && git__isalpha(*next); ++next);
if (next[0] == ':' && next[1] == '/' && next[2] == '/')
ceiling = (next + 3) - path->ptr;
}
base = to = from = path->ptr + ceiling;
while (*from) {
for (next = from; *next && *next != '/'; ++next);
len = next - from;
if (len == 1 && from[0] == '.')
/* do nothing with singleton dot */;
else if (len == 2 && from[0] == '.' && from[1] == '.') {
/* error out if trying to up one from a hard base */
if (to == base && ceiling != 0) {
git_error_set(GIT_ERROR_INVALID,
"cannot strip root component off url");
return -1;
}
/* no more path segments to strip,
* use '../' as a new base path */
if (to == base) {
if (*next == '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
/* this is now the base, can't back up from a
* relative prefix */
base = to;
} else {
/* back up a path segment */
while (to > base && to[-1] == '/') to--;
while (to > base && to[-1] != '/') to--;
}
} else {
if (*next == '/' && *from != '/')
len++;
if (to != from)
memmove(to, from, len);
to += len;
}
from += len;
while (*from == '/') from++;
}
*to = '\0';
path->size = to - path->ptr;
return 0;
}
int git_path_apply_relative(git_buf *target, const char *relpath)
{
return git_buf_joinpath(target, git_buf_cstr(target), relpath) ||
git_path_resolve_relative(target, 0);
}
int git_path_cmp(
const char *name1, size_t len1, int isdir1,
const char *name2, size_t len2, int isdir2,
int (*compare)(const char *, const char *, size_t))
{
unsigned char c1, c2;
size_t len = len1 < len2 ? len1 : len2;
int cmp;
cmp = compare(name1, name2, len);
if (cmp)
return cmp;
c1 = name1[len];
c2 = name2[len];
if (c1 == '\0' && isdir1)
c1 = '/';
if (c2 == '\0' && isdir2)
c2 = '/';
return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}
size_t git_path_common_dirlen(const char *one, const char *two)
{
const char *p, *q, *dirsep = NULL;
for (p = one, q = two; *p && *q; p++, q++) {
if (*p == '/' && *q == '/')
dirsep = p;
else if (*p != *q)
break;
}
return dirsep ? (dirsep - one) + 1 : 0;
}
int git_path_make_relative(git_buf *path, const char *parent)
{
const char *p, *q, *p_dirsep, *q_dirsep;
size_t plen = path->size, newlen, alloclen, depth = 1, i, offset;
for (p_dirsep = p = path->ptr, q_dirsep = q = parent; *p && *q; p++, q++) {
if (*p == '/' && *q == '/') {
p_dirsep = p;
q_dirsep = q;
}
else if (*p != *q)
break;
}
/* need at least 1 common path segment */
if ((p_dirsep == path->ptr || q_dirsep == parent) &&
(*p_dirsep != '/' || *q_dirsep != '/')) {
git_error_set(GIT_ERROR_INVALID,
"%s is not a parent of %s", parent, path->ptr);
return GIT_ENOTFOUND;
}
if (*p == '/' && !*q)
p++;
else if (!*p && *q == '/')
q++;
else if (!*p && !*q)
return git_buf_clear(path), 0;
else {
p = p_dirsep + 1;
q = q_dirsep + 1;
}
plen -= (p - path->ptr);
if (!*q)
return git_buf_set(path, p, plen);
for (; (q = strchr(q, '/')) && *(q + 1); q++)
depth++;
GIT_ERROR_CHECK_ALLOC_MULTIPLY(&newlen, depth, 3);
GIT_ERROR_CHECK_ALLOC_ADD(&newlen, newlen, plen);
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, newlen, 1);
/* save the offset as we might realllocate the pointer */
offset = p - path->ptr;
if (git_buf_try_grow(path, alloclen, 1) < 0)
return -1;
p = path->ptr + offset;
memmove(path->ptr + (depth * 3), p, plen + 1);
for (i = 0; i < depth; i++)
memcpy(path->ptr + (i * 3), "../", 3);
path->size = newlen;
return 0;
}
bool git_path_has_non_ascii(const char *path, size_t pathlen)
{
const uint8_t *scan = (const uint8_t *)path, *end;
for (end = scan + pathlen; scan < end; ++scan)
if (*scan & 0x80)
return true;
return false;
}
#ifdef GIT_USE_ICONV
int git_path_iconv_init_precompose(git_path_iconv_t *ic)
{
git_buf_init(&ic->buf, 0);
ic->map = iconv_open(GIT_PATH_REPO_ENCODING, GIT_PATH_NATIVE_ENCODING);
return 0;
}
void git_path_iconv_clear(git_path_iconv_t *ic)
{
if (ic) {
if (ic->map != (iconv_t)-1)
iconv_close(ic->map);
git_buf_dispose(&ic->buf);
}
}
int git_path_iconv(git_path_iconv_t *ic, const char **in, size_t *inlen)
{
char *nfd = (char*)*in, *nfc;
size_t nfdlen = *inlen, nfclen, wantlen = nfdlen, alloclen, rv;
int retry = 1;
if (!ic || ic->map == (iconv_t)-1 ||
!git_path_has_non_ascii(*in, *inlen))
return 0;
git_buf_clear(&ic->buf);
while (1) {
GIT_ERROR_CHECK_ALLOC_ADD(&alloclen, wantlen, 1);
if (git_buf_grow(&ic->buf, alloclen) < 0)
return -1;
nfc = ic->buf.ptr + ic->buf.size;
nfclen = ic->buf.asize - ic->buf.size;
rv = iconv(ic->map, &nfd, &nfdlen, &nfc, &nfclen);
ic->buf.size = (nfc - ic->buf.ptr);
if (rv != (size_t)-1)
break;
/* if we cannot convert the data (probably because iconv thinks
* it is not valid UTF-8 source data), then use original data
*/
if (errno != E2BIG)
return 0;
/* make space for 2x the remaining data to be converted
* (with per retry overhead to avoid infinite loops)
*/
wantlen = ic->buf.size + max(nfclen, nfdlen) * 2 + (size_t)(retry * 4);
if (retry++ > 4)
goto fail;
}
ic->buf.ptr[ic->buf.size] = '\0';
*in = ic->buf.ptr;
*inlen = ic->buf.size;
return 0;
fail:
git_error_set(GIT_ERROR_OS, "unable to convert unicode path data");
return -1;
}
static const char *nfc_file = "\xC3\x85\x73\x74\x72\xC3\xB6\x6D.XXXXXX";
static const char *nfd_file = "\x41\xCC\x8A\x73\x74\x72\x6F\xCC\x88\x6D.XXXXXX";
/* Check if the platform is decomposing unicode data for us. We will
* emulate core Git and prefer to use precomposed unicode data internally
* on these platforms, composing the decomposed unicode on the fly.
*
* This mainly happens on the Mac where HDFS stores filenames as
* decomposed unicode. Even on VFAT and SAMBA file systems, the Mac will
* return decomposed unicode from readdir() even when the actual
* filesystem is storing precomposed unicode.
*/
bool git_path_does_fs_decompose_unicode(const char *root)
{
git_buf path = GIT_BUF_INIT;
int fd;
bool found_decomposed = false;
char tmp[6];
/* Create a file using a precomposed path and then try to find it
* using the decomposed name. If the lookup fails, then we will mark
* that we should precompose unicode for this repository.
*/
if (git_buf_joinpath(&path, root, nfc_file) < 0 ||
(fd = p_mkstemp(path.ptr)) < 0)
goto done;
p_close(fd);
/* record trailing digits generated by mkstemp */
memcpy(tmp, path.ptr + path.size - sizeof(tmp), sizeof(tmp));
/* try to look up as NFD path */
if (git_buf_joinpath(&path, root, nfd_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
found_decomposed = git_path_exists(path.ptr);
/* remove temporary file (using original precomposed path) */
if (git_buf_joinpath(&path, root, nfc_file) < 0)
goto done;
memcpy(path.ptr + path.size - sizeof(tmp), tmp, sizeof(tmp));
(void)p_unlink(path.ptr);
done:
git_buf_dispose(&path);
return found_decomposed;
}
#else
bool git_path_does_fs_decompose_unicode(const char *root)
{
GIT_UNUSED(root);
return false;
}
#endif
#if defined(__sun) || defined(__GNU__)
typedef char path_dirent_data[sizeof(struct dirent) + FILENAME_MAX + 1];
#else
typedef struct dirent path_dirent_data;
#endif
int git_path_direach(
git_buf *path,
uint32_t flags,
int (*fn)(void *, git_buf *),
void *arg)
{
int error = 0;
ssize_t wd_len;
DIR *dir;
struct dirent *de;
#ifdef GIT_USE_ICONV
git_path_iconv_t ic = GIT_PATH_ICONV_INIT;
#endif
GIT_UNUSED(flags);
if (git_path_to_dir(path) < 0)
return -1;
wd_len = git_buf_len(path);
if ((dir = opendir(path->ptr)) == NULL) {
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path->ptr);
if (errno == ENOENT)
return GIT_ENOTFOUND;
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&ic);
#endif
while ((de = readdir(dir)) != NULL) {
const char *de_path = de->d_name;
size_t de_len = strlen(de_path);
if (git_path_is_dot_or_dotdot(de_path))
continue;
#ifdef GIT_USE_ICONV
if ((error = git_path_iconv(&ic, &de_path, &de_len)) < 0)
break;
#endif
if ((error = git_buf_put(path, de_path, de_len)) < 0)
break;
git_error_clear();
error = fn(arg, path);
git_buf_truncate(path, wd_len); /* restore path */
/* Only set our own error if the callback did not set one already */
if (error != 0) {
if (!git_error_last())
git_error_set_after_callback(error);
break;
}
}
closedir(dir);
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&ic);
#endif
return error;
}
#if defined(GIT_WIN32) && !defined(__MINGW32__)
/* Using _FIND_FIRST_EX_LARGE_FETCH may increase performance in Windows 7
* and better.
*/
#ifndef FIND_FIRST_EX_LARGE_FETCH
# define FIND_FIRST_EX_LARGE_FETCH 2
#endif
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
git_win32_path path_filter;
static int is_win7_or_later = -1;
if (is_win7_or_later < 0)
is_win7_or_later = git_has_win32_version(6, 1, 0);
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
diriter->handle = INVALID_HANDLE_VALUE;
if (git_buf_puts(&diriter->path_utf8, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path_utf8);
if (diriter->path_utf8.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->parent_len = git_win32_path_from_utf8(diriter->path, diriter->path_utf8.ptr)) < 0 ||
!git_win32__findfirstfile_filter(path_filter, diriter->path_utf8.ptr)) {
git_error_set(GIT_ERROR_OS, "could not parse the directory path '%s'", path);
return -1;
}
diriter->handle = FindFirstFileExW(
path_filter,
is_win7_or_later ? FindExInfoBasic : FindExInfoStandard,
&diriter->current,
FindExSearchNameMatch,
NULL,
is_win7_or_later ? FIND_FIRST_EX_LARGE_FETCH : 0);
if (diriter->handle == INVALID_HANDLE_VALUE) {
git_error_set(GIT_ERROR_OS, "could not open directory '%s'", path);
return -1;
}
diriter->parent_utf8_len = diriter->path_utf8.size;
diriter->flags = flags;
return 0;
}
static int diriter_update_paths(git_path_diriter *diriter)
{
size_t filename_len, path_len;
filename_len = wcslen(diriter->current.cFileName);
if (GIT_ADD_SIZET_OVERFLOW(&path_len, diriter->parent_len, filename_len) ||
GIT_ADD_SIZET_OVERFLOW(&path_len, path_len, 2))
return -1;
if (path_len > GIT_WIN_PATH_UTF16) {
git_error_set(GIT_ERROR_FILESYSTEM,
"invalid path '%.*ls\\%ls' (path too long)",
diriter->parent_len, diriter->path, diriter->current.cFileName);
return -1;
}
diriter->path[diriter->parent_len] = L'\\';
memcpy(&diriter->path[diriter->parent_len+1],
diriter->current.cFileName, filename_len * sizeof(wchar_t));
diriter->path[path_len-1] = L'\0';
git_buf_truncate(&diriter->path_utf8, diriter->parent_utf8_len);
if (diriter->parent_utf8_len > 0 &&
diriter->path_utf8.ptr[diriter->parent_utf8_len-1] != '/')
git_buf_putc(&diriter->path_utf8, '/');
git_buf_put_w(&diriter->path_utf8, diriter->current.cFileName, filename_len);
if (git_buf_oom(&diriter->path_utf8))
return -1;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
do {
/* Our first time through, we already have the data from
* FindFirstFileW. Use it, otherwise get the next file.
*/
if (!diriter->needs_next)
diriter->needs_next = 1;
else if (!FindNextFileW(diriter->handle, &diriter->current))
return GIT_ITEROVER;
} while (skip_dot && git_path_is_dot_or_dotdotW(diriter->current.cFileName));
if (diriter_update_paths(diriter) < 0)
return -1;
return 0;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path_utf8.size > diriter->parent_utf8_len);
*out = &diriter->path_utf8.ptr[diriter->parent_utf8_len+1];
*out_len = diriter->path_utf8.size - diriter->parent_utf8_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path_utf8.ptr;
*out_len = diriter->path_utf8.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_win32__file_attribute_to_stat(out,
(WIN32_FILE_ATTRIBUTE_DATA *)&diriter->current,
diriter->path);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
git_buf_dispose(&diriter->path_utf8);
if (diriter->handle != INVALID_HANDLE_VALUE) {
FindClose(diriter->handle);
diriter->handle = INVALID_HANDLE_VALUE;
}
}
#else
int git_path_diriter_init(
git_path_diriter *diriter,
const char *path,
unsigned int flags)
{
assert(diriter && path);
memset(diriter, 0, sizeof(git_path_diriter));
if (git_buf_puts(&diriter->path, path) < 0)
return -1;
git_path_trim_slashes(&diriter->path);
if (diriter->path.size == 0) {
git_error_set(GIT_ERROR_FILESYSTEM, "could not open directory '%s'", path);
return -1;
}
if ((diriter->dir = opendir(diriter->path.ptr)) == NULL) {
git_buf_dispose(&diriter->path);
git_error_set(GIT_ERROR_OS, "failed to open directory '%s'", path);
return -1;
}
#ifdef GIT_USE_ICONV
if ((flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0)
(void)git_path_iconv_init_precompose(&diriter->ic);
#endif
diriter->parent_len = diriter->path.size;
diriter->flags = flags;
return 0;
}
int git_path_diriter_next(git_path_diriter *diriter)
{
struct dirent *de;
const char *filename;
size_t filename_len;
bool skip_dot = !(diriter->flags & GIT_PATH_DIR_INCLUDE_DOT_AND_DOTDOT);
int error = 0;
assert(diriter);
errno = 0;
do {
if ((de = readdir(diriter->dir)) == NULL) {
if (!errno)
return GIT_ITEROVER;
git_error_set(GIT_ERROR_OS,
"could not read directory '%s'", diriter->path.ptr);
return -1;
}
} while (skip_dot && git_path_is_dot_or_dotdot(de->d_name));
filename = de->d_name;
filename_len = strlen(filename);
#ifdef GIT_USE_ICONV
if ((diriter->flags & GIT_PATH_DIR_PRECOMPOSE_UNICODE) != 0 &&
(error = git_path_iconv(&diriter->ic, &filename, &filename_len)) < 0)
return error;
#endif
git_buf_truncate(&diriter->path, diriter->parent_len);
if (diriter->parent_len > 0 &&
diriter->path.ptr[diriter->parent_len-1] != '/')
git_buf_putc(&diriter->path, '/');
git_buf_put(&diriter->path, filename, filename_len);
if (git_buf_oom(&diriter->path))
return -1;
return error;
}
int git_path_diriter_filename(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
assert(diriter->path.size > diriter->parent_len);
*out = &diriter->path.ptr[diriter->parent_len+1];
*out_len = diriter->path.size - diriter->parent_len - 1;
return 0;
}
int git_path_diriter_fullpath(
const char **out,
size_t *out_len,
git_path_diriter *diriter)
{
assert(out && out_len && diriter);
*out = diriter->path.ptr;
*out_len = diriter->path.size;
return 0;
}
int git_path_diriter_stat(struct stat *out, git_path_diriter *diriter)
{
assert(out && diriter);
return git_path_lstat(diriter->path.ptr, out);
}
void git_path_diriter_free(git_path_diriter *diriter)
{
if (diriter == NULL)
return;
if (diriter->dir) {
closedir(diriter->dir);
diriter->dir = NULL;
}
#ifdef GIT_USE_ICONV
git_path_iconv_clear(&diriter->ic);
#endif
git_buf_dispose(&diriter->path);
}
#endif
int git_path_dirload(
git_vector *contents,
const char *path,
size_t prefix_len,
uint32_t flags)
{
git_path_diriter iter = GIT_PATH_DIRITER_INIT;
const char *name;
size_t name_len;
char *dup;
int error;
assert(contents && path);
if ((error = git_path_diriter_init(&iter, path, flags)) < 0)
return error;
while ((error = git_path_diriter_next(&iter)) == 0) {
if ((error = git_path_diriter_fullpath(&name, &name_len, &iter)) < 0)
break;
assert(name_len > prefix_len);
dup = git__strndup(name + prefix_len, name_len - prefix_len);
GIT_ERROR_CHECK_ALLOC(dup);
if ((error = git_vector_insert(contents, dup)) < 0)
break;
}
if (error == GIT_ITEROVER)
error = 0;
git_path_diriter_free(&iter);
return error;
}
int git_path_from_url_or_path(git_buf *local_path_out, const char *url_or_path)
{
if (git_path_is_local_file_url(url_or_path))
return git_path_fromurl(local_path_out, url_or_path);
else
return git_buf_sets(local_path_out, url_or_path);
}
/* Reject paths like AUX or COM1, or those versions that end in a dot or
* colon. ("AUX." or "AUX:")
*/
GIT_INLINE(bool) verify_dospath(
const char *component,
size_t len,
const char dospath[3],
bool trailing_num)
{
size_t last = trailing_num ? 4 : 3;
if (len < last || git__strncasecmp(component, dospath, 3) != 0)
return true;
if (trailing_num && (component[3] < '1' || component[3] > '9'))
return true;
return (len > last &&
component[last] != '.' &&
component[last] != ':');
}
static int32_t next_hfs_char(const char **in, size_t *len)
{
while (*len) {
int32_t codepoint;
int cp_len = git__utf8_iterate((const uint8_t *)(*in), (int)(*len), &codepoint);
if (cp_len < 0)
return -1;
(*in) += cp_len;
(*len) -= cp_len;
/* these code points are ignored completely */
switch (codepoint) {
case 0x200c: /* ZERO WIDTH NON-JOINER */
case 0x200d: /* ZERO WIDTH JOINER */
case 0x200e: /* LEFT-TO-RIGHT MARK */
case 0x200f: /* RIGHT-TO-LEFT MARK */
case 0x202a: /* LEFT-TO-RIGHT EMBEDDING */
case 0x202b: /* RIGHT-TO-LEFT EMBEDDING */
case 0x202c: /* POP DIRECTIONAL FORMATTING */
case 0x202d: /* LEFT-TO-RIGHT OVERRIDE */
case 0x202e: /* RIGHT-TO-LEFT OVERRIDE */
case 0x206a: /* INHIBIT SYMMETRIC SWAPPING */
case 0x206b: /* ACTIVATE SYMMETRIC SWAPPING */
case 0x206c: /* INHIBIT ARABIC FORM SHAPING */
case 0x206d: /* ACTIVATE ARABIC FORM SHAPING */
case 0x206e: /* NATIONAL DIGIT SHAPES */
case 0x206f: /* NOMINAL DIGIT SHAPES */
case 0xfeff: /* ZERO WIDTH NO-BREAK SPACE */
continue;
}
/* fold into lowercase -- this will only fold characters in
* the ASCII range, which is perfectly fine, because the
* git folder name can only be composed of ascii characters
*/
return git__tolower(codepoint);
}
return 0; /* NULL byte -- end of string */
}
static bool verify_dotgit_hfs_generic(const char *path, size_t len, const char *needle, size_t needle_len)
{
size_t i;
char c;
if (next_hfs_char(&path, &len) != '.')
return true;
for (i = 0; i < needle_len; i++) {
c = next_hfs_char(&path, &len);
if (c != needle[i])
return true;
}
if (next_hfs_char(&path, &len) != '\0')
return true;
return false;
}
static bool verify_dotgit_hfs(const char *path, size_t len)
{
return verify_dotgit_hfs_generic(path, len, "git", CONST_STRLEN("git"));
}
GIT_INLINE(bool) verify_dotgit_ntfs(git_repository *repo, const char *path, size_t len)
{
git_buf *reserved = git_repository__reserved_names_win32;
size_t reserved_len = git_repository__reserved_names_win32_len;
size_t start = 0, i;
if (repo)
git_repository__reserved_names(&reserved, &reserved_len, repo, true);
for (i = 0; i < reserved_len; i++) {
git_buf *r = &reserved[i];
if (len >= r->size &&
strncasecmp(path, r->ptr, r->size) == 0) {
start = r->size;
break;
}
}
if (!start)
return true;
/*
* Reject paths that start with Windows-style directory separators
* (".git\") or NTFS alternate streams (".git:") and could be used
* to write to the ".git" directory on Windows platforms.
*/
if (path[start] == '\\' || path[start] == ':')
return false;
/* Reject paths like '.git ' or '.git.' */
for (i = start; i < len; i++) {
if (path[i] != ' ' && path[i] != '.')
return true;
}
return false;
}
GIT_INLINE(bool) only_spaces_and_dots(const char *path)
{
const char *c = path;
for (;; c++) {
if (*c == '\0' || *c == ':')
return true;
if (*c != ' ' && *c != '.')
return false;
}
return true;
}
GIT_INLINE(bool) verify_dotgit_ntfs_generic(const char *name, size_t len, const char *dotgit_name, size_t dotgit_len, const char *shortname_pfix)
{
int i, saw_tilde;
if (name[0] == '.' && len >= dotgit_len &&
!strncasecmp(name + 1, dotgit_name, dotgit_len)) {
return !only_spaces_and_dots(name + dotgit_len + 1);
}
/* Detect the basic NTFS shortname with the first six chars */
if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
name[7] >= '1' && name[7] <= '4')
return !only_spaces_and_dots(name + 8);
/* Catch fallback names */
for (i = 0, saw_tilde = 0; i < 8; i++) {
if (name[i] == '\0') {
return true;
} else if (saw_tilde) {
if (name[i] < '0' || name[i] > '9')
return true;
} else if (name[i] == '~') {
if (name[i+1] < '1' || name[i+1] > '9')
return true;
saw_tilde = 1;
} else if (i >= 6) {
return true;
} else if ((unsigned char)name[i] > 127) {
return true;
} else if (git__tolower(name[i]) != shortname_pfix[i]) {
return true;
}
}
return !only_spaces_and_dots(name + i);
}
GIT_INLINE(bool) verify_char(unsigned char c, unsigned int flags)
{
if ((flags & GIT_PATH_REJECT_BACKSLASH) && c == '\\')
return false;
if ((flags & GIT_PATH_REJECT_SLASH) && c == '/')
return false;
if (flags & GIT_PATH_REJECT_NT_CHARS) {
if (c < 32)
return false;
switch (c) {
case '<':
case '>':
case ':':
case '"':
case '|':
case '?':
case '*':
return false;
}
}
return true;
}
/*
* Return the length of the common prefix between str and prefix, comparing them
* case-insensitively (must be ASCII to match).
*/
GIT_INLINE(size_t) common_prefix_icase(const char *str, size_t len, const char *prefix)
{
size_t count = 0;
while (len >0 && tolower(*str) == tolower(*prefix)) {
count++;
str++;
prefix++;
len--;
}
return count;
}
/*
* We fundamentally don't like some paths when dealing with user-inputted
* strings (in checkout or ref names): we don't want dot or dot-dot
* anywhere, we want to avoid writing weird paths on Windows that can't
* be handled by tools that use the non-\\?\ APIs, we don't want slashes
* or double slashes at the end of paths that can make them ambiguous.
*
* For checkout, we don't want to recurse into ".git" either.
*/
static bool verify_component(
git_repository *repo,
const char *component,
size_t len,
uint16_t mode,
unsigned int flags)
{
if (len == 0)
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 1 && component[0] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAVERSAL) &&
len == 2 && component[0] == '.' && component[1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_DOT) && component[len-1] == '.')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_SPACE) && component[len-1] == ' ')
return false;
if ((flags & GIT_PATH_REJECT_TRAILING_COLON) && component[len-1] == ':')
return false;
if (flags & GIT_PATH_REJECT_DOS_PATHS) {
if (!verify_dospath(component, len, "CON", false) ||
!verify_dospath(component, len, "PRN", false) ||
!verify_dospath(component, len, "AUX", false) ||
!verify_dospath(component, len, "NUL", false) ||
!verify_dospath(component, len, "COM", true) ||
!verify_dospath(component, len, "LPT", true))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_HFS) {
if (!verify_dotgit_hfs(component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_HFS))
return false;
}
if (flags & GIT_PATH_REJECT_DOT_GIT_NTFS) {
if (!verify_dotgit_ntfs(repo, component, len))
return false;
if (S_ISLNK(mode) && git_path_is_gitfile(component, len, GIT_PATH_GITFILE_GITMODULES, GIT_PATH_FS_NTFS))
return false;
}
/* don't bother rerunning the `.git` test if we ran the HFS or NTFS
* specific tests, they would have already rejected `.git`.
*/
if ((flags & GIT_PATH_REJECT_DOT_GIT_HFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_NTFS) == 0 &&
(flags & GIT_PATH_REJECT_DOT_GIT_LITERAL)) {
if (len >= 4 &&
component[0] == '.' &&
(component[1] == 'g' || component[1] == 'G') &&
(component[2] == 'i' || component[2] == 'I') &&
(component[3] == 't' || component[3] == 'T')) {
if (len == 4)
return false;
if (S_ISLNK(mode) && common_prefix_icase(component, len, ".gitmodules") == len)
return false;
}
}
return true;
}
GIT_INLINE(unsigned int) dotgit_flags(
git_repository *repo,
unsigned int flags)
{
int protectHFS = 0, protectNTFS = 0;
int error = 0;
flags |= GIT_PATH_REJECT_DOT_GIT_LITERAL;
#ifdef __APPLE__
protectHFS = 1;
#endif
#ifdef GIT_WIN32
protectNTFS = 1;
#endif
if (repo && !protectHFS)
error = git_repository__configmap_lookup(&protectHFS, repo, GIT_CONFIGMAP_PROTECTHFS);
if (!error && protectHFS)
flags |= GIT_PATH_REJECT_DOT_GIT_HFS;
if (repo && !protectNTFS)
error = git_repository__configmap_lookup(&protectNTFS, repo, GIT_CONFIGMAP_PROTECTNTFS);
if (!error && protectNTFS)
flags |= GIT_PATH_REJECT_DOT_GIT_NTFS;
return flags;
}
bool git_path_isvalid(
git_repository *repo,
const char *path,
uint16_t mode,
unsigned int flags)
{
const char *start, *c;
/* Upgrade the ".git" checks based on platform */
if ((flags & GIT_PATH_REJECT_DOT_GIT))
flags = dotgit_flags(repo, flags);
for (start = c = path; *c; c++) {
if (!verify_char(*c, flags))
return false;
if (*c == '/') {
if (!verify_component(repo, start, (c - start), mode, flags))
return false;
start = c+1;
}
}
return verify_component(repo, start, (c - start), mode, flags);
}
int git_path_normalize_slashes(git_buf *out, const char *path)
{
int error;
char *p;
if ((error = git_buf_puts(out, path)) < 0)
return error;
for (p = out->ptr; *p; p++) {
if (*p == '\\')
*p = '/';
}
return 0;
}
static const struct {
const char *file;
const char *hash;
size_t filelen;
} gitfiles[] = {
{ "gitignore", "gi250a", CONST_STRLEN("gitignore") },
{ "gitmodules", "gi7eba", CONST_STRLEN("gitmodules") },
{ "gitattributes", "gi7d29", CONST_STRLEN("gitattributes") }
};
extern int git_path_is_gitfile(const char *path, size_t pathlen, git_path_gitfile gitfile, git_path_fs fs)
{
const char *file, *hash;
size_t filelen;
if (!(gitfile >= GIT_PATH_GITFILE_GITIGNORE && gitfile < ARRAY_SIZE(gitfiles))) {
git_error_set(GIT_ERROR_OS, "invalid gitfile for path validation");
return -1;
}
file = gitfiles[gitfile].file;
filelen = gitfiles[gitfile].filelen;
hash = gitfiles[gitfile].hash;
switch (fs) {
case GIT_PATH_FS_GENERIC:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash) ||
!verify_dotgit_hfs_generic(path, pathlen, file, filelen);
case GIT_PATH_FS_NTFS:
return !verify_dotgit_ntfs_generic(path, pathlen, file, filelen, hash);
case GIT_PATH_FS_HFS:
return !verify_dotgit_hfs_generic(path, pathlen, file, filelen);
default:
git_error_set(GIT_ERROR_OS, "invalid filesystem for path validation");
return -1;
}
}
bool git_path_supports_symlinks(const char *dir)
{
git_buf path = GIT_BUF_INIT;
bool supported = false;
struct stat st;
int fd;
if ((fd = git_futils_mktmp(&path, dir, 0666)) < 0 ||
p_close(fd) < 0 ||
p_unlink(path.ptr) < 0 ||
p_symlink("testing", path.ptr) < 0 ||
p_lstat(path.ptr, &st) < 0)
goto done;
supported = (S_ISLNK(st.st_mode) != 0);
done:
if (path.size)
(void)p_unlink(path.ptr);
git_buf_dispose(&path);
return supported;
}
int git_path_validate_system_file_ownership(const char *path)
{
#ifndef GIT_WIN32
GIT_UNUSED(path);
return GIT_OK;
#else
git_win32_path buf;
PSID owner_sid;
PSECURITY_DESCRIPTOR descriptor = NULL;
HANDLE token;
TOKEN_USER *info = NULL;
DWORD err, len;
int ret;
if (git_win32_path_from_utf8(buf, path) < 0)
return -1;
err = GetNamedSecurityInfoW(buf, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION,
&owner_sid, NULL, NULL, NULL, &descriptor);
if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
ret = GIT_ENOTFOUND;
goto cleanup;
}
if (err != ERROR_SUCCESS) {
git_error_set(GIT_ERROR_OS, "failed to get security information");
ret = GIT_ERROR;
goto cleanup;
}
if (!IsValidSid(owner_sid)) {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is unknown");
ret = GIT_ERROR;
goto cleanup;
}
if (IsWellKnownSid(owner_sid, WinBuiltinAdministratorsSid) ||
IsWellKnownSid(owner_sid, WinLocalSystemSid)) {
ret = GIT_OK;
goto cleanup;
}
/* Obtain current user's SID */
if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token) &&
!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
info = git__malloc(len);
GIT_ERROR_CHECK_ALLOC(info);
if (!GetTokenInformation(token, TokenUser, info, len, &len)) {
git__free(info);
info = NULL;
}
}
/*
* If the file is owned by the same account that is running the current
* process, it's okay to read from that file.
*/
if (info && EqualSid(owner_sid, info->User.Sid))
ret = GIT_OK;
else {
git_error_set(GIT_ERROR_INVALID, "programdata configuration file owner is not valid");
ret = GIT_ERROR;
}
free(info);
cleanup:
if (descriptor)
LocalFree(descriptor);
return ret;
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3988_0 |
crossvul-cpp_data_bad_5845_11 | /*
BlueZ - Bluetooth protocol stack for Linux
Copyright (C) 2000-2001 Qualcomm Incorporated
Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/* Bluetooth SCO sockets. */
#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/sco.h>
static bool disable_esco;
static const struct proto_ops sco_sock_ops;
static struct bt_sock_list sco_sk_list = {
.lock = __RW_LOCK_UNLOCKED(sco_sk_list.lock)
};
static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent);
static void sco_chan_del(struct sock *sk, int err);
static void sco_sock_close(struct sock *sk);
static void sco_sock_kill(struct sock *sk);
/* ---- SCO timers ---- */
static void sco_sock_timeout(unsigned long arg)
{
struct sock *sk = (struct sock *) arg;
BT_DBG("sock %p state %d", sk, sk->sk_state);
bh_lock_sock(sk);
sk->sk_err = ETIMEDOUT;
sk->sk_state_change(sk);
bh_unlock_sock(sk);
sco_sock_kill(sk);
sock_put(sk);
}
static void sco_sock_set_timer(struct sock *sk, long timeout)
{
BT_DBG("sock %p state %d timeout %ld", sk, sk->sk_state, timeout);
sk_reset_timer(sk, &sk->sk_timer, jiffies + timeout);
}
static void sco_sock_clear_timer(struct sock *sk)
{
BT_DBG("sock %p state %d", sk, sk->sk_state);
sk_stop_timer(sk, &sk->sk_timer);
}
/* ---- SCO connections ---- */
static struct sco_conn *sco_conn_add(struct hci_conn *hcon)
{
struct hci_dev *hdev = hcon->hdev;
struct sco_conn *conn = hcon->sco_data;
if (conn)
return conn;
conn = kzalloc(sizeof(struct sco_conn), GFP_KERNEL);
if (!conn)
return NULL;
spin_lock_init(&conn->lock);
hcon->sco_data = conn;
conn->hcon = hcon;
if (hdev->sco_mtu > 0)
conn->mtu = hdev->sco_mtu;
else
conn->mtu = 60;
BT_DBG("hcon %p conn %p", hcon, conn);
return conn;
}
static struct sock *sco_chan_get(struct sco_conn *conn)
{
struct sock *sk = NULL;
sco_conn_lock(conn);
sk = conn->sk;
sco_conn_unlock(conn);
return sk;
}
static int sco_conn_del(struct hci_conn *hcon, int err)
{
struct sco_conn *conn = hcon->sco_data;
struct sock *sk;
if (!conn)
return 0;
BT_DBG("hcon %p conn %p, err %d", hcon, conn, err);
/* Kill socket */
sk = sco_chan_get(conn);
if (sk) {
bh_lock_sock(sk);
sco_sock_clear_timer(sk);
sco_chan_del(sk, err);
bh_unlock_sock(sk);
sco_sock_kill(sk);
}
hcon->sco_data = NULL;
kfree(conn);
return 0;
}
static int sco_chan_add(struct sco_conn *conn, struct sock *sk,
struct sock *parent)
{
int err = 0;
sco_conn_lock(conn);
if (conn->sk)
err = -EBUSY;
else
__sco_chan_add(conn, sk, parent);
sco_conn_unlock(conn);
return err;
}
static int sco_connect(struct sock *sk)
{
struct sco_conn *conn;
struct hci_conn *hcon;
struct hci_dev *hdev;
int err, type;
BT_DBG("%pMR -> %pMR", &sco_pi(sk)->src, &sco_pi(sk)->dst);
hdev = hci_get_route(&sco_pi(sk)->dst, &sco_pi(sk)->src);
if (!hdev)
return -EHOSTUNREACH;
hci_dev_lock(hdev);
if (lmp_esco_capable(hdev) && !disable_esco)
type = ESCO_LINK;
else
type = SCO_LINK;
if (sco_pi(sk)->setting == BT_VOICE_TRANSPARENT &&
(!lmp_transp_capable(hdev) || !lmp_esco_capable(hdev))) {
err = -EOPNOTSUPP;
goto done;
}
hcon = hci_connect_sco(hdev, type, &sco_pi(sk)->dst,
sco_pi(sk)->setting);
if (IS_ERR(hcon)) {
err = PTR_ERR(hcon);
goto done;
}
conn = sco_conn_add(hcon);
if (!conn) {
hci_conn_drop(hcon);
err = -ENOMEM;
goto done;
}
/* Update source addr of the socket */
bacpy(&sco_pi(sk)->src, &hcon->src);
err = sco_chan_add(conn, sk, NULL);
if (err)
goto done;
if (hcon->state == BT_CONNECTED) {
sco_sock_clear_timer(sk);
sk->sk_state = BT_CONNECTED;
} else {
sk->sk_state = BT_CONNECT;
sco_sock_set_timer(sk, sk->sk_sndtimeo);
}
done:
hci_dev_unlock(hdev);
hci_dev_put(hdev);
return err;
}
static int sco_send_frame(struct sock *sk, struct msghdr *msg, int len)
{
struct sco_conn *conn = sco_pi(sk)->conn;
struct sk_buff *skb;
int err;
/* Check outgoing MTU */
if (len > conn->mtu)
return -EINVAL;
BT_DBG("sk %p len %d", sk, len);
skb = bt_skb_send_alloc(sk, len, msg->msg_flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
kfree_skb(skb);
return -EFAULT;
}
hci_send_sco(conn->hcon, skb);
return len;
}
static void sco_recv_frame(struct sco_conn *conn, struct sk_buff *skb)
{
struct sock *sk = sco_chan_get(conn);
if (!sk)
goto drop;
BT_DBG("sk %p len %d", sk, skb->len);
if (sk->sk_state != BT_CONNECTED)
goto drop;
if (!sock_queue_rcv_skb(sk, skb))
return;
drop:
kfree_skb(skb);
}
/* -------- Socket interface ---------- */
static struct sock *__sco_get_sock_listen_by_addr(bdaddr_t *ba)
{
struct sock *sk;
sk_for_each(sk, &sco_sk_list.head) {
if (sk->sk_state != BT_LISTEN)
continue;
if (!bacmp(&sco_pi(sk)->src, ba))
return sk;
}
return NULL;
}
/* Find socket listening on source bdaddr.
* Returns closest match.
*/
static struct sock *sco_get_sock_listen(bdaddr_t *src)
{
struct sock *sk = NULL, *sk1 = NULL;
read_lock(&sco_sk_list.lock);
sk_for_each(sk, &sco_sk_list.head) {
if (sk->sk_state != BT_LISTEN)
continue;
/* Exact match. */
if (!bacmp(&sco_pi(sk)->src, src))
break;
/* Closest match */
if (!bacmp(&sco_pi(sk)->src, BDADDR_ANY))
sk1 = sk;
}
read_unlock(&sco_sk_list.lock);
return sk ? sk : sk1;
}
static void sco_sock_destruct(struct sock *sk)
{
BT_DBG("sk %p", sk);
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
}
static void sco_sock_cleanup_listen(struct sock *parent)
{
struct sock *sk;
BT_DBG("parent %p", parent);
/* Close not yet accepted channels */
while ((sk = bt_accept_dequeue(parent, NULL))) {
sco_sock_close(sk);
sco_sock_kill(sk);
}
parent->sk_state = BT_CLOSED;
sock_set_flag(parent, SOCK_ZAPPED);
}
/* Kill socket (only if zapped and orphan)
* Must be called on unlocked socket.
*/
static void sco_sock_kill(struct sock *sk)
{
if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket)
return;
BT_DBG("sk %p state %d", sk, sk->sk_state);
/* Kill poor orphan */
bt_sock_unlink(&sco_sk_list, sk);
sock_set_flag(sk, SOCK_DEAD);
sock_put(sk);
}
static void __sco_sock_close(struct sock *sk)
{
BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket);
switch (sk->sk_state) {
case BT_LISTEN:
sco_sock_cleanup_listen(sk);
break;
case BT_CONNECTED:
case BT_CONFIG:
if (sco_pi(sk)->conn->hcon) {
sk->sk_state = BT_DISCONN;
sco_sock_set_timer(sk, SCO_DISCONN_TIMEOUT);
hci_conn_drop(sco_pi(sk)->conn->hcon);
sco_pi(sk)->conn->hcon = NULL;
} else
sco_chan_del(sk, ECONNRESET);
break;
case BT_CONNECT2:
case BT_CONNECT:
case BT_DISCONN:
sco_chan_del(sk, ECONNRESET);
break;
default:
sock_set_flag(sk, SOCK_ZAPPED);
break;
}
}
/* Must be called on unlocked socket. */
static void sco_sock_close(struct sock *sk)
{
sco_sock_clear_timer(sk);
lock_sock(sk);
__sco_sock_close(sk);
release_sock(sk);
sco_sock_kill(sk);
}
static void sco_sock_init(struct sock *sk, struct sock *parent)
{
BT_DBG("sk %p", sk);
if (parent) {
sk->sk_type = parent->sk_type;
bt_sk(sk)->flags = bt_sk(parent)->flags;
security_sk_clone(parent, sk);
}
}
static struct proto sco_proto = {
.name = "SCO",
.owner = THIS_MODULE,
.obj_size = sizeof(struct sco_pinfo)
};
static struct sock *sco_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio)
{
struct sock *sk;
sk = sk_alloc(net, PF_BLUETOOTH, prio, &sco_proto);
if (!sk)
return NULL;
sock_init_data(sock, sk);
INIT_LIST_HEAD(&bt_sk(sk)->accept_q);
sk->sk_destruct = sco_sock_destruct;
sk->sk_sndtimeo = SCO_CONN_TIMEOUT;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = proto;
sk->sk_state = BT_OPEN;
sco_pi(sk)->setting = BT_VOICE_CVSD_16BIT;
setup_timer(&sk->sk_timer, sco_sock_timeout, (unsigned long)sk);
bt_sock_link(&sco_sk_list, sk);
return sk;
}
static int sco_sock_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
BT_DBG("sock %p", sock);
sock->state = SS_UNCONNECTED;
if (sock->type != SOCK_SEQPACKET)
return -ESOCKTNOSUPPORT;
sock->ops = &sco_sock_ops;
sk = sco_sock_alloc(net, sock, protocol, GFP_ATOMIC);
if (!sk)
return -ENOMEM;
sco_sock_init(sk, NULL);
return 0;
}
static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_sco *sa = (struct sockaddr_sco *) addr;
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EINVAL;
goto done;
}
bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr);
sk->sk_state = BT_BOUND;
done:
release_sock(sk);
return err;
}
static int sco_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags)
{
struct sockaddr_sco *sa = (struct sockaddr_sco *) addr;
struct sock *sk = sock->sk;
int err;
BT_DBG("sk %p", sk);
if (alen < sizeof(struct sockaddr_sco) ||
addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND)
return -EBADFD;
if (sk->sk_type != SOCK_SEQPACKET)
return -EINVAL;
lock_sock(sk);
/* Set destination address and psm */
bacpy(&sco_pi(sk)->dst, &sa->sco_bdaddr);
err = sco_connect(sk);
if (err)
goto done;
err = bt_sock_wait_state(sk, BT_CONNECTED,
sock_sndtimeo(sk, flags & O_NONBLOCK));
done:
release_sock(sk);
return err;
}
static int sco_sock_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
bdaddr_t *src = &sco_pi(sk)->src;
int err = 0;
BT_DBG("sk %p backlog %d", sk, backlog);
lock_sock(sk);
if (sk->sk_state != BT_BOUND) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EINVAL;
goto done;
}
write_lock(&sco_sk_list.lock);
if (__sco_get_sock_listen_by_addr(src)) {
err = -EADDRINUSE;
goto unlock;
}
sk->sk_max_ack_backlog = backlog;
sk->sk_ack_backlog = 0;
sk->sk_state = BT_LISTEN;
unlock:
write_unlock(&sco_sk_list.lock);
done:
release_sock(sk);
return err;
}
static int sco_sock_accept(struct socket *sock, struct socket *newsock, int flags)
{
DECLARE_WAITQUEUE(wait, current);
struct sock *sk = sock->sk, *ch;
long timeo;
int err = 0;
lock_sock(sk);
timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
BT_DBG("sk %p timeo %ld", sk, timeo);
/* Wait for an incoming connection. (wake-one). */
add_wait_queue_exclusive(sk_sleep(sk), &wait);
while (1) {
set_current_state(TASK_INTERRUPTIBLE);
if (sk->sk_state != BT_LISTEN) {
err = -EBADFD;
break;
}
ch = bt_accept_dequeue(sk, newsock);
if (ch)
break;
if (!timeo) {
err = -EAGAIN;
break;
}
if (signal_pending(current)) {
err = sock_intr_errno(timeo);
break;
}
release_sock(sk);
timeo = schedule_timeout(timeo);
lock_sock(sk);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(sk_sleep(sk), &wait);
if (err)
goto done;
newsock->state = SS_CONNECTED;
BT_DBG("new socket %p", ch);
done:
release_sock(sk);
return err;
}
static int sco_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer)
{
struct sockaddr_sco *sa = (struct sockaddr_sco *) addr;
struct sock *sk = sock->sk;
BT_DBG("sock %p, sk %p", sock, sk);
addr->sa_family = AF_BLUETOOTH;
*len = sizeof(struct sockaddr_sco);
if (peer)
bacpy(&sa->sco_bdaddr, &sco_pi(sk)->dst);
else
bacpy(&sa->sco_bdaddr, &sco_pi(sk)->src);
return 0;
}
static int sco_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
int err;
BT_DBG("sock %p, sk %p", sock, sk);
err = sock_error(sk);
if (err)
return err;
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
lock_sock(sk);
if (sk->sk_state == BT_CONNECTED)
err = sco_send_frame(sk, msg, len);
else
err = -ENOTCONN;
release_sock(sk);
return err;
}
static void sco_conn_defer_accept(struct hci_conn *conn, u16 setting)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("conn %p", conn);
conn->state = BT_CONFIG;
if (!lmp_esco_capable(hdev)) {
struct hci_cp_accept_conn_req cp;
bacpy(&cp.bdaddr, &conn->dst);
cp.role = 0x00; /* Ignored */
hci_send_cmd(hdev, HCI_OP_ACCEPT_CONN_REQ, sizeof(cp), &cp);
} else {
struct hci_cp_accept_sync_conn_req cp;
bacpy(&cp.bdaddr, &conn->dst);
cp.pkt_type = cpu_to_le16(conn->pkt_type);
cp.tx_bandwidth = __constant_cpu_to_le32(0x00001f40);
cp.rx_bandwidth = __constant_cpu_to_le32(0x00001f40);
cp.content_format = cpu_to_le16(setting);
switch (setting & SCO_AIRMODE_MASK) {
case SCO_AIRMODE_TRANSP:
if (conn->pkt_type & ESCO_2EV3)
cp.max_latency = __constant_cpu_to_le16(0x0008);
else
cp.max_latency = __constant_cpu_to_le16(0x000D);
cp.retrans_effort = 0x02;
break;
case SCO_AIRMODE_CVSD:
cp.max_latency = __constant_cpu_to_le16(0xffff);
cp.retrans_effort = 0xff;
break;
}
hci_send_cmd(hdev, HCI_OP_ACCEPT_SYNC_CONN_REQ,
sizeof(cp), &cp);
}
}
static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sco_pinfo *pi = sco_pi(sk);
lock_sock(sk);
if (sk->sk_state == BT_CONNECT2 &&
test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) {
sco_conn_defer_accept(pi->conn->hcon, pi->setting);
sk->sk_state = BT_CONFIG;
msg->msg_namelen = 0;
release_sock(sk);
return 0;
}
release_sock(sk);
return bt_sock_recvmsg(iocb, sock, msg, len, flags);
}
static int sco_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int len, err = 0;
struct bt_voice voice;
u32 opt;
BT_DBG("sk %p", sk);
lock_sock(sk);
switch (optname) {
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (get_user(opt, (u32 __user *) optval)) {
err = -EFAULT;
break;
}
if (opt)
set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
else
clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags);
break;
case BT_VOICE:
if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND &&
sk->sk_state != BT_CONNECT2) {
err = -EINVAL;
break;
}
voice.setting = sco_pi(sk)->setting;
len = min_t(unsigned int, sizeof(voice), optlen);
if (copy_from_user((char *) &voice, optval, len)) {
err = -EFAULT;
break;
}
/* Explicitly check for these values */
if (voice.setting != BT_VOICE_TRANSPARENT &&
voice.setting != BT_VOICE_CVSD_16BIT) {
err = -EINVAL;
break;
}
sco_pi(sk)->setting = voice.setting;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct sco_options opts;
struct sco_conninfo cinfo;
int len, err = 0;
BT_DBG("sk %p", sk);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case SCO_OPTIONS:
if (sk->sk_state != BT_CONNECTED &&
!(sk->sk_state == BT_CONNECT2 &&
test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags))) {
err = -ENOTCONN;
break;
}
opts.mtu = sco_pi(sk)->conn->mtu;
BT_DBG("mtu %d", opts.mtu);
len = min_t(unsigned int, len, sizeof(opts));
if (copy_to_user(optval, (char *)&opts, len))
err = -EFAULT;
break;
case SCO_CONNINFO:
if (sk->sk_state != BT_CONNECTED &&
!(sk->sk_state == BT_CONNECT2 &&
test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags))) {
err = -ENOTCONN;
break;
}
memset(&cinfo, 0, sizeof(cinfo));
cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle;
memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3);
len = min_t(unsigned int, len, sizeof(cinfo));
if (copy_to_user(optval, (char *)&cinfo, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int sco_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
int len, err = 0;
struct bt_voice voice;
BT_DBG("sk %p", sk);
if (level == SOL_SCO)
return sco_sock_getsockopt_old(sock, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
lock_sock(sk);
switch (optname) {
case BT_DEFER_SETUP:
if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) {
err = -EINVAL;
break;
}
if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags),
(u32 __user *) optval))
err = -EFAULT;
break;
case BT_VOICE:
voice.setting = sco_pi(sk)->setting;
len = min_t(unsigned int, len, sizeof(voice));
if (copy_to_user(optval, (char *)&voice, len))
err = -EFAULT;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int sco_sock_shutdown(struct socket *sock, int how)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
lock_sock(sk);
if (!sk->sk_shutdown) {
sk->sk_shutdown = SHUTDOWN_MASK;
sco_sock_clear_timer(sk);
__sco_sock_close(sk);
if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime)
err = bt_sock_wait_state(sk, BT_CLOSED,
sk->sk_lingertime);
}
release_sock(sk);
return err;
}
static int sco_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
int err = 0;
BT_DBG("sock %p, sk %p", sock, sk);
if (!sk)
return 0;
sco_sock_close(sk);
if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) {
lock_sock(sk);
err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime);
release_sock(sk);
}
sock_orphan(sk);
sco_sock_kill(sk);
return err;
}
static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent)
{
BT_DBG("conn %p", conn);
sco_pi(sk)->conn = conn;
conn->sk = sk;
if (parent)
bt_accept_enqueue(parent, sk);
}
/* Delete channel.
* Must be called on the locked socket. */
static void sco_chan_del(struct sock *sk, int err)
{
struct sco_conn *conn;
conn = sco_pi(sk)->conn;
BT_DBG("sk %p, conn %p, err %d", sk, conn, err);
if (conn) {
sco_conn_lock(conn);
conn->sk = NULL;
sco_pi(sk)->conn = NULL;
sco_conn_unlock(conn);
if (conn->hcon)
hci_conn_drop(conn->hcon);
}
sk->sk_state = BT_CLOSED;
sk->sk_err = err;
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_ZAPPED);
}
static void sco_conn_ready(struct sco_conn *conn)
{
struct sock *parent;
struct sock *sk = conn->sk;
BT_DBG("conn %p", conn);
if (sk) {
sco_sock_clear_timer(sk);
bh_lock_sock(sk);
sk->sk_state = BT_CONNECTED;
sk->sk_state_change(sk);
bh_unlock_sock(sk);
} else {
sco_conn_lock(conn);
parent = sco_get_sock_listen(&conn->hcon->src);
if (!parent) {
sco_conn_unlock(conn);
return;
}
bh_lock_sock(parent);
sk = sco_sock_alloc(sock_net(parent), NULL,
BTPROTO_SCO, GFP_ATOMIC);
if (!sk) {
bh_unlock_sock(parent);
sco_conn_unlock(conn);
return;
}
sco_sock_init(sk, parent);
bacpy(&sco_pi(sk)->src, &conn->hcon->src);
bacpy(&sco_pi(sk)->dst, &conn->hcon->dst);
hci_conn_hold(conn->hcon);
__sco_chan_add(conn, sk, parent);
if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags))
sk->sk_state = BT_CONNECT2;
else
sk->sk_state = BT_CONNECTED;
/* Wake up parent */
parent->sk_data_ready(parent, 1);
bh_unlock_sock(parent);
sco_conn_unlock(conn);
}
}
/* ----- SCO interface with lower layer (HCI) ----- */
int sco_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr, __u8 *flags)
{
struct sock *sk;
int lm = 0;
BT_DBG("hdev %s, bdaddr %pMR", hdev->name, bdaddr);
/* Find listening sockets */
read_lock(&sco_sk_list.lock);
sk_for_each(sk, &sco_sk_list.head) {
if (sk->sk_state != BT_LISTEN)
continue;
if (!bacmp(&sco_pi(sk)->src, &hdev->bdaddr) ||
!bacmp(&sco_pi(sk)->src, BDADDR_ANY)) {
lm |= HCI_LM_ACCEPT;
if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags))
*flags |= HCI_PROTO_DEFER;
break;
}
}
read_unlock(&sco_sk_list.lock);
return lm;
}
void sco_connect_cfm(struct hci_conn *hcon, __u8 status)
{
BT_DBG("hcon %p bdaddr %pMR status %d", hcon, &hcon->dst, status);
if (!status) {
struct sco_conn *conn;
conn = sco_conn_add(hcon);
if (conn)
sco_conn_ready(conn);
} else
sco_conn_del(hcon, bt_to_errno(status));
}
void sco_disconn_cfm(struct hci_conn *hcon, __u8 reason)
{
BT_DBG("hcon %p reason %d", hcon, reason);
sco_conn_del(hcon, bt_to_errno(reason));
}
int sco_recv_scodata(struct hci_conn *hcon, struct sk_buff *skb)
{
struct sco_conn *conn = hcon->sco_data;
if (!conn)
goto drop;
BT_DBG("conn %p len %d", conn, skb->len);
if (skb->len) {
sco_recv_frame(conn, skb);
return 0;
}
drop:
kfree_skb(skb);
return 0;
}
static int sco_debugfs_show(struct seq_file *f, void *p)
{
struct sock *sk;
read_lock(&sco_sk_list.lock);
sk_for_each(sk, &sco_sk_list.head) {
seq_printf(f, "%pMR %pMR %d\n", &sco_pi(sk)->src,
&sco_pi(sk)->dst, sk->sk_state);
}
read_unlock(&sco_sk_list.lock);
return 0;
}
static int sco_debugfs_open(struct inode *inode, struct file *file)
{
return single_open(file, sco_debugfs_show, inode->i_private);
}
static const struct file_operations sco_debugfs_fops = {
.open = sco_debugfs_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static struct dentry *sco_debugfs;
static const struct proto_ops sco_sock_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.release = sco_sock_release,
.bind = sco_sock_bind,
.connect = sco_sock_connect,
.listen = sco_sock_listen,
.accept = sco_sock_accept,
.getname = sco_sock_getname,
.sendmsg = sco_sock_sendmsg,
.recvmsg = sco_sock_recvmsg,
.poll = bt_sock_poll,
.ioctl = bt_sock_ioctl,
.mmap = sock_no_mmap,
.socketpair = sock_no_socketpair,
.shutdown = sco_sock_shutdown,
.setsockopt = sco_sock_setsockopt,
.getsockopt = sco_sock_getsockopt
};
static const struct net_proto_family sco_sock_family_ops = {
.family = PF_BLUETOOTH,
.owner = THIS_MODULE,
.create = sco_sock_create,
};
int __init sco_init(void)
{
int err;
err = proto_register(&sco_proto, 0);
if (err < 0)
return err;
err = bt_sock_register(BTPROTO_SCO, &sco_sock_family_ops);
if (err < 0) {
BT_ERR("SCO socket registration failed");
goto error;
}
err = bt_procfs_init(&init_net, "sco", &sco_sk_list, NULL);
if (err < 0) {
BT_ERR("Failed to create SCO proc file");
bt_sock_unregister(BTPROTO_SCO);
goto error;
}
BT_INFO("SCO socket layer initialized");
if (IS_ERR_OR_NULL(bt_debugfs))
return 0;
sco_debugfs = debugfs_create_file("sco", 0444, bt_debugfs,
NULL, &sco_debugfs_fops);
return 0;
error:
proto_unregister(&sco_proto);
return err;
}
void __exit sco_exit(void)
{
bt_procfs_cleanup(&init_net, "sco");
debugfs_remove(sco_debugfs);
bt_sock_unregister(BTPROTO_SCO);
proto_unregister(&sco_proto);
}
module_param(disable_esco, bool, 0644);
MODULE_PARM_DESC(disable_esco, "Disable eSCO connection creation");
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_11 |
crossvul-cpp_data_good_874_0 | /* bubblewrap
* Copyright (C) 2016 Alexander Larsson
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <poll.h>
#include <sched.h>
#include <pwd.h>
#include <grp.h>
#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/eventfd.h>
#include <sys/fsuid.h>
#include <sys/signalfd.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <linux/sched.h>
#include <linux/seccomp.h>
#include <linux/filter.h>
#include "utils.h"
#include "network.h"
#include "bind-mount.h"
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000 /* New cgroup namespace */
#endif
/* Globals to avoid having to use getuid(), since the uid/gid changes during runtime */
static uid_t real_uid;
static gid_t real_gid;
static uid_t overflow_uid;
static gid_t overflow_gid;
static bool is_privileged; /* See acquire_privs() */
static const char *argv0;
static const char *host_tty_dev;
static int proc_fd = -1;
static const char *opt_exec_label = NULL;
static const char *opt_file_label = NULL;
static bool opt_as_pid_1;
const char *opt_chdir_path = NULL;
bool opt_unshare_user = FALSE;
bool opt_unshare_user_try = FALSE;
bool opt_unshare_pid = FALSE;
bool opt_unshare_ipc = FALSE;
bool opt_unshare_net = FALSE;
bool opt_unshare_uts = FALSE;
bool opt_unshare_cgroup = FALSE;
bool opt_unshare_cgroup_try = FALSE;
bool opt_needs_devpts = FALSE;
bool opt_new_session = FALSE;
bool opt_die_with_parent = FALSE;
uid_t opt_sandbox_uid = -1;
gid_t opt_sandbox_gid = -1;
int opt_sync_fd = -1;
int opt_block_fd = -1;
int opt_userns_block_fd = -1;
int opt_info_fd = -1;
int opt_json_status_fd = -1;
int opt_seccomp_fd = -1;
const char *opt_sandbox_hostname = NULL;
char *opt_args_data = NULL; /* owned */
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
typedef enum {
SETUP_BIND_MOUNT,
SETUP_RO_BIND_MOUNT,
SETUP_DEV_BIND_MOUNT,
SETUP_MOUNT_PROC,
SETUP_MOUNT_DEV,
SETUP_MOUNT_TMPFS,
SETUP_MOUNT_MQUEUE,
SETUP_MAKE_DIR,
SETUP_MAKE_FILE,
SETUP_MAKE_BIND_FILE,
SETUP_MAKE_RO_BIND_FILE,
SETUP_MAKE_SYMLINK,
SETUP_REMOUNT_RO_NO_RECURSIVE,
SETUP_SET_HOSTNAME,
} SetupOpType;
typedef enum {
NO_CREATE_DEST = (1 << 0),
ALLOW_NOTEXIST = (2 << 0),
} SetupOpFlag;
typedef struct _SetupOp SetupOp;
struct _SetupOp
{
SetupOpType type;
const char *source;
const char *dest;
int fd;
SetupOpFlag flags;
SetupOp *next;
};
typedef struct _LockFile LockFile;
struct _LockFile
{
const char *path;
int fd;
LockFile *next;
};
static SetupOp *ops = NULL;
static SetupOp *last_op = NULL;
static LockFile *lock_files = NULL;
static LockFile *last_lock_file = NULL;
enum {
PRIV_SEP_OP_DONE,
PRIV_SEP_OP_BIND_MOUNT,
PRIV_SEP_OP_PROC_MOUNT,
PRIV_SEP_OP_TMPFS_MOUNT,
PRIV_SEP_OP_DEVPTS_MOUNT,
PRIV_SEP_OP_MQUEUE_MOUNT,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE,
PRIV_SEP_OP_SET_HOSTNAME,
};
typedef struct
{
uint32_t op;
uint32_t flags;
uint32_t arg1_offset;
uint32_t arg2_offset;
} PrivSepOp;
static SetupOp *
setup_op_new (SetupOpType type)
{
SetupOp *op = xcalloc (sizeof (SetupOp));
op->type = type;
op->fd = -1;
op->flags = 0;
if (last_op != NULL)
last_op->next = op;
else
ops = op;
last_op = op;
return op;
}
static LockFile *
lock_file_new (const char *path)
{
LockFile *lock = xcalloc (sizeof (LockFile));
lock->path = path;
if (last_lock_file != NULL)
last_lock_file->next = lock;
else
lock_files = lock;
last_lock_file = lock;
return lock;
}
static void
usage (int ecode, FILE *out)
{
fprintf (out, "usage: %s [OPTIONS...] [--] COMMAND [ARGS...]\n\n", argv0);
fprintf (out,
" --help Print this help\n"
" --version Print version\n"
" --args FD Parse NUL-separated args from FD\n"
" --unshare-all Unshare every namespace we support by default\n"
" --share-net Retain the network namespace (can only combine with --unshare-all)\n"
" --unshare-user Create new user namespace (may be automatically implied if not setuid)\n"
" --unshare-user-try Create new user namespace if possible else continue by skipping it\n"
" --unshare-ipc Create new ipc namespace\n"
" --unshare-pid Create new pid namespace\n"
" --unshare-net Create new network namespace\n"
" --unshare-uts Create new uts namespace\n"
" --unshare-cgroup Create new cgroup namespace\n"
" --unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it\n"
" --uid UID Custom uid in the sandbox (requires --unshare-user)\n"
" --gid GID Custom gid in the sandbox (requires --unshare-user)\n"
" --hostname NAME Custom hostname in the sandbox (requires --unshare-uts)\n"
" --chdir DIR Change directory to DIR\n"
" --setenv VAR VALUE Set an environment variable\n"
" --unsetenv VAR Unset an environment variable\n"
" --lock-file DEST Take a lock on DEST while sandbox is running\n"
" --sync-fd FD Keep this fd open while sandbox is running\n"
" --bind SRC DEST Bind mount the host path SRC on DEST\n"
" --bind-try SRC DEST Equal to --bind but ignores non-existent SRC\n"
" --dev-bind SRC DEST Bind mount the host path SRC on DEST, allowing device access\n"
" --dev-bind-try SRC DEST Equal to --dev-bind but ignores non-existent SRC\n"
" --ro-bind SRC DEST Bind mount the host path SRC readonly on DEST\n"
" --ro-bind-try SRC DEST Equal to --ro-bind but ignores non-existent SRC\n"
" --remount-ro DEST Remount DEST as readonly; does not recursively remount\n"
" --exec-label LABEL Exec label for the sandbox\n"
" --file-label LABEL File label for temporary sandbox content\n"
" --proc DEST Mount new procfs on DEST\n"
" --dev DEST Mount new dev on DEST\n"
" --tmpfs DEST Mount new tmpfs on DEST\n"
" --mqueue DEST Mount new mqueue on DEST\n"
" --dir DEST Create dir at DEST\n"
" --file FD DEST Copy from FD to destination DEST\n"
" --bind-data FD DEST Copy from FD to file which is bind-mounted on DEST\n"
" --ro-bind-data FD DEST Copy from FD to file which is readonly bind-mounted on DEST\n"
" --symlink SRC DEST Create symlink at DEST with target SRC\n"
" --seccomp FD Load and use seccomp rules from FD\n"
" --block-fd FD Block on FD until some data to read is available\n"
" --userns-block-fd FD Block on FD until the user namespace is ready\n"
" --info-fd FD Write information about the running container to FD\n"
" --json-status-fd FD Write container status to FD as multiple JSON documents\n"
" --new-session Create a new terminal session\n"
" --die-with-parent Kills with SIGKILL child process (COMMAND) when bwrap or bwrap's parent dies.\n"
" --as-pid-1 Do not install a reaper process with PID=1\n"
" --cap-add CAP Add cap CAP when running as privileged user\n"
" --cap-drop CAP Drop cap CAP when running as privileged user\n"
);
exit (ecode);
}
/* If --die-with-parent was specified, use PDEATHSIG to ensure SIGKILL
* is sent to the current process when our parent dies.
*/
static void
handle_die_with_parent (void)
{
if (opt_die_with_parent && prctl (PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0) != 0)
die_with_error ("prctl");
}
static void
block_sigchild (void)
{
sigset_t mask;
int status;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_BLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
/* Reap any outstanding zombies that we may have inherited */
while (waitpid (-1, &status, WNOHANG) > 0)
;
}
static void
unblock_sigchild (void)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
if (sigprocmask (SIG_UNBLOCK, &mask, NULL) == -1)
die_with_error ("sigprocmask");
}
/* Closes all fd:s except 0,1,2 and the passed in array of extra fds */
static int
close_extra_fds (void *data, int fd)
{
int *extra_fds = (int *) data;
int i;
for (i = 0; extra_fds[i] != -1; i++)
if (fd == extra_fds[i])
return 0;
if (fd <= 2)
return 0;
close (fd);
return 0;
}
static int
propagate_exit_status (int status)
{
if (WIFEXITED (status))
return WEXITSTATUS (status);
/* The process died of a signal, we can't really report that, but we
* can at least be bash-compatible. The bash manpage says:
* The return value of a simple command is its
* exit status, or 128+n if the command is
* terminated by signal n.
*/
if (WIFSIGNALED (status))
return 128 + WTERMSIG (status);
/* Weird? */
return 255;
}
static void
dump_info (int fd, const char *output, bool exit_on_error)
{
size_t len = strlen (output);
if (write_to_fd (fd, output, len))
{
if (exit_on_error)
die_with_error ("Write to info_fd");
}
}
static void
report_child_exit_status (int exitc, int setup_finished_fd)
{
ssize_t s;
char data[2];
cleanup_free char *output = NULL;
if (opt_json_status_fd == -1 || setup_finished_fd == -1)
return;
s = TEMP_FAILURE_RETRY (read (setup_finished_fd, data, sizeof data));
if (s == -1 && errno != EAGAIN)
die_with_error ("read eventfd");
if (s != 1) // Is 0 if pipe closed before exec, is 2 if closed after exec.
return;
output = xasprintf ("{ \"exit-code\": %i }\n", exitc);
dump_info (opt_json_status_fd, output, FALSE);
close (opt_json_status_fd);
opt_json_status_fd = -1;
close (setup_finished_fd);
}
/* This stays around for as long as the initial process in the app does
* and when that exits it exits, propagating the exit status. We do this
* by having pid 1 in the sandbox detect this exit and tell the monitor
* the exit status via a eventfd. We also track the exit of the sandbox
* pid 1 via a signalfd for SIGCHLD, and exit with an error in this case.
* This is to catch e.g. problems during setup. */
static int
monitor_child (int event_fd, pid_t child_pid, int setup_finished_fd)
{
int res;
uint64_t val;
ssize_t s;
int signal_fd;
sigset_t mask;
struct pollfd fds[2];
int num_fds;
struct signalfd_siginfo fdsi;
int dont_close[] = {-1, -1, -1, -1};
int j = 0;
int exitc;
pid_t died_pid;
int died_status;
/* Close all extra fds in the monitoring process.
Any passed in fds have been passed on to the child anyway. */
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_json_status_fd != -1)
dont_close[j++] = opt_json_status_fd;
if (setup_finished_fd != -1)
dont_close[j++] = setup_finished_fd;
assert (j < sizeof(dont_close)/sizeof(*dont_close));
fdwalk (proc_fd, close_extra_fds, dont_close);
sigemptyset (&mask);
sigaddset (&mask, SIGCHLD);
signal_fd = signalfd (-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
if (signal_fd == -1)
die_with_error ("Can't create signalfd");
num_fds = 1;
fds[0].fd = signal_fd;
fds[0].events = POLLIN;
if (event_fd != -1)
{
fds[1].fd = event_fd;
fds[1].events = POLLIN;
num_fds++;
}
while (1)
{
fds[0].revents = fds[1].revents = 0;
res = poll (fds, num_fds, -1);
if (res == -1 && errno != EINTR)
die_with_error ("poll");
/* Always read from the eventfd first, if pid 2 died then pid 1 often
* dies too, and we could race, reporting that first and we'd lose
* the real exit status. */
if (event_fd != -1)
{
s = read (event_fd, &val, 8);
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read eventfd");
else if (s == 8)
{
exitc = (int) val - 1;
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
/* We need to read the signal_fd, or it will keep polling as read,
* however we ignore the details as we get them from waitpid
* below anyway */
s = read (signal_fd, &fdsi, sizeof (struct signalfd_siginfo));
if (s == -1 && errno != EINTR && errno != EAGAIN)
die_with_error ("read signalfd");
/* We may actually get several sigchld compressed into one
SIGCHLD, so we have to handle all of them. */
while ((died_pid = waitpid (-1, &died_status, WNOHANG)) > 0)
{
/* We may be getting sigchild from other children too. For instance if
someone created a child process, and then exec:ed bubblewrap. Ignore them */
if (died_pid == child_pid)
{
exitc = propagate_exit_status (died_status);
report_child_exit_status (exitc, setup_finished_fd);
return exitc;
}
}
}
die ("Should not be reached");
return 0;
}
/* This is pid 1 in the app sandbox. It is needed because we're using
* pid namespaces, and someone has to reap zombies in it. We also detect
* when the initial process (pid 2) dies and report its exit status to
* the monitor so that it can return it to the original spawner.
*
* When there are no other processes in the sandbox the wait will return
* ECHILD, and we then exit pid 1 to clean up the sandbox. */
static int
do_init (int event_fd, pid_t initial_pid, struct sock_fprog *seccomp_prog)
{
int initial_exit_status = 1;
LockFile *lock;
for (lock = lock_files; lock != NULL; lock = lock->next)
{
int fd = open (lock->path, O_RDONLY | O_CLOEXEC);
if (fd == -1)
die_with_error ("Unable to open lock file %s", lock->path);
struct flock l = {
.l_type = F_RDLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
if (fcntl (fd, F_SETLK, &l) < 0)
die_with_error ("Unable to lock file %s", lock->path);
/* Keep fd open to hang on to lock */
lock->fd = fd;
}
/* Optionally bind our lifecycle to that of the caller */
handle_die_with_parent ();
if (seccomp_prog != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
while (TRUE)
{
pid_t child;
int status;
child = wait (&status);
if (child == initial_pid && event_fd != -1)
{
uint64_t val;
int res UNUSED;
initial_exit_status = propagate_exit_status (status);
val = initial_exit_status + 1;
res = write (event_fd, &val, 8);
/* Ignore res, if e.g. the parent died and closed event_fd
we don't want to error out here */
}
if (child == -1 && errno != EINTR)
{
if (errno != ECHILD)
die_with_error ("init wait()");
break;
}
}
/* Close FDs. */
for (lock = lock_files; lock != NULL; lock = lock->next)
{
if (lock->fd >= 0)
{
close (lock->fd);
lock->fd = -1;
}
}
return initial_exit_status;
}
#define CAP_TO_MASK_0(x) (1L << ((x) & 31))
#define CAP_TO_MASK_1(x) CAP_TO_MASK_0(x - 32)
/* Set if --cap-add or --cap-drop were used */
static bool opt_cap_add_or_drop_used;
/* The capability set we'll target, used if above is true */
static uint32_t requested_caps[2] = {0, 0};
/* low 32bit caps needed */
#define REQUIRED_CAPS_0 (CAP_TO_MASK_0 (CAP_SYS_ADMIN) | CAP_TO_MASK_0 (CAP_SYS_CHROOT) | CAP_TO_MASK_0 (CAP_NET_ADMIN) | CAP_TO_MASK_0 (CAP_SETUID) | CAP_TO_MASK_0 (CAP_SETGID))
/* high 32bit caps needed */
#define REQUIRED_CAPS_1 0
static void
set_required_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
/* Drop all non-require capabilities */
data[0].effective = REQUIRED_CAPS_0;
data[0].permitted = REQUIRED_CAPS_0;
data[0].inheritable = 0;
data[1].effective = REQUIRED_CAPS_1;
data[1].permitted = REQUIRED_CAPS_1;
data[1].inheritable = 0;
if (capset (&hdr, data) < 0)
die_with_error ("capset failed");
}
static void
drop_all_caps (bool keep_requested_caps)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (keep_requested_caps)
{
/* Avoid calling capset() unless we need to; currently
* systemd-nspawn at least is known to install a seccomp
* policy denying capset() for dubious reasons.
* <https://github.com/projectatomic/bubblewrap/pull/122>
*/
if (!opt_cap_add_or_drop_used && real_uid == 0)
{
assert (!is_privileged);
return;
}
data[0].effective = requested_caps[0];
data[0].permitted = requested_caps[0];
data[0].inheritable = requested_caps[0];
data[1].effective = requested_caps[1];
data[1].permitted = requested_caps[1];
data[1].inheritable = requested_caps[1];
}
if (capset (&hdr, data) < 0)
{
/* While the above logic ensures we don't call capset() for the primary
* process unless configured to do so, we still try to drop privileges for
* the init process unconditionally. Since due to the systemd seccomp
* filter that will fail, let's just ignore it.
*/
if (errno == EPERM && real_uid == 0 && !is_privileged)
return;
else
die_with_error ("capset failed");
}
}
static bool
has_caps (void)
{
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget failed");
return data[0].permitted != 0 || data[1].permitted != 0;
}
/* Most of the code here is used both to add caps to the ambient capabilities
* and drop caps from the bounding set. Handle both cases here and add
* drop_cap_bounding_set/set_ambient_capabilities wrappers to facilitate its usage.
*/
static void
prctl_caps (uint32_t *caps, bool do_cap_bounding, bool do_set_ambient)
{
unsigned long cap;
/* We ignore both EINVAL and EPERM, as we are actually relying
* on PR_SET_NO_NEW_PRIVS to ensure the right capabilities are
* available. EPERM in particular can happen with old, buggy
* kernels. See:
* https://github.com/projectatomic/bubblewrap/pull/175#issuecomment-278051373
* https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/security/commoncap.c?id=160da84dbb39443fdade7151bc63a88f8e953077
*/
for (cap = 0; cap <= CAP_LAST_CAP; cap++)
{
bool keep = FALSE;
if (cap < 32)
{
if (CAP_TO_MASK_0 (cap) & caps[0])
keep = TRUE;
}
else
{
if (CAP_TO_MASK_1 (cap) & caps[1])
keep = TRUE;
}
if (keep && do_set_ambient)
{
#ifdef PR_CAP_AMBIENT
int res = prctl (PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, cap, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Adding ambient capability %ld", cap);
#else
/* We ignore the EINVAL that results from not having PR_CAP_AMBIENT
* in the current kernel at runtime, so also ignore not having it
* in the current kernel headers at compile-time */
#endif
}
if (!keep && do_cap_bounding)
{
int res = prctl (PR_CAPBSET_DROP, cap, 0, 0, 0);
if (res == -1 && !(errno == EINVAL || errno == EPERM))
die_with_error ("Dropping capability %ld from bounds", cap);
}
}
}
static void
drop_cap_bounding_set (bool drop_all)
{
if (!drop_all)
prctl_caps (requested_caps, TRUE, FALSE);
else
{
uint32_t no_caps[2] = {0, 0};
prctl_caps (no_caps, TRUE, FALSE);
}
}
static void
set_ambient_capabilities (void)
{
if (is_privileged)
return;
prctl_caps (requested_caps, FALSE, TRUE);
}
/* This acquires the privileges that the bwrap will need it to work.
* If bwrap is not setuid, then this does nothing, and it relies on
* unprivileged user namespaces to be used. This case is
* "is_privileged = FALSE".
*
* If bwrap is setuid, then we do things in phases.
* The first part is run as euid 0, but with fsuid as the real user.
* The second part, inside the child, is run as the real user but with
* capabilities.
* And finally we drop all capabilities.
* The reason for the above dance is to avoid having the setup phase
* being able to read files the user can't, while at the same time
* working around various kernel issues. See below for details.
*/
static void
acquire_privs (void)
{
uid_t euid, new_fsuid;
euid = geteuid ();
/* Are we setuid ? */
if (real_uid != euid)
{
if (euid != 0)
die ("Unexpected setuid user %d, should be 0", euid);
is_privileged = TRUE;
/* We want to keep running as euid=0 until at the clone()
* operation because doing so will make the user namespace be
* owned by root, which makes it not ptrace:able by the user as
* it otherwise would be. After that we will run fully as the
* user, which is necessary e.g. to be able to read from a fuse
* mount from the user.
*
* However, we don't want to accidentally mis-use euid=0 for
* escalated filesystem access before the clone(), so we set
* fsuid to the uid.
*/
if (setfsuid (real_uid) < 0)
die_with_error ("Unable to set fsuid");
/* setfsuid can't properly report errors, check that it worked (as per manpage) */
new_fsuid = setfsuid (-1);
if (new_fsuid != real_uid)
die ("Unable to set fsuid (was %d)", (int)new_fsuid);
/* We never need capabilities after execve(), so lets drop everything from the bounding set */
drop_cap_bounding_set (TRUE);
/* Keep only the required capabilities for setup */
set_required_caps ();
}
else if (real_uid != 0 && has_caps ())
{
/* We have some capabilities in the non-setuid case, which should not happen.
Probably caused by the binary being setcap instead of setuid which we
don't support anymore */
die ("Unexpected capabilities but not setuid, old file caps config?");
}
else if (real_uid == 0)
{
/* If our uid is 0, default to inheriting all caps; the caller
* can drop them via --cap-drop. This is used by at least rpm-ostree.
* Note this needs to happen before the argument parsing of --cap-drop.
*/
struct __user_cap_header_struct hdr = { _LINUX_CAPABILITY_VERSION_3, 0 };
struct __user_cap_data_struct data[2] = { { 0 } };
if (capget (&hdr, data) < 0)
die_with_error ("capget (for uid == 0) failed");
requested_caps[0] = data[0].effective;
requested_caps[1] = data[1].effective;
}
/* Else, we try unprivileged user namespaces */
}
/* This is called once we're inside the namespace */
static void
switch_to_user_with_privs (void)
{
/* If we're in a new user namespace, we got back the bounding set, clear it again */
if (opt_unshare_user)
drop_cap_bounding_set (FALSE);
if (!is_privileged)
return;
/* Tell kernel not clear capabilities when later dropping root uid */
if (prctl (PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_KEEPCAPS) failed");
if (setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
/* Regain effective required capabilities from permitted */
set_required_caps ();
}
/* Call setuid() and use capset() to adjust capabilities */
static void
drop_privs (bool keep_requested_caps)
{
assert (!keep_requested_caps || !is_privileged);
/* Drop root uid */
if (getuid () == 0 && setuid (opt_sandbox_uid) < 0)
die_with_error ("unable to drop root uid");
drop_all_caps (keep_requested_caps);
}
static char *
get_newroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/newroot/", path);
}
static char *
get_oldroot_path (const char *path)
{
while (*path == '/')
path++;
return strconcat ("/oldroot/", path);
}
static void
write_uid_gid_map (uid_t sandbox_uid,
uid_t parent_uid,
uid_t sandbox_gid,
uid_t parent_gid,
pid_t pid,
bool deny_groups,
bool map_root)
{
cleanup_free char *uid_map = NULL;
cleanup_free char *gid_map = NULL;
cleanup_free char *dir = NULL;
cleanup_fd int dir_fd = -1;
uid_t old_fsuid = -1;
if (pid == -1)
dir = xstrdup ("self");
else
dir = xasprintf ("%d", pid);
dir_fd = openat (proc_fd, dir, O_PATH);
if (dir_fd < 0)
die_with_error ("open /proc/%s failed", dir);
if (map_root && parent_uid != 0 && sandbox_uid != 0)
uid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_uid, sandbox_uid, parent_uid);
else
uid_map = xasprintf ("%d %d 1\n", sandbox_uid, parent_uid);
if (map_root && parent_gid != 0 && sandbox_gid != 0)
gid_map = xasprintf ("0 %d 1\n"
"%d %d 1\n", overflow_gid, sandbox_gid, parent_gid);
else
gid_map = xasprintf ("%d %d 1\n", sandbox_gid, parent_gid);
/* We have to be root to be allowed to write to the uid map
* for setuid apps, so temporary set fsuid to 0 */
if (is_privileged)
old_fsuid = setfsuid (0);
if (write_file_at (dir_fd, "uid_map", uid_map) != 0)
die_with_error ("setting up uid map");
if (deny_groups &&
write_file_at (dir_fd, "setgroups", "deny\n") != 0)
{
/* If /proc/[pid]/setgroups does not exist, assume we are
* running a linux kernel < 3.19, i.e. we live with the
* vulnerability known as CVE-2014-8989 in older kernels
* where setgroups does not exist.
*/
if (errno != ENOENT)
die_with_error ("error writing to setgroups");
}
if (write_file_at (dir_fd, "gid_map", gid_map) != 0)
die_with_error ("setting up gid map");
if (is_privileged)
{
setfsuid (old_fsuid);
if (setfsuid (-1) != real_uid)
die ("Unable to re-set fsuid");
}
}
static void
privileged_op (int privileged_op_socket,
uint32_t op,
uint32_t flags,
const char *arg1,
const char *arg2)
{
if (privileged_op_socket != -1)
{
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
PrivSepOp *op_buffer = (PrivSepOp *) buffer;
size_t buffer_size = sizeof (PrivSepOp);
uint32_t arg1_offset = 0, arg2_offset = 0;
/* We're unprivileged, send this request to the privileged part */
if (arg1 != NULL)
{
arg1_offset = buffer_size;
buffer_size += strlen (arg1) + 1;
}
if (arg2 != NULL)
{
arg2_offset = buffer_size;
buffer_size += strlen (arg2) + 1;
}
if (buffer_size >= sizeof (buffer))
die ("privilege separation operation to large");
op_buffer->op = op;
op_buffer->flags = flags;
op_buffer->arg1_offset = arg1_offset;
op_buffer->arg2_offset = arg2_offset;
if (arg1 != NULL)
strcpy ((char *) buffer + arg1_offset, arg1);
if (arg2 != NULL)
strcpy ((char *) buffer + arg2_offset, arg2);
if (write (privileged_op_socket, buffer, buffer_size) != buffer_size)
die ("Can't write to privileged_op_socket");
if (read (privileged_op_socket, buffer, 1) != 1)
die ("Can't read from privileged_op_socket");
return;
}
/*
* This runs a privileged request for the unprivileged setup
* code. Note that since the setup code is unprivileged it is not as
* trusted, so we need to verify that all requests only affect the
* child namespace as set up by the privileged parts of the setup,
* and that all the code is very careful about handling input.
*
* This means:
* * Bind mounts are safe, since we always use filesystem namespace. They
* must be recursive though, as otherwise you can use a non-recursive bind
* mount to access an otherwise over-mounted mountpoint.
* * Mounting proc, tmpfs, mqueue, devpts in the child namespace is assumed to
* be safe.
* * Remounting RO (even non-recursive) is safe because it decreases privileges.
* * sethostname() is safe only if we set up a UTS namespace
*/
switch (op)
{
case PRIV_SEP_OP_DONE:
break;
case PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE:
if (bind_mount (proc_fd, NULL, arg2, BIND_READONLY) != 0)
die_with_error ("Can't remount readonly on %s", arg2);
break;
case PRIV_SEP_OP_BIND_MOUNT:
/* We always bind directories recursively, otherwise this would let us
access files that are otherwise covered on the host */
if (bind_mount (proc_fd, arg1, arg2, BIND_RECURSIVE | flags) != 0)
die_with_error ("Can't bind mount %s on %s", arg1, arg2);
break;
case PRIV_SEP_OP_PROC_MOUNT:
if (mount ("proc", arg1, "proc", MS_NOSUID | MS_NOEXEC | MS_NODEV, NULL) != 0)
die_with_error ("Can't mount proc on %s", arg1);
break;
case PRIV_SEP_OP_TMPFS_MOUNT:
{
cleanup_free char *opt = label_mount ("mode=0755", opt_file_label);
if (mount ("tmpfs", arg1, "tmpfs", MS_NOSUID | MS_NODEV, opt) != 0)
die_with_error ("Can't mount tmpfs on %s", arg1);
break;
}
case PRIV_SEP_OP_DEVPTS_MOUNT:
if (mount ("devpts", arg1, "devpts", MS_NOSUID | MS_NOEXEC,
"newinstance,ptmxmode=0666,mode=620") != 0)
die_with_error ("Can't mount devpts on %s", arg1);
break;
case PRIV_SEP_OP_MQUEUE_MOUNT:
if (mount ("mqueue", arg1, "mqueue", 0, NULL) != 0)
die_with_error ("Can't mount mqueue on %s", arg1);
break;
case PRIV_SEP_OP_SET_HOSTNAME:
/* This is checked at the start, but lets verify it here in case
something manages to send hacked priv-sep operation requests. */
if (!opt_unshare_uts)
die ("Refusing to set hostname in original namespace");
if (sethostname (arg1, strlen(arg1)) != 0)
die_with_error ("Can't set hostname to %s", arg1);
break;
default:
die ("Unexpected privileged op %d", op);
}
}
/* This is run unprivileged in the child namespace but can request
* some privileged operations (also in the child namespace) via the
* privileged_op_socket.
*/
static void
setup_newroot (bool unshare_pid,
int privileged_op_socket)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
cleanup_free char *source = NULL;
cleanup_free char *dest = NULL;
int source_mode = 0;
int i;
if (op->source &&
op->type != SETUP_MAKE_SYMLINK)
{
source = get_oldroot_path (op->source);
source_mode = get_file_mode (source);
if (source_mode < 0)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
continue; /* Ignore and move on */
die_with_error("Can't get type of source %s", op->source);
}
}
if (op->dest &&
(op->flags & NO_CREATE_DEST) == 0)
{
dest = get_newroot_path (op->dest);
if (mkdir_with_parents (dest, 0755, FALSE) != 0)
die_with_error ("Can't mkdir parents for %s", op->dest);
}
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
if (source_mode == S_IFDIR)
{
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
}
else if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_RO_BIND_MOUNT ? BIND_READONLY : 0) |
(op->type == SETUP_DEV_BIND_MOUNT ? BIND_DEVICES : 0),
source, dest);
break;
case SETUP_REMOUNT_RO_NO_RECURSIVE:
privileged_op (privileged_op_socket,
PRIV_SEP_OP_REMOUNT_RO_NO_RECURSIVE, 0, NULL, dest);
break;
case SETUP_MOUNT_PROC:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
if (unshare_pid)
{
/* Our own procfs */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_PROC_MOUNT, 0,
dest, NULL);
}
else
{
/* Use system procfs, as we share pid namespace anyway */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, 0,
"oldroot/proc", dest);
}
/* There are a bunch of weird old subdirs of /proc that could potentially be
problematic (for instance /proc/sysrq-trigger lets you shut down the machine
if you have write access). We should not have access to these as a non-privileged
user, but lets cover them anyway just to make sure */
const char *cover_proc_dirs[] = { "sys", "sysrq-trigger", "irq", "bus" };
for (i = 0; i < N_ELEMENTS (cover_proc_dirs); i++)
{
cleanup_free char *subdir = strconcat3 (dest, "/", cover_proc_dirs[i]);
if (access (subdir, W_OK) < 0)
{
/* The file is already read-only or doesn't exist. */
if (errno == EACCES || errno == ENOENT)
continue;
die_with_error ("Can't access %s", subdir);
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_READONLY,
subdir, subdir);
}
break;
case SETUP_MOUNT_DEV:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
static const char *const devnodes[] = { "null", "zero", "full", "random", "urandom", "tty" };
for (i = 0; i < N_ELEMENTS (devnodes); i++)
{
cleanup_free char *node_dest = strconcat3 (dest, "/", devnodes[i]);
cleanup_free char *node_src = strconcat ("/oldroot/dev/", devnodes[i]);
if (create_file (node_dest, 0666, NULL) != 0)
die_with_error ("Can't create file %s/%s", op->dest, devnodes[i]);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
node_src, node_dest);
}
static const char *const stdionodes[] = { "stdin", "stdout", "stderr" };
for (i = 0; i < N_ELEMENTS (stdionodes); i++)
{
cleanup_free char *target = xasprintf ("/proc/self/fd/%d", i);
cleanup_free char *node_dest = strconcat3 (dest, "/", stdionodes[i]);
if (symlink (target, node_dest) < 0)
die_with_error ("Can't create symlink %s/%s", op->dest, stdionodes[i]);
}
/* /dev/fd and /dev/core - legacy, but both nspawn and docker do these */
{ cleanup_free char *dev_fd = strconcat (dest, "/fd");
if (symlink ("/proc/self/fd", dev_fd) < 0)
die_with_error ("Can't create symlink %s", dev_fd);
}
{ cleanup_free char *dev_core = strconcat (dest, "/core");
if (symlink ("/proc/kcore", dev_core) < 0)
die_with_error ("Can't create symlink %s", dev_core);
}
{
cleanup_free char *pts = strconcat (dest, "/pts");
cleanup_free char *ptmx = strconcat (dest, "/ptmx");
cleanup_free char *shm = strconcat (dest, "/shm");
if (mkdir (shm, 0755) == -1)
die_with_error ("Can't create %s/shm", op->dest);
if (mkdir (pts, 0755) == -1)
die_with_error ("Can't create %s/devpts", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DEVPTS_MOUNT, 0, pts, NULL);
if (symlink ("pts/ptmx", ptmx) != 0)
die_with_error ("Can't make symlink at %s/ptmx", op->dest);
}
/* If stdout is a tty, that means the sandbox can write to the
outside-sandbox tty. In that case we also create a /dev/console
that points to this tty device. This should not cause any more
access than we already have, and it makes ttyname() work in the
sandbox. */
if (host_tty_dev != NULL && *host_tty_dev != 0)
{
cleanup_free char *src_tty_dev = strconcat ("/oldroot", host_tty_dev);
cleanup_free char *dest_console = strconcat (dest, "/console");
if (create_file (dest_console, 0666, NULL) != 0)
die_with_error ("creating %s/console", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT, BIND_DEVICES,
src_tty_dev, dest_console);
}
break;
case SETUP_MOUNT_TMPFS:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_TMPFS_MOUNT, 0,
dest, NULL);
break;
case SETUP_MOUNT_MQUEUE:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_MQUEUE_MOUNT, 0,
dest, NULL);
break;
case SETUP_MAKE_DIR:
if (ensure_dir (dest, 0755) != 0)
die_with_error ("Can't mkdir %s", op->dest);
break;
case SETUP_MAKE_FILE:
{
cleanup_fd int dest_fd = -1;
dest_fd = creat (dest, 0666);
if (dest_fd == -1)
die_with_error ("Can't create file %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
}
break;
case SETUP_MAKE_BIND_FILE:
case SETUP_MAKE_RO_BIND_FILE:
{
cleanup_fd int dest_fd = -1;
char tempfile[] = "/bindfileXXXXXX";
dest_fd = mkstemp (tempfile);
if (dest_fd == -1)
die_with_error ("Can't create tmpfile for %s", op->dest);
if (copy_file_data (op->fd, dest_fd) != 0)
die_with_error ("Can't write data to file %s", op->dest);
close (op->fd);
op->fd = -1;
assert (dest != NULL);
if (ensure_file (dest, 0666) != 0)
die_with_error ("Can't create file at %s", op->dest);
privileged_op (privileged_op_socket,
PRIV_SEP_OP_BIND_MOUNT,
(op->type == SETUP_MAKE_RO_BIND_FILE ? BIND_READONLY : 0),
tempfile, dest);
/* Remove the file so we're sure the app can't get to it in any other way.
Its outside the container chroot, so it shouldn't be possible, but lets
make it really sure. */
unlink (tempfile);
}
break;
case SETUP_MAKE_SYMLINK:
assert (op->source != NULL); /* guaranteed by the constructor */
if (symlink (op->source, dest) != 0)
die_with_error ("Can't make symlink at %s", op->dest);
break;
case SETUP_SET_HOSTNAME:
assert (op->dest != NULL); /* guaranteed by the constructor */
privileged_op (privileged_op_socket,
PRIV_SEP_OP_SET_HOSTNAME, 0,
op->dest, NULL);
break;
default:
die ("Unexpected type %d", op->type);
}
}
privileged_op (privileged_op_socket,
PRIV_SEP_OP_DONE, 0, NULL, NULL);
}
/* Do not leak file descriptors already used by setup_newroot () */
static void
close_ops_fd (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
if (op->fd != -1)
{
(void) close (op->fd);
op->fd = -1;
}
}
}
/* We need to resolve relative symlinks in the sandbox before we
chroot so that absolute symlinks are handled correctly. We also
need to do this after we've switched to the real uid so that
e.g. paths on fuse mounts work */
static void
resolve_symlinks_in_ops (void)
{
SetupOp *op;
for (op = ops; op != NULL; op = op->next)
{
const char *old_source;
switch (op->type)
{
case SETUP_RO_BIND_MOUNT:
case SETUP_DEV_BIND_MOUNT:
case SETUP_BIND_MOUNT:
old_source = op->source;
op->source = realpath (old_source, NULL);
if (op->source == NULL)
{
if (op->flags & ALLOW_NOTEXIST && errno == ENOENT)
op->source = old_source;
else
die_with_error("Can't find source path %s", old_source);
}
break;
default:
break;
}
}
}
static const char *
resolve_string_offset (void *buffer,
size_t buffer_size,
uint32_t offset)
{
if (offset == 0)
return NULL;
if (offset > buffer_size)
die ("Invalid string offset %d (buffer size %zd)", offset, buffer_size);
return (const char *) buffer + offset;
}
static uint32_t
read_priv_sec_op (int read_socket,
void *buffer,
size_t buffer_size,
uint32_t *flags,
const char **arg1,
const char **arg2)
{
const PrivSepOp *op = (const PrivSepOp *) buffer;
ssize_t rec_len;
do
rec_len = read (read_socket, buffer, buffer_size - 1);
while (rec_len == -1 && errno == EINTR);
if (rec_len < 0)
die_with_error ("Can't read from unprivileged helper");
if (rec_len == 0)
exit (1); /* Privileged helper died and printed error, so exit silently */
if (rec_len < sizeof (PrivSepOp))
die ("Invalid size %zd from unprivileged helper", rec_len);
/* Guarantee zero termination of any strings */
((char *) buffer)[rec_len] = 0;
*flags = op->flags;
*arg1 = resolve_string_offset (buffer, rec_len, op->arg1_offset);
*arg2 = resolve_string_offset (buffer, rec_len, op->arg2_offset);
return op->op;
}
static void __attribute__ ((noreturn))
print_version_and_exit (void)
{
printf ("%s\n", PACKAGE_STRING);
exit (0);
}
static void
parse_args_recurse (int *argcp,
const char ***argvp,
bool in_file,
int *total_parsed_argc_p)
{
SetupOp *op;
int argc = *argcp;
const char **argv = *argvp;
/* I can't imagine a case where someone wants more than this.
* If you do...you should be able to pass multiple files
* via a single tmpfs and linking them there, etc.
*
* We're adding this hardening due to precedent from
* http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html
*
* I picked 9000 because the Internet told me to and it was hard to
* resist.
*/
static const uint32_t MAX_ARGS = 9000;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
while (argc > 0)
{
const char *arg = argv[0];
if (strcmp (arg, "--help") == 0)
{
usage (EXIT_SUCCESS, stdout);
}
else if (strcmp (arg, "--version") == 0)
{
print_version_and_exit ();
}
else if (strcmp (arg, "--args") == 0)
{
int the_fd;
char *endptr;
const char *p, *data_end;
size_t data_len;
cleanup_free const char **data_argv = NULL;
const char **data_argv_copy;
int data_argc;
int i;
if (in_file)
die ("--args not supported in arguments file");
if (argc < 2)
die ("--args takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
/* opt_args_data is essentially a recursive argv array, which we must
* keep allocated until exit time, since its argv entries get used
* by the other cases in parse_args_recurse() when we recurse. */
opt_args_data = load_file_data (the_fd, &data_len);
if (opt_args_data == NULL)
die_with_error ("Can't read --args data");
(void) close (the_fd);
data_end = opt_args_data + data_len;
data_argc = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
data_argc++;
(*total_parsed_argc_p)++;
if (*total_parsed_argc_p > MAX_ARGS)
die ("Exceeded maximum number of arguments %u", MAX_ARGS);
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv = xcalloc (sizeof (char *) * (data_argc + 1));
i = 0;
p = opt_args_data;
while (p != NULL && p < data_end)
{
/* Note: load_file_data always adds a nul terminator, so this is safe
* even for the last string. */
data_argv[i++] = p;
p = memchr (p, 0, data_end - p);
if (p != NULL)
p++;
}
data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */
parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--unshare-all") == 0)
{
/* Keep this in order with the older (legacy) --unshare arguments,
* we use the --try variants of user and cgroup, since we want
* to support systems/kernels without support for those.
*/
opt_unshare_user_try = opt_unshare_ipc = opt_unshare_pid =
opt_unshare_uts = opt_unshare_cgroup_try =
opt_unshare_net = TRUE;
}
/* Begin here the older individual --unshare variants */
else if (strcmp (arg, "--unshare-user") == 0)
{
opt_unshare_user = TRUE;
}
else if (strcmp (arg, "--unshare-user-try") == 0)
{
opt_unshare_user_try = TRUE;
}
else if (strcmp (arg, "--unshare-ipc") == 0)
{
opt_unshare_ipc = TRUE;
}
else if (strcmp (arg, "--unshare-pid") == 0)
{
opt_unshare_pid = TRUE;
}
else if (strcmp (arg, "--unshare-net") == 0)
{
opt_unshare_net = TRUE;
}
else if (strcmp (arg, "--unshare-uts") == 0)
{
opt_unshare_uts = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup") == 0)
{
opt_unshare_cgroup = TRUE;
}
else if (strcmp (arg, "--unshare-cgroup-try") == 0)
{
opt_unshare_cgroup_try = TRUE;
}
/* Begin here the newer --share variants */
else if (strcmp (arg, "--share-net") == 0)
{
opt_unshare_net = FALSE;
}
/* End --share variants, other arguments begin */
else if (strcmp (arg, "--chdir") == 0)
{
if (argc < 2)
die ("--chdir takes one argument");
opt_chdir_path = argv[1];
argv++;
argc--;
}
else if (strcmp (arg, "--remount-ro") == 0)
{
if (argc < 2)
die ("--remount-ro takes one argument");
SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE);
op->dest = argv[1];
argv++;
argc--;
}
else if (strcmp(arg, "--bind") == 0 ||
strcmp(arg, "--bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp(arg, "--ro-bind") == 0 ||
strcmp(arg, "--ro-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_RO_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--ro-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--dev-bind") == 0 ||
strcmp (arg, "--dev-bind-try") == 0)
{
if (argc < 3)
die ("%s takes two arguments", arg);
op = setup_op_new (SETUP_DEV_BIND_MOUNT);
op->source = argv[1];
op->dest = argv[2];
if (strcmp(arg, "--dev-bind-try") == 0)
op->flags = ALLOW_NOTEXIST;
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--proc") == 0)
{
if (argc < 2)
die ("--proc takes an argument");
op = setup_op_new (SETUP_MOUNT_PROC);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--exec-label") == 0)
{
if (argc < 2)
die ("--exec-label takes an argument");
opt_exec_label = argv[1];
die_unless_label_valid (opt_exec_label);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file-label") == 0)
{
if (argc < 2)
die ("--file-label takes an argument");
opt_file_label = argv[1];
die_unless_label_valid (opt_file_label);
if (label_create_file (opt_file_label))
die_with_error ("--file-label setup failed");
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dev") == 0)
{
if (argc < 2)
die ("--dev takes an argument");
op = setup_op_new (SETUP_MOUNT_DEV);
op->dest = argv[1];
opt_needs_devpts = TRUE;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--tmpfs") == 0)
{
if (argc < 2)
die ("--tmpfs takes an argument");
op = setup_op_new (SETUP_MOUNT_TMPFS);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--mqueue") == 0)
{
if (argc < 2)
die ("--mqueue takes an argument");
op = setup_op_new (SETUP_MOUNT_MQUEUE);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--dir") == 0)
{
if (argc < 2)
die ("--dir takes an argument");
op = setup_op_new (SETUP_MAKE_DIR);
op->dest = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--file") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--file takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--ro-bind-data") == 0)
{
int file_fd;
char *endptr;
if (argc < 3)
die ("--ro-bind-data takes two arguments");
file_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0)
die ("Invalid fd: %s", argv[1]);
op = setup_op_new (SETUP_MAKE_RO_BIND_FILE);
op->fd = file_fd;
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--symlink") == 0)
{
if (argc < 3)
die ("--symlink takes two arguments");
op = setup_op_new (SETUP_MAKE_SYMLINK);
op->source = argv[1];
op->dest = argv[2];
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--lock-file") == 0)
{
if (argc < 2)
die ("--lock-file takes an argument");
(void) lock_file_new (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--sync-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--sync-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_sync_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--userns-block-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--userns-block-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_userns_block_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--info-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--info-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_info_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--json-status-fd") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--json-status-fd takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_json_status_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--seccomp") == 0)
{
int the_fd;
char *endptr;
if (argc < 2)
die ("--seccomp takes an argument");
the_fd = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0)
die ("Invalid fd: %s", argv[1]);
opt_seccomp_fd = the_fd;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--setenv") == 0)
{
if (argc < 3)
die ("--setenv takes two arguments");
xsetenv (argv[1], argv[2], 1);
argv += 2;
argc -= 2;
}
else if (strcmp (arg, "--unsetenv") == 0)
{
if (argc < 2)
die ("--unsetenv takes an argument");
xunsetenv (argv[1]);
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--uid") == 0)
{
int the_uid;
char *endptr;
if (argc < 2)
die ("--uid takes an argument");
the_uid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0)
die ("Invalid uid: %s", argv[1]);
opt_sandbox_uid = the_uid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--gid") == 0)
{
int the_gid;
char *endptr;
if (argc < 2)
die ("--gid takes an argument");
the_gid = strtol (argv[1], &endptr, 10);
if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0)
die ("Invalid gid: %s", argv[1]);
opt_sandbox_gid = the_gid;
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--hostname") == 0)
{
if (argc < 2)
die ("--hostname takes an argument");
op = setup_op_new (SETUP_SET_HOSTNAME);
op->dest = argv[1];
op->flags = NO_CREATE_DEST;
opt_sandbox_hostname = argv[1];
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--new-session") == 0)
{
opt_new_session = TRUE;
}
else if (strcmp (arg, "--die-with-parent") == 0)
{
opt_die_with_parent = TRUE;
}
else if (strcmp (arg, "--as-pid-1") == 0)
{
opt_as_pid_1 = TRUE;
}
else if (strcmp (arg, "--cap-add") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-add takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0xFFFFFFFF;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] |= CAP_TO_MASK_0 (cap);
else
requested_caps[1] |= CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--cap-drop") == 0)
{
cap_value_t cap;
if (argc < 2)
die ("--cap-drop takes an argument");
opt_cap_add_or_drop_used = TRUE;
if (strcasecmp (argv[1], "ALL") == 0)
{
requested_caps[0] = requested_caps[1] = 0;
}
else
{
if (cap_from_name (argv[1], &cap) < 0)
die ("unknown cap: %s", argv[1]);
if (cap < 32)
requested_caps[0] &= ~CAP_TO_MASK_0 (cap);
else
requested_caps[1] &= ~CAP_TO_MASK_1 (cap - 32);
}
argv += 1;
argc -= 1;
}
else if (strcmp (arg, "--") == 0)
{
argv += 1;
argc -= 1;
break;
}
else if (*arg == '-')
{
die ("Unknown option %s", arg);
}
else
{
break;
}
argv++;
argc--;
}
*argcp = argc;
*argvp = argv;
}
static void
parse_args (int *argcp,
const char ***argvp)
{
int total_parsed_argc = *argcp;
parse_args_recurse (argcp, argvp, FALSE, &total_parsed_argc);
}
static void
read_overflowids (void)
{
cleanup_free char *uid_data = NULL;
cleanup_free char *gid_data = NULL;
uid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowuid");
if (uid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowuid");
overflow_uid = strtol (uid_data, NULL, 10);
if (overflow_uid == 0)
die ("Can't parse /proc/sys/kernel/overflowuid");
gid_data = load_file_at (AT_FDCWD, "/proc/sys/kernel/overflowgid");
if (gid_data == NULL)
die_with_error ("Can't read /proc/sys/kernel/overflowgid");
overflow_gid = strtol (gid_data, NULL, 10);
if (overflow_gid == 0)
die ("Can't parse /proc/sys/kernel/overflowgid");
}
int
main (int argc,
char **argv)
{
mode_t old_umask;
const char *base_path = NULL;
int clone_flags;
char *old_cwd = NULL;
pid_t pid;
int event_fd = -1;
int child_wait_fd = -1;
int setup_finished_pipe[] = {-1, -1};
const char *new_cwd;
uid_t ns_uid;
gid_t ns_gid;
struct stat sbuf;
uint64_t val;
int res UNUSED;
cleanup_free char *seccomp_data = NULL;
size_t seccomp_len;
struct sock_fprog seccomp_prog;
cleanup_free char *args_data = NULL;
/* Handle --version early on before we try to acquire/drop
* any capabilities so it works in a build environment;
* right now flatpak's build runs bubblewrap --version.
* https://github.com/projectatomic/bubblewrap/issues/185
*/
if (argc == 2 && (strcmp (argv[1], "--version") == 0))
print_version_and_exit ();
real_uid = getuid ();
real_gid = getgid ();
/* Get the (optional) privileges we need */
acquire_privs ();
/* Never gain any more privs during exec */
if (prctl (PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0)
die_with_error ("prctl(PR_SET_NO_NEW_CAPS) failed");
/* The initial code is run with high permissions
(i.e. CAP_SYS_ADMIN), so take lots of care. */
read_overflowids ();
argv0 = argv[0];
if (isatty (1))
host_tty_dev = ttyname (1);
argv++;
argc--;
if (argc == 0)
usage (EXIT_FAILURE, stderr);
parse_args (&argc, (const char ***) &argv);
/* suck the args into a cleanup_free variable to control their lifecycle */
args_data = opt_args_data;
opt_args_data = NULL;
if ((requested_caps[0] || requested_caps[1]) && is_privileged)
die ("--cap-add in setuid mode can be used only by root");
if (opt_userns_block_fd != -1 && !opt_unshare_user)
die ("--userns-block-fd requires --unshare-user");
if (opt_userns_block_fd != -1 && opt_info_fd == -1)
die ("--userns-block-fd requires --info-fd");
/* We have to do this if we weren't installed setuid (and we're not
* root), so let's just DWIM */
if (!is_privileged && getuid () != 0)
opt_unshare_user = TRUE;
#ifdef ENABLE_REQUIRE_USERNS
/* In this build option, we require userns. */
if (is_privileged && getuid () != 0)
opt_unshare_user = TRUE;
#endif
if (opt_unshare_user_try &&
stat ("/proc/self/ns/user", &sbuf) == 0)
{
bool disabled = FALSE;
/* RHEL7 has a kernel module parameter that lets you enable user namespaces */
if (stat ("/sys/module/user_namespace/parameters/enable", &sbuf) == 0)
{
cleanup_free char *enable = NULL;
enable = load_file_at (AT_FDCWD, "/sys/module/user_namespace/parameters/enable");
if (enable != NULL && enable[0] == 'N')
disabled = TRUE;
}
/* Check for max_user_namespaces */
if (stat ("/proc/sys/user/max_user_namespaces", &sbuf) == 0)
{
cleanup_free char *max_user_ns = NULL;
max_user_ns = load_file_at (AT_FDCWD, "/proc/sys/user/max_user_namespaces");
if (max_user_ns != NULL && strcmp(max_user_ns, "0\n") == 0)
disabled = TRUE;
}
/* Debian lets you disable *unprivileged* user namespaces. However this is not
a problem if we're privileged, and if we're not opt_unshare_user is TRUE
already, and there is not much we can do, its just a non-working setup. */
if (!disabled)
opt_unshare_user = TRUE;
}
if (argc == 0)
usage (EXIT_FAILURE, stderr);
__debug__ (("Creating root mount point\n"));
if (opt_sandbox_uid == -1)
opt_sandbox_uid = real_uid;
if (opt_sandbox_gid == -1)
opt_sandbox_gid = real_gid;
if (!opt_unshare_user && opt_sandbox_uid != real_uid)
die ("Specifying --uid requires --unshare-user");
if (!opt_unshare_user && opt_sandbox_gid != real_gid)
die ("Specifying --gid requires --unshare-user");
if (!opt_unshare_uts && opt_sandbox_hostname != NULL)
die ("Specifying --hostname requires --unshare-uts");
if (opt_as_pid_1 && !opt_unshare_pid)
die ("Specifying --as-pid-1 requires --unshare-pid");
if (opt_as_pid_1 && lock_files != NULL)
die ("Specifying --as-pid-1 and --lock-file is not permitted");
/* We need to read stuff from proc during the pivot_root dance, etc.
Lets keep a fd to it open */
proc_fd = open ("/proc", O_PATH);
if (proc_fd == -1)
die_with_error ("Can't open /proc");
/* We need *some* mountpoint where we can mount the root tmpfs.
* Because we use pivot_root, it won't appear to be mounted from
* the perspective of the sandboxed process, so we can use anywhere
* that is sure to exist, that is sure to not be a symlink controlled
* by someone malicious, and that we won't immediately need to
* access ourselves. */
base_path = "/tmp";
__debug__ (("creating new namespace\n"));
if (opt_unshare_pid && !opt_as_pid_1)
{
event_fd = eventfd (0, EFD_CLOEXEC | EFD_NONBLOCK);
if (event_fd == -1)
die_with_error ("eventfd()");
}
/* We block sigchild here so that we can use signalfd in the monitor. */
block_sigchild ();
clone_flags = SIGCHLD | CLONE_NEWNS;
if (opt_unshare_user)
clone_flags |= CLONE_NEWUSER;
if (opt_unshare_pid)
clone_flags |= CLONE_NEWPID;
if (opt_unshare_net)
clone_flags |= CLONE_NEWNET;
if (opt_unshare_ipc)
clone_flags |= CLONE_NEWIPC;
if (opt_unshare_uts)
clone_flags |= CLONE_NEWUTS;
if (opt_unshare_cgroup)
{
if (stat ("/proc/self/ns/cgroup", &sbuf))
{
if (errno == ENOENT)
die ("Cannot create new cgroup namespace because the kernel does not support it");
else
die_with_error ("stat on /proc/self/ns/cgroup failed");
}
clone_flags |= CLONE_NEWCGROUP;
}
if (opt_unshare_cgroup_try)
if (!stat ("/proc/self/ns/cgroup", &sbuf))
clone_flags |= CLONE_NEWCGROUP;
child_wait_fd = eventfd (0, EFD_CLOEXEC);
if (child_wait_fd == -1)
die_with_error ("eventfd()");
/* Track whether pre-exec setup finished if we're reporting process exit */
if (opt_json_status_fd != -1)
{
int ret;
ret = pipe2 (setup_finished_pipe, O_CLOEXEC);
if (ret == -1)
die_with_error ("pipe2()");
}
pid = raw_clone (clone_flags, NULL);
if (pid == -1)
{
if (opt_unshare_user)
{
if (errno == EINVAL)
die ("Creating new namespace failed, likely because the kernel does not support user namespaces. bwrap must be installed setuid on such systems.");
else if (errno == EPERM && !is_privileged)
die ("No permissions to creating new namespace, likely because the kernel does not allow non-privileged user namespaces. On e.g. debian this can be enabled with 'sysctl kernel.unprivileged_userns_clone=1'.");
}
die_with_error ("Creating new namespace failed");
}
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (pid != 0)
{
/* Parent, outside sandbox, privileged (initially) */
if (is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* We're running as euid 0, but the uid we want to map is
* not 0. This means we're not allowed to write this from
* the child user namespace, so we do it from the parent.
*
* Also, we map uid/gid 0 in the namespace (to overflowuid)
* if opt_needs_devpts is true, because otherwise the mount
* of devpts fails due to root not being mapped.
*/
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
pid, TRUE, opt_needs_devpts);
}
/* Initial launched process, wait for exec:ed command to exit */
/* We don't need any privileges in the launcher, drop them immediately. */
drop_privs (FALSE);
/* Optionally bind our lifecycle to that of the parent */
handle_die_with_parent ();
if (opt_info_fd != -1)
{
cleanup_free char *output = xasprintf ("{\n \"child-pid\": %i\n}\n", pid);
dump_info (opt_info_fd, output, TRUE);
close (opt_info_fd);
}
if (opt_json_status_fd != -1)
{
cleanup_free char *output = xasprintf ("{ \"child-pid\": %i }\n", pid);
dump_info (opt_json_status_fd, output, TRUE);
}
if (opt_userns_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_userns_block_fd, b, 1));
close (opt_userns_block_fd);
}
/* Let child run now that the uid maps are set up */
val = 1;
res = write (child_wait_fd, &val, 8);
/* Ignore res, if e.g. the child died and closed child_wait_fd we don't want to error out here */
close (child_wait_fd);
return monitor_child (event_fd, pid, setup_finished_pipe[0]);
}
/* Child, in sandbox, privileged in the parent or in the user namespace (if --unshare-user).
*
* Note that for user namespaces we run as euid 0 during clone(), so
* the child user namespace is owned by euid 0., This means that the
* regular user namespace parent (with uid != 0) doesn't have any
* capabilities in it, which is nice as we can't exploit those. In
* particular the parent user namespace doesn't have CAP_PTRACE
* which would otherwise allow the parent to hijack of the child
* after this point.
*
* Unfortunately this also means you can't ptrace the final
* sandboxed process from outside the sandbox either.
*/
if (opt_info_fd != -1)
close (opt_info_fd);
if (opt_json_status_fd != -1)
close (opt_json_status_fd);
/* Wait for the parent to init uid/gid maps and drop caps */
res = read (child_wait_fd, &val, 8);
close (child_wait_fd);
/* At this point we can completely drop root uid, but retain the
* required permitted caps. This allow us to do full setup as
* the user uid, which makes e.g. fuse access work.
*/
switch_to_user_with_privs ();
if (opt_unshare_net)
loopback_setup (); /* Will exit if unsuccessful */
ns_uid = opt_sandbox_uid;
ns_gid = opt_sandbox_gid;
if (!is_privileged && opt_unshare_user && opt_userns_block_fd == -1)
{
/* In the unprivileged case we have to write the uid/gid maps in
* the child, because we have no caps in the parent */
if (opt_needs_devpts)
{
/* This is a bit hacky, but we need to first map the real uid/gid to
0, otherwise we can't mount the devpts filesystem because root is
not mapped. Later we will create another child user namespace and
map back to the real uid */
ns_uid = 0;
ns_gid = 0;
}
write_uid_gid_map (ns_uid, real_uid,
ns_gid, real_gid,
-1, TRUE, FALSE);
}
old_umask = umask (0);
/* Need to do this before the chroot, but after we're the real uid */
resolve_symlinks_in_ops ();
/* Mark everything as slave, so that we still
* receive mounts from the real root, but don't
* propagate mounts to the real root. */
if (mount (NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
die_with_error ("Failed to make / slave");
/* Create a tmpfs which we will use as / in the namespace */
if (mount ("tmpfs", base_path, "tmpfs", MS_NODEV | MS_NOSUID, NULL) != 0)
die_with_error ("Failed to mount tmpfs");
old_cwd = get_current_dir_name ();
/* Chdir to the new root tmpfs mount. This will be the CWD during
the entire setup. Access old or new root via "oldroot" and "newroot". */
if (chdir (base_path) != 0)
die_with_error ("chdir base_path");
/* We create a subdir "$base_path/newroot" for the new root, that
* way we can pivot_root to base_path, and put the old root at
* "$base_path/oldroot". This avoids problems accessing the oldroot
* dir if the user requested to bind mount something over / (or
* over /tmp, now that we use that for base_path). */
if (mkdir ("newroot", 0755))
die_with_error ("Creating newroot failed");
if (mount ("newroot", "newroot", NULL, MS_MGC_VAL | MS_BIND | MS_REC, NULL) < 0)
die_with_error ("setting up newroot bind");
if (mkdir ("oldroot", 0755))
die_with_error ("Creating oldroot failed");
if (pivot_root (base_path, "oldroot"))
die_with_error ("pivot_root");
if (chdir ("/") != 0)
die_with_error ("chdir / (base path)");
if (is_privileged)
{
pid_t child;
int privsep_sockets[2];
if (socketpair (AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, privsep_sockets) != 0)
die_with_error ("Can't create privsep socket");
child = fork ();
if (child == -1)
die_with_error ("Can't fork unprivileged helper");
if (child == 0)
{
/* Unprivileged setup process */
drop_privs (FALSE);
close (privsep_sockets[0]);
setup_newroot (opt_unshare_pid, privsep_sockets[1]);
exit (0);
}
else
{
int status;
uint32_t buffer[2048]; /* 8k, but is int32 to guarantee nice alignment */
uint32_t op, flags;
const char *arg1, *arg2;
cleanup_fd int unpriv_socket = -1;
unpriv_socket = privsep_sockets[0];
close (privsep_sockets[1]);
do
{
op = read_priv_sec_op (unpriv_socket, buffer, sizeof (buffer),
&flags, &arg1, &arg2);
privileged_op (-1, op, flags, arg1, arg2);
if (write (unpriv_socket, buffer, 1) != 1)
die ("Can't write to op_socket");
}
while (op != PRIV_SEP_OP_DONE);
waitpid (child, &status, 0);
/* Continue post setup */
}
}
else
{
setup_newroot (opt_unshare_pid, -1);
}
close_ops_fd ();
/* The old root better be rprivate or we will send unmount events to the parent namespace */
if (mount ("oldroot", "oldroot", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
die_with_error ("Failed to make old root rprivate");
if (umount2 ("oldroot", MNT_DETACH))
die_with_error ("unmount old root");
/* This is our second pivot. It's like we're a Silicon Valley startup flush
* with cash but short on ideas!
*
* We're aiming to make /newroot the real root, and get rid of /oldroot. To do
* that we need a temporary place to store it before we can unmount it.
*/
{ cleanup_fd int oldrootfd = open ("/", O_DIRECTORY | O_RDONLY);
if (oldrootfd < 0)
die_with_error ("can't open /");
if (chdir ("/newroot") != 0)
die_with_error ("chdir /newroot");
/* While the documentation claims that put_old must be underneath
* new_root, it is perfectly fine to use the same directory as the
* kernel checks only if old_root is accessible from new_root.
*
* Both runc and LXC are using this "alternative" method for
* setting up the root of the container:
*
* https://github.com/opencontainers/runc/blob/master/libcontainer/rootfs_linux.go#L671
* https://github.com/lxc/lxc/blob/master/src/lxc/conf.c#L1121
*/
if (pivot_root (".", ".") != 0)
die_with_error ("pivot_root(/newroot)");
if (fchdir (oldrootfd) < 0)
die_with_error ("fchdir to oldroot");
if (umount2 (".", MNT_DETACH) < 0)
die_with_error ("umount old root");
if (chdir ("/") != 0)
die_with_error ("chdir /");
}
if (opt_unshare_user &&
(ns_uid != opt_sandbox_uid || ns_gid != opt_sandbox_gid) &&
opt_userns_block_fd == -1)
{
/* Now that devpts is mounted and we've no need for mount
permissions we can create a new userspace and map our uid
1:1 */
if (unshare (CLONE_NEWUSER))
die_with_error ("unshare user ns");
write_uid_gid_map (opt_sandbox_uid, ns_uid,
opt_sandbox_gid, ns_gid,
-1, FALSE, FALSE);
}
/* All privileged ops are done now, so drop caps we don't need */
drop_privs (!is_privileged);
if (opt_block_fd != -1)
{
char b[1];
(void) TEMP_FAILURE_RETRY (read (opt_block_fd, b, 1));
close (opt_block_fd);
}
if (opt_seccomp_fd != -1)
{
seccomp_data = load_file_data (opt_seccomp_fd, &seccomp_len);
if (seccomp_data == NULL)
die_with_error ("Can't read seccomp data");
if (seccomp_len % 8 != 0)
die ("Invalid seccomp data, must be multiple of 8");
seccomp_prog.len = seccomp_len / 8;
seccomp_prog.filter = (struct sock_filter *) seccomp_data;
close (opt_seccomp_fd);
}
umask (old_umask);
new_cwd = "/";
if (opt_chdir_path)
{
if (chdir (opt_chdir_path))
die_with_error ("Can't chdir to %s", opt_chdir_path);
new_cwd = opt_chdir_path;
}
else if (chdir (old_cwd) == 0)
{
/* If the old cwd is mapped in the sandbox, go there */
new_cwd = old_cwd;
}
else
{
/* If the old cwd is not mapped, go to home */
const char *home = getenv ("HOME");
if (home != NULL &&
chdir (home) == 0)
new_cwd = home;
}
xsetenv ("PWD", new_cwd, 1);
free (old_cwd);
if (opt_new_session &&
setsid () == (pid_t) -1)
die_with_error ("setsid");
if (label_exec (opt_exec_label) == -1)
die_with_error ("label_exec %s", argv[0]);
__debug__ (("forking for child\n"));
if (!opt_as_pid_1 && (opt_unshare_pid || lock_files != NULL || opt_sync_fd != -1))
{
/* We have to have a pid 1 in the pid namespace, because
* otherwise we'll get a bunch of zombies as nothing reaps
* them. Alternatively if we're using sync_fd or lock_files we
* need some process to own these.
*/
pid = fork ();
if (pid == -1)
die_with_error ("Can't fork for pid 1");
if (pid != 0)
{
drop_all_caps (FALSE);
/* Close fds in pid 1, except stdio and optionally event_fd
(for syncing pid 2 lifetime with monitor_child) and
opt_sync_fd (for syncing sandbox lifetime with outside
process).
Any other fds will been passed on to the child though. */
{
int dont_close[3];
int j = 0;
if (event_fd != -1)
dont_close[j++] = event_fd;
if (opt_sync_fd != -1)
dont_close[j++] = opt_sync_fd;
dont_close[j++] = -1;
fdwalk (proc_fd, close_extra_fds, dont_close);
}
return do_init (event_fd, pid, seccomp_data != NULL ? &seccomp_prog : NULL);
}
}
__debug__ (("launch executable %s\n", argv[0]));
if (proc_fd != -1)
close (proc_fd);
/* If we are using --as-pid-1 leak the sync fd into the sandbox.
--sync-fd will still work unless the container process doesn't close this file. */
if (!opt_as_pid_1)
{
if (opt_sync_fd != -1)
close (opt_sync_fd);
}
/* We want sigchild in the child */
unblock_sigchild ();
/* Optionally bind our lifecycle */
handle_die_with_parent ();
if (!is_privileged)
set_ambient_capabilities ();
/* Should be the last thing before execve() so that filters don't
* need to handle anything above */
if (seccomp_data != NULL &&
prctl (PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &seccomp_prog) != 0)
die_with_error ("prctl(PR_SET_SECCOMP)");
if (setup_finished_pipe[1] != -1)
{
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
if (execvp (argv[0], argv) == -1)
{
if (setup_finished_pipe[1] != -1)
{
int saved_errno = errno;
char data = 0;
res = write_to_fd (setup_finished_pipe[1], &data, 1);
errno = saved_errno;
/* Ignore res, if e.g. the parent died and closed setup_finished_pipe[0]
we don't want to error out here */
}
die_with_error ("execvp %s", argv[0]);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_874_0 |
crossvul-cpp_data_good_2015_0 | /*
* 32bit Socket syscall emulation. Based on arch/sparc64/kernel/sys_sparc32.c.
*
* Copyright (C) 2000 VA Linux Co
* Copyright (C) 2000 Don Dugger <n0ano@valinux.com>
* Copyright (C) 1999 Arun Sharma <arun.sharma@intel.com>
* Copyright (C) 1997,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
* Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu)
* Copyright (C) 2000 Hewlett-Packard Co.
* Copyright (C) 2000 David Mosberger-Tang <davidm@hpl.hp.com>
* Copyright (C) 2000,2001 Andi Kleen, SuSE Labs
*/
#include <linux/kernel.h>
#include <linux/gfp.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/file.h>
#include <linux/icmpv6.h>
#include <linux/socket.h>
#include <linux/syscalls.h>
#include <linux/filter.h>
#include <linux/compat.h>
#include <linux/security.h>
#include <linux/export.h>
#include <net/scm.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <asm/uaccess.h>
#include <net/compat.h>
static inline int iov_from_user_compat_to_kern(struct iovec *kiov,
struct compat_iovec __user *uiov32,
int niov)
{
int tot_len = 0;
while (niov > 0) {
compat_uptr_t buf;
compat_size_t len;
if (get_user(len, &uiov32->iov_len) ||
get_user(buf, &uiov32->iov_base))
return -EFAULT;
if (len > INT_MAX - tot_len)
len = INT_MAX - tot_len;
tot_len += len;
kiov->iov_base = compat_ptr(buf);
kiov->iov_len = (__kernel_size_t) len;
uiov32++;
kiov++;
niov--;
}
return tot_len;
}
int get_compat_msghdr(struct msghdr *kmsg, struct compat_msghdr __user *umsg)
{
compat_uptr_t tmp1, tmp2, tmp3;
if (!access_ok(VERIFY_READ, umsg, sizeof(*umsg)) ||
__get_user(tmp1, &umsg->msg_name) ||
__get_user(kmsg->msg_namelen, &umsg->msg_namelen) ||
__get_user(tmp2, &umsg->msg_iov) ||
__get_user(kmsg->msg_iovlen, &umsg->msg_iovlen) ||
__get_user(tmp3, &umsg->msg_control) ||
__get_user(kmsg->msg_controllen, &umsg->msg_controllen) ||
__get_user(kmsg->msg_flags, &umsg->msg_flags))
return -EFAULT;
if (kmsg->msg_namelen > sizeof(struct sockaddr_storage))
kmsg->msg_namelen = sizeof(struct sockaddr_storage);
kmsg->msg_name = compat_ptr(tmp1);
kmsg->msg_iov = compat_ptr(tmp2);
kmsg->msg_control = compat_ptr(tmp3);
return 0;
}
/* I've named the args so it is easy to tell whose space the pointers are in. */
int verify_compat_iovec(struct msghdr *kern_msg, struct iovec *kern_iov,
struct sockaddr_storage *kern_address, int mode)
{
int tot_len;
if (kern_msg->msg_namelen) {
if (mode == VERIFY_READ) {
int err = move_addr_to_kernel(kern_msg->msg_name,
kern_msg->msg_namelen,
kern_address);
if (err < 0)
return err;
}
if (kern_msg->msg_name)
kern_msg->msg_name = kern_address;
} else
kern_msg->msg_name = NULL;
tot_len = iov_from_user_compat_to_kern(kern_iov,
(struct compat_iovec __user *)kern_msg->msg_iov,
kern_msg->msg_iovlen);
if (tot_len >= 0)
kern_msg->msg_iov = kern_iov;
return tot_len;
}
/* Bleech... */
#define CMSG_COMPAT_ALIGN(len) ALIGN((len), sizeof(s32))
#define CMSG_COMPAT_DATA(cmsg) \
((void __user *)((char __user *)(cmsg) + CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr))))
#define CMSG_COMPAT_SPACE(len) \
(CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr)) + CMSG_COMPAT_ALIGN(len))
#define CMSG_COMPAT_LEN(len) \
(CMSG_COMPAT_ALIGN(sizeof(struct compat_cmsghdr)) + (len))
#define CMSG_COMPAT_FIRSTHDR(msg) \
(((msg)->msg_controllen) >= sizeof(struct compat_cmsghdr) ? \
(struct compat_cmsghdr __user *)((msg)->msg_control) : \
(struct compat_cmsghdr __user *)NULL)
#define CMSG_COMPAT_OK(ucmlen, ucmsg, mhdr) \
((ucmlen) >= sizeof(struct compat_cmsghdr) && \
(ucmlen) <= (unsigned long) \
((mhdr)->msg_controllen - \
((char *)(ucmsg) - (char *)(mhdr)->msg_control)))
static inline struct compat_cmsghdr __user *cmsg_compat_nxthdr(struct msghdr *msg,
struct compat_cmsghdr __user *cmsg, int cmsg_len)
{
char __user *ptr = (char __user *)cmsg + CMSG_COMPAT_ALIGN(cmsg_len);
if ((unsigned long)(ptr + 1 - (char __user *)msg->msg_control) >
msg->msg_controllen)
return NULL;
return (struct compat_cmsghdr __user *)ptr;
}
/* There is a lot of hair here because the alignment rules (and
* thus placement) of cmsg headers and length are different for
* 32-bit apps. -DaveM
*/
int cmsghdr_from_user_compat_to_kern(struct msghdr *kmsg, struct sock *sk,
unsigned char *stackbuf, int stackbuf_size)
{
struct compat_cmsghdr __user *ucmsg;
struct cmsghdr *kcmsg, *kcmsg_base;
compat_size_t ucmlen;
__kernel_size_t kcmlen, tmp;
int err = -EFAULT;
kcmlen = 0;
kcmsg_base = kcmsg = (struct cmsghdr *)stackbuf;
ucmsg = CMSG_COMPAT_FIRSTHDR(kmsg);
while (ucmsg != NULL) {
if (get_user(ucmlen, &ucmsg->cmsg_len))
return -EFAULT;
/* Catch bogons. */
if (!CMSG_COMPAT_OK(ucmlen, ucmsg, kmsg))
return -EINVAL;
tmp = ((ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg))) +
CMSG_ALIGN(sizeof(struct cmsghdr)));
tmp = CMSG_ALIGN(tmp);
kcmlen += tmp;
ucmsg = cmsg_compat_nxthdr(kmsg, ucmsg, ucmlen);
}
if (kcmlen == 0)
return -EINVAL;
/* The kcmlen holds the 64-bit version of the control length.
* It may not be modified as we do not stick it into the kmsg
* until we have successfully copied over all of the data
* from the user.
*/
if (kcmlen > stackbuf_size)
kcmsg_base = kcmsg = sock_kmalloc(sk, kcmlen, GFP_KERNEL);
if (kcmsg == NULL)
return -ENOBUFS;
/* Now copy them over neatly. */
memset(kcmsg, 0, kcmlen);
ucmsg = CMSG_COMPAT_FIRSTHDR(kmsg);
while (ucmsg != NULL) {
if (__get_user(ucmlen, &ucmsg->cmsg_len))
goto Efault;
if (!CMSG_COMPAT_OK(ucmlen, ucmsg, kmsg))
goto Einval;
tmp = ((ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg))) +
CMSG_ALIGN(sizeof(struct cmsghdr)));
if ((char *)kcmsg_base + kcmlen - (char *)kcmsg < CMSG_ALIGN(tmp))
goto Einval;
kcmsg->cmsg_len = tmp;
tmp = CMSG_ALIGN(tmp);
if (__get_user(kcmsg->cmsg_level, &ucmsg->cmsg_level) ||
__get_user(kcmsg->cmsg_type, &ucmsg->cmsg_type) ||
copy_from_user(CMSG_DATA(kcmsg),
CMSG_COMPAT_DATA(ucmsg),
(ucmlen - CMSG_COMPAT_ALIGN(sizeof(*ucmsg)))))
goto Efault;
/* Advance. */
kcmsg = (struct cmsghdr *)((char *)kcmsg + tmp);
ucmsg = cmsg_compat_nxthdr(kmsg, ucmsg, ucmlen);
}
/* Ok, looks like we made it. Hook it up and return success. */
kmsg->msg_control = kcmsg_base;
kmsg->msg_controllen = kcmlen;
return 0;
Einval:
err = -EINVAL;
Efault:
if (kcmsg_base != (struct cmsghdr *)stackbuf)
sock_kfree_s(sk, kcmsg_base, kcmlen);
return err;
}
int put_cmsg_compat(struct msghdr *kmsg, int level, int type, int len, void *data)
{
struct compat_cmsghdr __user *cm = (struct compat_cmsghdr __user *) kmsg->msg_control;
struct compat_cmsghdr cmhdr;
struct compat_timeval ctv;
struct compat_timespec cts[3];
int cmlen;
if (cm == NULL || kmsg->msg_controllen < sizeof(*cm)) {
kmsg->msg_flags |= MSG_CTRUNC;
return 0; /* XXX: return error? check spec. */
}
if (!COMPAT_USE_64BIT_TIME) {
if (level == SOL_SOCKET && type == SCM_TIMESTAMP) {
struct timeval *tv = (struct timeval *)data;
ctv.tv_sec = tv->tv_sec;
ctv.tv_usec = tv->tv_usec;
data = &ctv;
len = sizeof(ctv);
}
if (level == SOL_SOCKET &&
(type == SCM_TIMESTAMPNS || type == SCM_TIMESTAMPING)) {
int count = type == SCM_TIMESTAMPNS ? 1 : 3;
int i;
struct timespec *ts = (struct timespec *)data;
for (i = 0; i < count; i++) {
cts[i].tv_sec = ts[i].tv_sec;
cts[i].tv_nsec = ts[i].tv_nsec;
}
data = &cts;
len = sizeof(cts[0]) * count;
}
}
cmlen = CMSG_COMPAT_LEN(len);
if (kmsg->msg_controllen < cmlen) {
kmsg->msg_flags |= MSG_CTRUNC;
cmlen = kmsg->msg_controllen;
}
cmhdr.cmsg_level = level;
cmhdr.cmsg_type = type;
cmhdr.cmsg_len = cmlen;
if (copy_to_user(cm, &cmhdr, sizeof cmhdr))
return -EFAULT;
if (copy_to_user(CMSG_COMPAT_DATA(cm), data, cmlen - sizeof(struct compat_cmsghdr)))
return -EFAULT;
cmlen = CMSG_COMPAT_SPACE(len);
if (kmsg->msg_controllen < cmlen)
cmlen = kmsg->msg_controllen;
kmsg->msg_control += cmlen;
kmsg->msg_controllen -= cmlen;
return 0;
}
void scm_detach_fds_compat(struct msghdr *kmsg, struct scm_cookie *scm)
{
struct compat_cmsghdr __user *cm = (struct compat_cmsghdr __user *) kmsg->msg_control;
int fdmax = (kmsg->msg_controllen - sizeof(struct compat_cmsghdr)) / sizeof(int);
int fdnum = scm->fp->count;
struct file **fp = scm->fp->fp;
int __user *cmfptr;
int err = 0, i;
if (fdnum < fdmax)
fdmax = fdnum;
for (i = 0, cmfptr = (int __user *) CMSG_COMPAT_DATA(cm); i < fdmax; i++, cmfptr++) {
int new_fd;
err = security_file_receive(fp[i]);
if (err)
break;
err = get_unused_fd_flags(MSG_CMSG_CLOEXEC & kmsg->msg_flags
? O_CLOEXEC : 0);
if (err < 0)
break;
new_fd = err;
err = put_user(new_fd, cmfptr);
if (err) {
put_unused_fd(new_fd);
break;
}
/* Bump the usage count and install the file. */
fd_install(new_fd, get_file(fp[i]));
}
if (i > 0) {
int cmlen = CMSG_COMPAT_LEN(i * sizeof(int));
err = put_user(SOL_SOCKET, &cm->cmsg_level);
if (!err)
err = put_user(SCM_RIGHTS, &cm->cmsg_type);
if (!err)
err = put_user(cmlen, &cm->cmsg_len);
if (!err) {
cmlen = CMSG_COMPAT_SPACE(i * sizeof(int));
kmsg->msg_control += cmlen;
kmsg->msg_controllen -= cmlen;
}
}
if (i < fdnum)
kmsg->msg_flags |= MSG_CTRUNC;
/*
* All of the files that fit in the message have had their
* usage counts incremented, so we just free the list.
*/
__scm_destroy(scm);
}
static int do_set_attach_filter(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct compat_sock_fprog __user *fprog32 = (struct compat_sock_fprog __user *)optval;
struct sock_fprog __user *kfprog = compat_alloc_user_space(sizeof(struct sock_fprog));
compat_uptr_t ptr;
u16 len;
if (!access_ok(VERIFY_READ, fprog32, sizeof(*fprog32)) ||
!access_ok(VERIFY_WRITE, kfprog, sizeof(struct sock_fprog)) ||
__get_user(len, &fprog32->len) ||
__get_user(ptr, &fprog32->filter) ||
__put_user(len, &kfprog->len) ||
__put_user(compat_ptr(ptr), &kfprog->filter))
return -EFAULT;
return sock_setsockopt(sock, level, optname, (char __user *)kfprog,
sizeof(struct sock_fprog));
}
static int do_set_sock_timeout(struct socket *sock, int level,
int optname, char __user *optval, unsigned int optlen)
{
struct compat_timeval __user *up = (struct compat_timeval __user *)optval;
struct timeval ktime;
mm_segment_t old_fs;
int err;
if (optlen < sizeof(*up))
return -EINVAL;
if (!access_ok(VERIFY_READ, up, sizeof(*up)) ||
__get_user(ktime.tv_sec, &up->tv_sec) ||
__get_user(ktime.tv_usec, &up->tv_usec))
return -EFAULT;
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sock_setsockopt(sock, level, optname, (char *)&ktime, sizeof(ktime));
set_fs(old_fs);
return err;
}
static int compat_sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (optname == SO_ATTACH_FILTER)
return do_set_attach_filter(sock, level, optname,
optval, optlen);
if (optname == SO_RCVTIMEO || optname == SO_SNDTIMEO)
return do_set_sock_timeout(sock, level, optname, optval, optlen);
return sock_setsockopt(sock, level, optname, optval, optlen);
}
asmlinkage long compat_sys_setsockopt(int fd, int level, int optname,
char __user *optval, unsigned int optlen)
{
int err;
struct socket *sock = sockfd_lookup(fd, &err);
if (sock) {
err = security_socket_setsockopt(sock, level, optname);
if (err) {
sockfd_put(sock);
return err;
}
if (level == SOL_SOCKET)
err = compat_sock_setsockopt(sock, level,
optname, optval, optlen);
else if (sock->ops->compat_setsockopt)
err = sock->ops->compat_setsockopt(sock, level,
optname, optval, optlen);
else
err = sock->ops->setsockopt(sock, level,
optname, optval, optlen);
sockfd_put(sock);
}
return err;
}
static int do_get_sock_timeout(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct compat_timeval __user *up;
struct timeval ktime;
mm_segment_t old_fs;
int len, err;
up = (struct compat_timeval __user *) optval;
if (get_user(len, optlen))
return -EFAULT;
if (len < sizeof(*up))
return -EINVAL;
len = sizeof(ktime);
old_fs = get_fs();
set_fs(KERNEL_DS);
err = sock_getsockopt(sock, level, optname, (char *) &ktime, &len);
set_fs(old_fs);
if (!err) {
if (put_user(sizeof(*up), optlen) ||
!access_ok(VERIFY_WRITE, up, sizeof(*up)) ||
__put_user(ktime.tv_sec, &up->tv_sec) ||
__put_user(ktime.tv_usec, &up->tv_usec))
err = -EFAULT;
}
return err;
}
static int compat_sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
if (optname == SO_RCVTIMEO || optname == SO_SNDTIMEO)
return do_get_sock_timeout(sock, level, optname, optval, optlen);
return sock_getsockopt(sock, level, optname, optval, optlen);
}
int compat_sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp)
{
struct compat_timeval __user *ctv;
int err;
struct timeval tv;
if (COMPAT_USE_64BIT_TIME)
return sock_get_timestamp(sk, userstamp);
ctv = (struct compat_timeval __user *) userstamp;
err = -ENOENT;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
tv = ktime_to_timeval(sk->sk_stamp);
if (tv.tv_sec == -1)
return err;
if (tv.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
tv = ktime_to_timeval(sk->sk_stamp);
}
err = 0;
if (put_user(tv.tv_sec, &ctv->tv_sec) ||
put_user(tv.tv_usec, &ctv->tv_usec))
err = -EFAULT;
return err;
}
EXPORT_SYMBOL(compat_sock_get_timestamp);
int compat_sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp)
{
struct compat_timespec __user *ctv;
int err;
struct timespec ts;
if (COMPAT_USE_64BIT_TIME)
return sock_get_timestampns (sk, userstamp);
ctv = (struct compat_timespec __user *) userstamp;
err = -ENOENT;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
ts = ktime_to_timespec(sk->sk_stamp);
if (ts.tv_sec == -1)
return err;
if (ts.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
ts = ktime_to_timespec(sk->sk_stamp);
}
err = 0;
if (put_user(ts.tv_sec, &ctv->tv_sec) ||
put_user(ts.tv_nsec, &ctv->tv_nsec))
err = -EFAULT;
return err;
}
EXPORT_SYMBOL(compat_sock_get_timestampns);
asmlinkage long compat_sys_getsockopt(int fd, int level, int optname,
char __user *optval, int __user *optlen)
{
int err;
struct socket *sock = sockfd_lookup(fd, &err);
if (sock) {
err = security_socket_getsockopt(sock, level, optname);
if (err) {
sockfd_put(sock);
return err;
}
if (level == SOL_SOCKET)
err = compat_sock_getsockopt(sock, level,
optname, optval, optlen);
else if (sock->ops->compat_getsockopt)
err = sock->ops->compat_getsockopt(sock, level,
optname, optval, optlen);
else
err = sock->ops->getsockopt(sock, level,
optname, optval, optlen);
sockfd_put(sock);
}
return err;
}
struct compat_group_req {
__u32 gr_interface;
struct __kernel_sockaddr_storage gr_group
__attribute__ ((aligned(4)));
} __packed;
struct compat_group_source_req {
__u32 gsr_interface;
struct __kernel_sockaddr_storage gsr_group
__attribute__ ((aligned(4)));
struct __kernel_sockaddr_storage gsr_source
__attribute__ ((aligned(4)));
} __packed;
struct compat_group_filter {
__u32 gf_interface;
struct __kernel_sockaddr_storage gf_group
__attribute__ ((aligned(4)));
__u32 gf_fmode;
__u32 gf_numsrc;
struct __kernel_sockaddr_storage gf_slist[1]
__attribute__ ((aligned(4)));
} __packed;
#define __COMPAT_GF0_SIZE (sizeof(struct compat_group_filter) - \
sizeof(struct __kernel_sockaddr_storage))
int compat_mc_setsockopt(struct sock *sock, int level, int optname,
char __user *optval, unsigned int optlen,
int (*setsockopt)(struct sock *, int, int, char __user *, unsigned int))
{
char __user *koptval = optval;
int koptlen = optlen;
switch (optname) {
case MCAST_JOIN_GROUP:
case MCAST_LEAVE_GROUP:
{
struct compat_group_req __user *gr32 = (void *)optval;
struct group_req __user *kgr =
compat_alloc_user_space(sizeof(struct group_req));
u32 interface;
if (!access_ok(VERIFY_READ, gr32, sizeof(*gr32)) ||
!access_ok(VERIFY_WRITE, kgr, sizeof(struct group_req)) ||
__get_user(interface, &gr32->gr_interface) ||
__put_user(interface, &kgr->gr_interface) ||
copy_in_user(&kgr->gr_group, &gr32->gr_group,
sizeof(kgr->gr_group)))
return -EFAULT;
koptval = (char __user *)kgr;
koptlen = sizeof(struct group_req);
break;
}
case MCAST_JOIN_SOURCE_GROUP:
case MCAST_LEAVE_SOURCE_GROUP:
case MCAST_BLOCK_SOURCE:
case MCAST_UNBLOCK_SOURCE:
{
struct compat_group_source_req __user *gsr32 = (void *)optval;
struct group_source_req __user *kgsr = compat_alloc_user_space(
sizeof(struct group_source_req));
u32 interface;
if (!access_ok(VERIFY_READ, gsr32, sizeof(*gsr32)) ||
!access_ok(VERIFY_WRITE, kgsr,
sizeof(struct group_source_req)) ||
__get_user(interface, &gsr32->gsr_interface) ||
__put_user(interface, &kgsr->gsr_interface) ||
copy_in_user(&kgsr->gsr_group, &gsr32->gsr_group,
sizeof(kgsr->gsr_group)) ||
copy_in_user(&kgsr->gsr_source, &gsr32->gsr_source,
sizeof(kgsr->gsr_source)))
return -EFAULT;
koptval = (char __user *)kgsr;
koptlen = sizeof(struct group_source_req);
break;
}
case MCAST_MSFILTER:
{
struct compat_group_filter __user *gf32 = (void *)optval;
struct group_filter __user *kgf;
u32 interface, fmode, numsrc;
if (!access_ok(VERIFY_READ, gf32, __COMPAT_GF0_SIZE) ||
__get_user(interface, &gf32->gf_interface) ||
__get_user(fmode, &gf32->gf_fmode) ||
__get_user(numsrc, &gf32->gf_numsrc))
return -EFAULT;
koptlen = optlen + sizeof(struct group_filter) -
sizeof(struct compat_group_filter);
if (koptlen < GROUP_FILTER_SIZE(numsrc))
return -EINVAL;
kgf = compat_alloc_user_space(koptlen);
if (!access_ok(VERIFY_WRITE, kgf, koptlen) ||
__put_user(interface, &kgf->gf_interface) ||
__put_user(fmode, &kgf->gf_fmode) ||
__put_user(numsrc, &kgf->gf_numsrc) ||
copy_in_user(&kgf->gf_group, &gf32->gf_group,
sizeof(kgf->gf_group)) ||
(numsrc && copy_in_user(kgf->gf_slist, gf32->gf_slist,
numsrc * sizeof(kgf->gf_slist[0]))))
return -EFAULT;
koptval = (char __user *)kgf;
break;
}
default:
break;
}
return setsockopt(sock, level, optname, koptval, koptlen);
}
EXPORT_SYMBOL(compat_mc_setsockopt);
int compat_mc_getsockopt(struct sock *sock, int level, int optname,
char __user *optval, int __user *optlen,
int (*getsockopt)(struct sock *, int, int, char __user *, int __user *))
{
struct compat_group_filter __user *gf32 = (void *)optval;
struct group_filter __user *kgf;
int __user *koptlen;
u32 interface, fmode, numsrc;
int klen, ulen, err;
if (optname != MCAST_MSFILTER)
return getsockopt(sock, level, optname, optval, optlen);
koptlen = compat_alloc_user_space(sizeof(*koptlen));
if (!access_ok(VERIFY_READ, optlen, sizeof(*optlen)) ||
__get_user(ulen, optlen))
return -EFAULT;
/* adjust len for pad */
klen = ulen + sizeof(*kgf) - sizeof(*gf32);
if (klen < GROUP_FILTER_SIZE(0))
return -EINVAL;
if (!access_ok(VERIFY_WRITE, koptlen, sizeof(*koptlen)) ||
__put_user(klen, koptlen))
return -EFAULT;
/* have to allow space for previous compat_alloc_user_space, too */
kgf = compat_alloc_user_space(klen+sizeof(*optlen));
if (!access_ok(VERIFY_READ, gf32, __COMPAT_GF0_SIZE) ||
__get_user(interface, &gf32->gf_interface) ||
__get_user(fmode, &gf32->gf_fmode) ||
__get_user(numsrc, &gf32->gf_numsrc) ||
__put_user(interface, &kgf->gf_interface) ||
__put_user(fmode, &kgf->gf_fmode) ||
__put_user(numsrc, &kgf->gf_numsrc) ||
copy_in_user(&kgf->gf_group, &gf32->gf_group, sizeof(kgf->gf_group)))
return -EFAULT;
err = getsockopt(sock, level, optname, (char __user *)kgf, koptlen);
if (err)
return err;
if (!access_ok(VERIFY_READ, koptlen, sizeof(*koptlen)) ||
__get_user(klen, koptlen))
return -EFAULT;
ulen = klen - (sizeof(*kgf)-sizeof(*gf32));
if (!access_ok(VERIFY_WRITE, optlen, sizeof(*optlen)) ||
__put_user(ulen, optlen))
return -EFAULT;
if (!access_ok(VERIFY_READ, kgf, klen) ||
!access_ok(VERIFY_WRITE, gf32, ulen) ||
__get_user(interface, &kgf->gf_interface) ||
__get_user(fmode, &kgf->gf_fmode) ||
__get_user(numsrc, &kgf->gf_numsrc) ||
__put_user(interface, &gf32->gf_interface) ||
__put_user(fmode, &gf32->gf_fmode) ||
__put_user(numsrc, &gf32->gf_numsrc))
return -EFAULT;
if (numsrc) {
int copylen;
klen -= GROUP_FILTER_SIZE(0);
copylen = numsrc * sizeof(gf32->gf_slist[0]);
if (copylen > klen)
copylen = klen;
if (copy_in_user(gf32->gf_slist, kgf->gf_slist, copylen))
return -EFAULT;
}
return err;
}
EXPORT_SYMBOL(compat_mc_getsockopt);
/* Argument list sizes for compat_sys_socketcall */
#define AL(x) ((x) * sizeof(u32))
static unsigned char nas[21] = {
AL(0), AL(3), AL(3), AL(3), AL(2), AL(3),
AL(3), AL(3), AL(4), AL(4), AL(4), AL(6),
AL(6), AL(2), AL(5), AL(5), AL(3), AL(3),
AL(4), AL(5), AL(4)
};
#undef AL
asmlinkage long compat_sys_sendmsg(int fd, struct compat_msghdr __user *msg, unsigned int flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_sendmsg(fd, (struct msghdr __user *)msg, flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_sendmmsg(int fd, struct compat_mmsghdr __user *mmsg,
unsigned int vlen, unsigned int flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_sendmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_recvmsg(int fd, struct compat_msghdr __user *msg, unsigned int flags)
{
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
return __sys_recvmsg(fd, (struct msghdr __user *)msg, flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_recv(int fd, void __user *buf, size_t len, unsigned int flags)
{
return sys_recv(fd, buf, len, flags | MSG_CMSG_COMPAT);
}
asmlinkage long compat_sys_recvfrom(int fd, void __user *buf, size_t len,
unsigned int flags, struct sockaddr __user *addr,
int __user *addrlen)
{
return sys_recvfrom(fd, buf, len, flags | MSG_CMSG_COMPAT, addr, addrlen);
}
asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg,
unsigned int vlen, unsigned int flags,
struct compat_timespec __user *timeout)
{
int datagrams;
struct timespec ktspec;
if (flags & MSG_CMSG_COMPAT)
return -EINVAL;
if (timeout == NULL)
return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, NULL);
if (compat_get_timespec(&ktspec, timeout))
return -EFAULT;
datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen,
flags | MSG_CMSG_COMPAT, &ktspec);
if (datagrams > 0 && compat_put_timespec(&ktspec, timeout))
datagrams = -EFAULT;
return datagrams;
}
asmlinkage long compat_sys_socketcall(int call, u32 __user *args)
{
int ret;
u32 a[6];
u32 a0, a1;
if (call < SYS_SOCKET || call > SYS_SENDMMSG)
return -EINVAL;
if (copy_from_user(a, args, nas[call]))
return -EFAULT;
a0 = a[0];
a1 = a[1];
switch (call) {
case SYS_SOCKET:
ret = sys_socket(a0, a1, a[2]);
break;
case SYS_BIND:
ret = sys_bind(a0, compat_ptr(a1), a[2]);
break;
case SYS_CONNECT:
ret = sys_connect(a0, compat_ptr(a1), a[2]);
break;
case SYS_LISTEN:
ret = sys_listen(a0, a1);
break;
case SYS_ACCEPT:
ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), 0);
break;
case SYS_GETSOCKNAME:
ret = sys_getsockname(a0, compat_ptr(a1), compat_ptr(a[2]));
break;
case SYS_GETPEERNAME:
ret = sys_getpeername(a0, compat_ptr(a1), compat_ptr(a[2]));
break;
case SYS_SOCKETPAIR:
ret = sys_socketpair(a0, a1, a[2], compat_ptr(a[3]));
break;
case SYS_SEND:
ret = sys_send(a0, compat_ptr(a1), a[2], a[3]);
break;
case SYS_SENDTO:
ret = sys_sendto(a0, compat_ptr(a1), a[2], a[3], compat_ptr(a[4]), a[5]);
break;
case SYS_RECV:
ret = compat_sys_recv(a0, compat_ptr(a1), a[2], a[3]);
break;
case SYS_RECVFROM:
ret = compat_sys_recvfrom(a0, compat_ptr(a1), a[2], a[3],
compat_ptr(a[4]), compat_ptr(a[5]));
break;
case SYS_SHUTDOWN:
ret = sys_shutdown(a0, a1);
break;
case SYS_SETSOCKOPT:
ret = compat_sys_setsockopt(a0, a1, a[2],
compat_ptr(a[3]), a[4]);
break;
case SYS_GETSOCKOPT:
ret = compat_sys_getsockopt(a0, a1, a[2],
compat_ptr(a[3]), compat_ptr(a[4]));
break;
case SYS_SENDMSG:
ret = compat_sys_sendmsg(a0, compat_ptr(a1), a[2]);
break;
case SYS_SENDMMSG:
ret = compat_sys_sendmmsg(a0, compat_ptr(a1), a[2], a[3]);
break;
case SYS_RECVMSG:
ret = compat_sys_recvmsg(a0, compat_ptr(a1), a[2]);
break;
case SYS_RECVMMSG:
ret = compat_sys_recvmmsg(a0, compat_ptr(a1), a[2], a[3],
compat_ptr(a[4]));
break;
case SYS_ACCEPT4:
ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), a[3]);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2015_0 |
crossvul-cpp_data_good_364_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD CCCC M M %
% D D C MM MM %
% D D C M M M %
% D D C M M %
% DDDD CCCC M M %
% %
% %
% Read DICOM Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/resource_.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/module.h"
/*
Dicom medical image declarations.
*/
typedef struct _DicomInfo
{
const unsigned short
group,
element;
const char
*vr,
*description;
} DicomInfo;
static const DicomInfo
dicom_info[] =
{
{ 0x0000, 0x0000, "UL", "Group Length" },
{ 0x0000, 0x0001, "UL", "Command Length to End" },
{ 0x0000, 0x0002, "UI", "Affected SOP Class UID" },
{ 0x0000, 0x0003, "UI", "Requested SOP Class UID" },
{ 0x0000, 0x0010, "LO", "Command Recognition Code" },
{ 0x0000, 0x0100, "US", "Command Field" },
{ 0x0000, 0x0110, "US", "Message ID" },
{ 0x0000, 0x0120, "US", "Message ID Being Responded To" },
{ 0x0000, 0x0200, "AE", "Initiator" },
{ 0x0000, 0x0300, "AE", "Receiver" },
{ 0x0000, 0x0400, "AE", "Find Location" },
{ 0x0000, 0x0600, "AE", "Move Destination" },
{ 0x0000, 0x0700, "US", "Priority" },
{ 0x0000, 0x0800, "US", "Data Set Type" },
{ 0x0000, 0x0850, "US", "Number of Matches" },
{ 0x0000, 0x0860, "US", "Response Sequence Number" },
{ 0x0000, 0x0900, "US", "Status" },
{ 0x0000, 0x0901, "AT", "Offending Element" },
{ 0x0000, 0x0902, "LO", "Exception Comment" },
{ 0x0000, 0x0903, "US", "Exception ID" },
{ 0x0000, 0x1000, "UI", "Affected SOP Instance UID" },
{ 0x0000, 0x1001, "UI", "Requested SOP Instance UID" },
{ 0x0000, 0x1002, "US", "Event Type ID" },
{ 0x0000, 0x1005, "AT", "Attribute Identifier List" },
{ 0x0000, 0x1008, "US", "Action Type ID" },
{ 0x0000, 0x1020, "US", "Number of Remaining Suboperations" },
{ 0x0000, 0x1021, "US", "Number of Completed Suboperations" },
{ 0x0000, 0x1022, "US", "Number of Failed Suboperations" },
{ 0x0000, 0x1023, "US", "Number of Warning Suboperations" },
{ 0x0000, 0x1030, "AE", "Move Originator Application Entity Title" },
{ 0x0000, 0x1031, "US", "Move Originator Message ID" },
{ 0x0000, 0x4000, "LO", "Dialog Receiver" },
{ 0x0000, 0x4010, "LO", "Terminal Type" },
{ 0x0000, 0x5010, "SH", "Message Set ID" },
{ 0x0000, 0x5020, "SH", "End Message Set" },
{ 0x0000, 0x5110, "LO", "Display Format" },
{ 0x0000, 0x5120, "LO", "Page Position ID" },
{ 0x0000, 0x5130, "LO", "Text Format ID" },
{ 0x0000, 0x5140, "LO", "Normal Reverse" },
{ 0x0000, 0x5150, "LO", "Add Gray Scale" },
{ 0x0000, 0x5160, "LO", "Borders" },
{ 0x0000, 0x5170, "IS", "Copies" },
{ 0x0000, 0x5180, "LO", "OldMagnificationType" },
{ 0x0000, 0x5190, "LO", "Erase" },
{ 0x0000, 0x51a0, "LO", "Print" },
{ 0x0000, 0x51b0, "US", "Overlays" },
{ 0x0002, 0x0000, "UL", "Meta Element Group Length" },
{ 0x0002, 0x0001, "OB", "File Meta Information Version" },
{ 0x0002, 0x0002, "UI", "Media Storage SOP Class UID" },
{ 0x0002, 0x0003, "UI", "Media Storage SOP Instance UID" },
{ 0x0002, 0x0010, "UI", "Transfer Syntax UID" },
{ 0x0002, 0x0012, "UI", "Implementation Class UID" },
{ 0x0002, 0x0013, "SH", "Implementation Version Name" },
{ 0x0002, 0x0016, "AE", "Source Application Entity Title" },
{ 0x0002, 0x0100, "UI", "Private Information Creator UID" },
{ 0x0002, 0x0102, "OB", "Private Information" },
{ 0x0003, 0x0000, "US", "?" },
{ 0x0003, 0x0008, "US", "ISI Command Field" },
{ 0x0003, 0x0011, "US", "Attach ID Application Code" },
{ 0x0003, 0x0012, "UL", "Attach ID Message Count" },
{ 0x0003, 0x0013, "DA", "Attach ID Date" },
{ 0x0003, 0x0014, "TM", "Attach ID Time" },
{ 0x0003, 0x0020, "US", "Message Type" },
{ 0x0003, 0x0030, "DA", "Max Waiting Date" },
{ 0x0003, 0x0031, "TM", "Max Waiting Time" },
{ 0x0004, 0x0000, "UL", "File Set Group Length" },
{ 0x0004, 0x1130, "CS", "File Set ID" },
{ 0x0004, 0x1141, "CS", "File Set Descriptor File ID" },
{ 0x0004, 0x1142, "CS", "File Set Descriptor File Specific Character Set" },
{ 0x0004, 0x1200, "UL", "Root Directory Entity First Directory Record Offset" },
{ 0x0004, 0x1202, "UL", "Root Directory Entity Last Directory Record Offset" },
{ 0x0004, 0x1212, "US", "File Set Consistency Flag" },
{ 0x0004, 0x1220, "SQ", "Directory Record Sequence" },
{ 0x0004, 0x1400, "UL", "Next Directory Record Offset" },
{ 0x0004, 0x1410, "US", "Record In Use Flag" },
{ 0x0004, 0x1420, "UL", "Referenced Lower Level Directory Entity Offset" },
{ 0x0004, 0x1430, "CS", "Directory Record Type" },
{ 0x0004, 0x1432, "UI", "Private Record UID" },
{ 0x0004, 0x1500, "CS", "Referenced File ID" },
{ 0x0004, 0x1504, "UL", "MRDR Directory Record Offset" },
{ 0x0004, 0x1510, "UI", "Referenced SOP Class UID In File" },
{ 0x0004, 0x1511, "UI", "Referenced SOP Instance UID In File" },
{ 0x0004, 0x1512, "UI", "Referenced Transfer Syntax UID In File" },
{ 0x0004, 0x1600, "UL", "Number of References" },
{ 0x0005, 0x0000, "US", "?" },
{ 0x0006, 0x0000, "US", "?" },
{ 0x0008, 0x0000, "UL", "Identifying Group Length" },
{ 0x0008, 0x0001, "UL", "Length to End" },
{ 0x0008, 0x0005, "CS", "Specific Character Set" },
{ 0x0008, 0x0008, "CS", "Image Type" },
{ 0x0008, 0x0010, "LO", "Recognition Code" },
{ 0x0008, 0x0012, "DA", "Instance Creation Date" },
{ 0x0008, 0x0013, "TM", "Instance Creation Time" },
{ 0x0008, 0x0014, "UI", "Instance Creator UID" },
{ 0x0008, 0x0016, "UI", "SOP Class UID" },
{ 0x0008, 0x0018, "UI", "SOP Instance UID" },
{ 0x0008, 0x0020, "DA", "Study Date" },
{ 0x0008, 0x0021, "DA", "Series Date" },
{ 0x0008, 0x0022, "DA", "Acquisition Date" },
{ 0x0008, 0x0023, "DA", "Image Date" },
{ 0x0008, 0x0024, "DA", "Overlay Date" },
{ 0x0008, 0x0025, "DA", "Curve Date" },
{ 0x0008, 0x002A, "DT", "Acquisition DateTime" },
{ 0x0008, 0x0030, "TM", "Study Time" },
{ 0x0008, 0x0031, "TM", "Series Time" },
{ 0x0008, 0x0032, "TM", "Acquisition Time" },
{ 0x0008, 0x0033, "TM", "Image Time" },
{ 0x0008, 0x0034, "TM", "Overlay Time" },
{ 0x0008, 0x0035, "TM", "Curve Time" },
{ 0x0008, 0x0040, "xs", "Old Data Set Type" },
{ 0x0008, 0x0041, "xs", "Old Data Set Subtype" },
{ 0x0008, 0x0042, "CS", "Nuclear Medicine Series Type" },
{ 0x0008, 0x0050, "SH", "Accession Number" },
{ 0x0008, 0x0052, "CS", "Query/Retrieve Level" },
{ 0x0008, 0x0054, "AE", "Retrieve AE Title" },
{ 0x0008, 0x0058, "UI", "Failed SOP Instance UID List" },
{ 0x0008, 0x0060, "CS", "Modality" },
{ 0x0008, 0x0062, "SQ", "Modality Subtype" },
{ 0x0008, 0x0064, "CS", "Conversion Type" },
{ 0x0008, 0x0068, "CS", "Presentation Intent Type" },
{ 0x0008, 0x0070, "LO", "Manufacturer" },
{ 0x0008, 0x0080, "LO", "Institution Name" },
{ 0x0008, 0x0081, "ST", "Institution Address" },
{ 0x0008, 0x0082, "SQ", "Institution Code Sequence" },
{ 0x0008, 0x0090, "PN", "Referring Physician's Name" },
{ 0x0008, 0x0092, "ST", "Referring Physician's Address" },
{ 0x0008, 0x0094, "SH", "Referring Physician's Telephone Numbers" },
{ 0x0008, 0x0100, "SH", "Code Value" },
{ 0x0008, 0x0102, "SH", "Coding Scheme Designator" },
{ 0x0008, 0x0103, "SH", "Coding Scheme Version" },
{ 0x0008, 0x0104, "LO", "Code Meaning" },
{ 0x0008, 0x0105, "CS", "Mapping Resource" },
{ 0x0008, 0x0106, "DT", "Context Group Version" },
{ 0x0008, 0x010b, "CS", "Code Set Extension Flag" },
{ 0x0008, 0x010c, "UI", "Private Coding Scheme Creator UID" },
{ 0x0008, 0x010d, "UI", "Code Set Extension Creator UID" },
{ 0x0008, 0x010f, "CS", "Context Identifier" },
{ 0x0008, 0x1000, "LT", "Network ID" },
{ 0x0008, 0x1010, "SH", "Station Name" },
{ 0x0008, 0x1030, "LO", "Study Description" },
{ 0x0008, 0x1032, "SQ", "Procedure Code Sequence" },
{ 0x0008, 0x103e, "LO", "Series Description" },
{ 0x0008, 0x1040, "LO", "Institutional Department Name" },
{ 0x0008, 0x1048, "PN", "Physician of Record" },
{ 0x0008, 0x1050, "PN", "Performing Physician's Name" },
{ 0x0008, 0x1060, "PN", "Name of Physician(s) Reading Study" },
{ 0x0008, 0x1070, "PN", "Operator's Name" },
{ 0x0008, 0x1080, "LO", "Admitting Diagnosis Description" },
{ 0x0008, 0x1084, "SQ", "Admitting Diagnosis Code Sequence" },
{ 0x0008, 0x1090, "LO", "Manufacturer's Model Name" },
{ 0x0008, 0x1100, "SQ", "Referenced Results Sequence" },
{ 0x0008, 0x1110, "SQ", "Referenced Study Sequence" },
{ 0x0008, 0x1111, "SQ", "Referenced Study Component Sequence" },
{ 0x0008, 0x1115, "SQ", "Referenced Series Sequence" },
{ 0x0008, 0x1120, "SQ", "Referenced Patient Sequence" },
{ 0x0008, 0x1125, "SQ", "Referenced Visit Sequence" },
{ 0x0008, 0x1130, "SQ", "Referenced Overlay Sequence" },
{ 0x0008, 0x1140, "SQ", "Referenced Image Sequence" },
{ 0x0008, 0x1145, "SQ", "Referenced Curve Sequence" },
{ 0x0008, 0x1148, "SQ", "Referenced Previous Waveform" },
{ 0x0008, 0x114a, "SQ", "Referenced Simultaneous Waveforms" },
{ 0x0008, 0x114c, "SQ", "Referenced Subsequent Waveform" },
{ 0x0008, 0x1150, "UI", "Referenced SOP Class UID" },
{ 0x0008, 0x1155, "UI", "Referenced SOP Instance UID" },
{ 0x0008, 0x1160, "IS", "Referenced Frame Number" },
{ 0x0008, 0x1195, "UI", "Transaction UID" },
{ 0x0008, 0x1197, "US", "Failure Reason" },
{ 0x0008, 0x1198, "SQ", "Failed SOP Sequence" },
{ 0x0008, 0x1199, "SQ", "Referenced SOP Sequence" },
{ 0x0008, 0x2110, "CS", "Old Lossy Image Compression" },
{ 0x0008, 0x2111, "ST", "Derivation Description" },
{ 0x0008, 0x2112, "SQ", "Source Image Sequence" },
{ 0x0008, 0x2120, "SH", "Stage Name" },
{ 0x0008, 0x2122, "IS", "Stage Number" },
{ 0x0008, 0x2124, "IS", "Number of Stages" },
{ 0x0008, 0x2128, "IS", "View Number" },
{ 0x0008, 0x2129, "IS", "Number of Event Timers" },
{ 0x0008, 0x212a, "IS", "Number of Views in Stage" },
{ 0x0008, 0x2130, "DS", "Event Elapsed Time(s)" },
{ 0x0008, 0x2132, "LO", "Event Timer Name(s)" },
{ 0x0008, 0x2142, "IS", "Start Trim" },
{ 0x0008, 0x2143, "IS", "Stop Trim" },
{ 0x0008, 0x2144, "IS", "Recommended Display Frame Rate" },
{ 0x0008, 0x2200, "CS", "Transducer Position" },
{ 0x0008, 0x2204, "CS", "Transducer Orientation" },
{ 0x0008, 0x2208, "CS", "Anatomic Structure" },
{ 0x0008, 0x2218, "SQ", "Anatomic Region Sequence" },
{ 0x0008, 0x2220, "SQ", "Anatomic Region Modifier Sequence" },
{ 0x0008, 0x2228, "SQ", "Primary Anatomic Structure Sequence" },
{ 0x0008, 0x2230, "SQ", "Primary Anatomic Structure Modifier Sequence" },
{ 0x0008, 0x2240, "SQ", "Transducer Position Sequence" },
{ 0x0008, 0x2242, "SQ", "Transducer Position Modifier Sequence" },
{ 0x0008, 0x2244, "SQ", "Transducer Orientation Sequence" },
{ 0x0008, 0x2246, "SQ", "Transducer Orientation Modifier Sequence" },
{ 0x0008, 0x2251, "SQ", "Anatomic Structure Space Or Region Code Sequence" },
{ 0x0008, 0x2253, "SQ", "Anatomic Portal Of Entrance Code Sequence" },
{ 0x0008, 0x2255, "SQ", "Anatomic Approach Direction Code Sequence" },
{ 0x0008, 0x2256, "ST", "Anatomic Perspective Description" },
{ 0x0008, 0x2257, "SQ", "Anatomic Perspective Code Sequence" },
{ 0x0008, 0x2258, "ST", "Anatomic Location Of Examining Instrument Description" },
{ 0x0008, 0x2259, "SQ", "Anatomic Location Of Examining Instrument Code Sequence" },
{ 0x0008, 0x225a, "SQ", "Anatomic Structure Space Or Region Modifier Code Sequence" },
{ 0x0008, 0x225c, "SQ", "OnAxis Background Anatomic Structure Code Sequence" },
{ 0x0008, 0x4000, "LT", "Identifying Comments" },
{ 0x0009, 0x0000, "xs", "?" },
{ 0x0009, 0x0001, "xs", "?" },
{ 0x0009, 0x0002, "xs", "?" },
{ 0x0009, 0x0003, "xs", "?" },
{ 0x0009, 0x0004, "xs", "?" },
{ 0x0009, 0x0005, "UN", "?" },
{ 0x0009, 0x0006, "UN", "?" },
{ 0x0009, 0x0007, "UN", "?" },
{ 0x0009, 0x0008, "xs", "?" },
{ 0x0009, 0x0009, "LT", "?" },
{ 0x0009, 0x000a, "IS", "?" },
{ 0x0009, 0x000b, "IS", "?" },
{ 0x0009, 0x000c, "IS", "?" },
{ 0x0009, 0x000d, "IS", "?" },
{ 0x0009, 0x000e, "IS", "?" },
{ 0x0009, 0x000f, "UN", "?" },
{ 0x0009, 0x0010, "xs", "?" },
{ 0x0009, 0x0011, "xs", "?" },
{ 0x0009, 0x0012, "xs", "?" },
{ 0x0009, 0x0013, "xs", "?" },
{ 0x0009, 0x0014, "xs", "?" },
{ 0x0009, 0x0015, "xs", "?" },
{ 0x0009, 0x0016, "xs", "?" },
{ 0x0009, 0x0017, "LT", "?" },
{ 0x0009, 0x0018, "LT", "Data Set Identifier" },
{ 0x0009, 0x001a, "US", "?" },
{ 0x0009, 0x001e, "UI", "?" },
{ 0x0009, 0x0020, "xs", "?" },
{ 0x0009, 0x0021, "xs", "?" },
{ 0x0009, 0x0022, "SH", "User Orientation" },
{ 0x0009, 0x0023, "SL", "Initiation Type" },
{ 0x0009, 0x0024, "xs", "?" },
{ 0x0009, 0x0025, "xs", "?" },
{ 0x0009, 0x0026, "xs", "?" },
{ 0x0009, 0x0027, "xs", "?" },
{ 0x0009, 0x0029, "xs", "?" },
{ 0x0009, 0x002a, "SL", "?" },
{ 0x0009, 0x002c, "LO", "Series Comments" },
{ 0x0009, 0x002d, "SL", "Track Beat Average" },
{ 0x0009, 0x002e, "FD", "Distance Prescribed" },
{ 0x0009, 0x002f, "LT", "?" },
{ 0x0009, 0x0030, "xs", "?" },
{ 0x0009, 0x0031, "xs", "?" },
{ 0x0009, 0x0032, "LT", "?" },
{ 0x0009, 0x0034, "xs", "?" },
{ 0x0009, 0x0035, "SL", "Gantry Locus Type" },
{ 0x0009, 0x0037, "SL", "Starting Heart Rate" },
{ 0x0009, 0x0038, "xs", "?" },
{ 0x0009, 0x0039, "SL", "RR Window Offset" },
{ 0x0009, 0x003a, "SL", "Percent Cycle Imaged" },
{ 0x0009, 0x003e, "US", "?" },
{ 0x0009, 0x003f, "US", "?" },
{ 0x0009, 0x0040, "xs", "?" },
{ 0x0009, 0x0041, "xs", "?" },
{ 0x0009, 0x0042, "xs", "?" },
{ 0x0009, 0x0043, "xs", "?" },
{ 0x0009, 0x0050, "LT", "?" },
{ 0x0009, 0x0051, "xs", "?" },
{ 0x0009, 0x0060, "LT", "?" },
{ 0x0009, 0x0061, "LT", "Series Unique Identifier" },
{ 0x0009, 0x0070, "LT", "?" },
{ 0x0009, 0x0080, "LT", "?" },
{ 0x0009, 0x0091, "LT", "?" },
{ 0x0009, 0x00e2, "LT", "?" },
{ 0x0009, 0x00e3, "UI", "Equipment UID" },
{ 0x0009, 0x00e6, "SH", "Genesis Version Now" },
{ 0x0009, 0x00e7, "UL", "Exam Record Checksum" },
{ 0x0009, 0x00e8, "UL", "?" },
{ 0x0009, 0x00e9, "SL", "Actual Series Data Time Stamp" },
{ 0x0009, 0x00f2, "UN", "?" },
{ 0x0009, 0x00f3, "UN", "?" },
{ 0x0009, 0x00f4, "LT", "?" },
{ 0x0009, 0x00f5, "xs", "?" },
{ 0x0009, 0x00f6, "LT", "PDM Data Object Type Extension" },
{ 0x0009, 0x00f8, "US", "?" },
{ 0x0009, 0x00fb, "IS", "?" },
{ 0x0009, 0x1002, "OB", "?" },
{ 0x0009, 0x1003, "OB", "?" },
{ 0x0009, 0x1010, "UN", "?" },
{ 0x0010, 0x0000, "UL", "Patient Group Length" },
{ 0x0010, 0x0010, "PN", "Patient's Name" },
{ 0x0010, 0x0020, "LO", "Patient's ID" },
{ 0x0010, 0x0021, "LO", "Issuer of Patient's ID" },
{ 0x0010, 0x0030, "DA", "Patient's Birth Date" },
{ 0x0010, 0x0032, "TM", "Patient's Birth Time" },
{ 0x0010, 0x0040, "CS", "Patient's Sex" },
{ 0x0010, 0x0050, "SQ", "Patient's Insurance Plan Code Sequence" },
{ 0x0010, 0x1000, "LO", "Other Patient's ID's" },
{ 0x0010, 0x1001, "PN", "Other Patient's Names" },
{ 0x0010, 0x1005, "PN", "Patient's Birth Name" },
{ 0x0010, 0x1010, "AS", "Patient's Age" },
{ 0x0010, 0x1020, "DS", "Patient's Size" },
{ 0x0010, 0x1030, "DS", "Patient's Weight" },
{ 0x0010, 0x1040, "LO", "Patient's Address" },
{ 0x0010, 0x1050, "LT", "Insurance Plan Identification" },
{ 0x0010, 0x1060, "PN", "Patient's Mother's Birth Name" },
{ 0x0010, 0x1080, "LO", "Military Rank" },
{ 0x0010, 0x1081, "LO", "Branch of Service" },
{ 0x0010, 0x1090, "LO", "Medical Record Locator" },
{ 0x0010, 0x2000, "LO", "Medical Alerts" },
{ 0x0010, 0x2110, "LO", "Contrast Allergies" },
{ 0x0010, 0x2150, "LO", "Country of Residence" },
{ 0x0010, 0x2152, "LO", "Region of Residence" },
{ 0x0010, 0x2154, "SH", "Patients Telephone Numbers" },
{ 0x0010, 0x2160, "SH", "Ethnic Group" },
{ 0x0010, 0x2180, "SH", "Occupation" },
{ 0x0010, 0x21a0, "CS", "Smoking Status" },
{ 0x0010, 0x21b0, "LT", "Additional Patient History" },
{ 0x0010, 0x21c0, "US", "Pregnancy Status" },
{ 0x0010, 0x21d0, "DA", "Last Menstrual Date" },
{ 0x0010, 0x21f0, "LO", "Patients Religious Preference" },
{ 0x0010, 0x4000, "LT", "Patient Comments" },
{ 0x0011, 0x0001, "xs", "?" },
{ 0x0011, 0x0002, "US", "?" },
{ 0x0011, 0x0003, "LT", "Patient UID" },
{ 0x0011, 0x0004, "LT", "Patient ID" },
{ 0x0011, 0x000a, "xs", "?" },
{ 0x0011, 0x000b, "SL", "Effective Series Duration" },
{ 0x0011, 0x000c, "SL", "Num Beats" },
{ 0x0011, 0x000d, "LO", "Radio Nuclide Name" },
{ 0x0011, 0x0010, "xs", "?" },
{ 0x0011, 0x0011, "xs", "?" },
{ 0x0011, 0x0012, "LO", "Dataset Name" },
{ 0x0011, 0x0013, "LO", "Dataset Type" },
{ 0x0011, 0x0015, "xs", "?" },
{ 0x0011, 0x0016, "SL", "Energy Number" },
{ 0x0011, 0x0017, "SL", "RR Interval Window Number" },
{ 0x0011, 0x0018, "SL", "MG Bin Number" },
{ 0x0011, 0x0019, "FD", "Radius Of Rotation" },
{ 0x0011, 0x001a, "SL", "Detector Count Zone" },
{ 0x0011, 0x001b, "SL", "Num Energy Windows" },
{ 0x0011, 0x001c, "SL", "Energy Offset" },
{ 0x0011, 0x001d, "SL", "Energy Range" },
{ 0x0011, 0x001f, "SL", "Image Orientation" },
{ 0x0011, 0x0020, "xs", "?" },
{ 0x0011, 0x0021, "xs", "?" },
{ 0x0011, 0x0022, "xs", "?" },
{ 0x0011, 0x0023, "xs", "?" },
{ 0x0011, 0x0024, "SL", "FOV Mask Y Cutoff Angle" },
{ 0x0011, 0x0025, "xs", "?" },
{ 0x0011, 0x0026, "SL", "Table Orientation" },
{ 0x0011, 0x0027, "SL", "ROI Top Left" },
{ 0x0011, 0x0028, "SL", "ROI Bottom Right" },
{ 0x0011, 0x0030, "xs", "?" },
{ 0x0011, 0x0031, "xs", "?" },
{ 0x0011, 0x0032, "UN", "?" },
{ 0x0011, 0x0033, "LO", "Energy Correct Name" },
{ 0x0011, 0x0034, "LO", "Spatial Correct Name" },
{ 0x0011, 0x0035, "xs", "?" },
{ 0x0011, 0x0036, "LO", "Uniformity Correct Name" },
{ 0x0011, 0x0037, "LO", "Acquisition Specific Correct Name" },
{ 0x0011, 0x0038, "SL", "Byte Order" },
{ 0x0011, 0x003a, "SL", "Picture Format" },
{ 0x0011, 0x003b, "FD", "Pixel Scale" },
{ 0x0011, 0x003c, "FD", "Pixel Offset" },
{ 0x0011, 0x003e, "SL", "FOV Shape" },
{ 0x0011, 0x003f, "SL", "Dataset Flags" },
{ 0x0011, 0x0040, "xs", "?" },
{ 0x0011, 0x0041, "LT", "Medical Alerts" },
{ 0x0011, 0x0042, "LT", "Contrast Allergies" },
{ 0x0011, 0x0044, "FD", "Threshold Center" },
{ 0x0011, 0x0045, "FD", "Threshold Width" },
{ 0x0011, 0x0046, "SL", "Interpolation Type" },
{ 0x0011, 0x0055, "FD", "Period" },
{ 0x0011, 0x0056, "FD", "ElapsedTime" },
{ 0x0011, 0x00a1, "DA", "Patient Registration Date" },
{ 0x0011, 0x00a2, "TM", "Patient Registration Time" },
{ 0x0011, 0x00b0, "LT", "Patient Last Name" },
{ 0x0011, 0x00b2, "LT", "Patient First Name" },
{ 0x0011, 0x00b4, "LT", "Patient Hospital Status" },
{ 0x0011, 0x00bc, "TM", "Current Location Time" },
{ 0x0011, 0x00c0, "LT", "Patient Insurance Status" },
{ 0x0011, 0x00d0, "LT", "Patient Billing Type" },
{ 0x0011, 0x00d2, "LT", "Patient Billing Address" },
{ 0x0013, 0x0000, "LT", "Modifying Physician" },
{ 0x0013, 0x0010, "xs", "?" },
{ 0x0013, 0x0011, "SL", "?" },
{ 0x0013, 0x0012, "xs", "?" },
{ 0x0013, 0x0016, "SL", "AutoTrack Peak" },
{ 0x0013, 0x0017, "SL", "AutoTrack Width" },
{ 0x0013, 0x0018, "FD", "Transmission Scan Time" },
{ 0x0013, 0x0019, "FD", "Transmission Mask Width" },
{ 0x0013, 0x001a, "FD", "Copper Attenuator Thickness" },
{ 0x0013, 0x001c, "FD", "?" },
{ 0x0013, 0x001d, "FD", "?" },
{ 0x0013, 0x001e, "FD", "Tomo View Offset" },
{ 0x0013, 0x0020, "LT", "Patient Name" },
{ 0x0013, 0x0022, "LT", "Patient Id" },
{ 0x0013, 0x0026, "LT", "Study Comments" },
{ 0x0013, 0x0030, "DA", "Patient Birthdate" },
{ 0x0013, 0x0031, "DS", "Patient Weight" },
{ 0x0013, 0x0032, "LT", "Patients Maiden Name" },
{ 0x0013, 0x0033, "LT", "Referring Physician" },
{ 0x0013, 0x0034, "LT", "Admitting Diagnosis" },
{ 0x0013, 0x0035, "LT", "Patient Sex" },
{ 0x0013, 0x0040, "LT", "Procedure Description" },
{ 0x0013, 0x0042, "LT", "Patient Rest Direction" },
{ 0x0013, 0x0044, "LT", "Patient Position" },
{ 0x0013, 0x0046, "LT", "View Direction" },
{ 0x0015, 0x0001, "DS", "Stenosis Calibration Ratio" },
{ 0x0015, 0x0002, "DS", "Stenosis Magnification" },
{ 0x0015, 0x0003, "DS", "Cardiac Calibration Ratio" },
{ 0x0018, 0x0000, "UL", "Acquisition Group Length" },
{ 0x0018, 0x0010, "LO", "Contrast/Bolus Agent" },
{ 0x0018, 0x0012, "SQ", "Contrast/Bolus Agent Sequence" },
{ 0x0018, 0x0014, "SQ", "Contrast/Bolus Administration Route Sequence" },
{ 0x0018, 0x0015, "CS", "Body Part Examined" },
{ 0x0018, 0x0020, "CS", "Scanning Sequence" },
{ 0x0018, 0x0021, "CS", "Sequence Variant" },
{ 0x0018, 0x0022, "CS", "Scan Options" },
{ 0x0018, 0x0023, "CS", "MR Acquisition Type" },
{ 0x0018, 0x0024, "SH", "Sequence Name" },
{ 0x0018, 0x0025, "CS", "Angio Flag" },
{ 0x0018, 0x0026, "SQ", "Intervention Drug Information Sequence" },
{ 0x0018, 0x0027, "TM", "Intervention Drug Stop Time" },
{ 0x0018, 0x0028, "DS", "Intervention Drug Dose" },
{ 0x0018, 0x0029, "SQ", "Intervention Drug Code Sequence" },
{ 0x0018, 0x002a, "SQ", "Additional Drug Sequence" },
{ 0x0018, 0x0030, "LO", "Radionuclide" },
{ 0x0018, 0x0031, "LO", "Radiopharmaceutical" },
{ 0x0018, 0x0032, "DS", "Energy Window Centerline" },
{ 0x0018, 0x0033, "DS", "Energy Window Total Width" },
{ 0x0018, 0x0034, "LO", "Intervention Drug Name" },
{ 0x0018, 0x0035, "TM", "Intervention Drug Start Time" },
{ 0x0018, 0x0036, "SQ", "Intervention Therapy Sequence" },
{ 0x0018, 0x0037, "CS", "Therapy Type" },
{ 0x0018, 0x0038, "CS", "Intervention Status" },
{ 0x0018, 0x0039, "CS", "Therapy Description" },
{ 0x0018, 0x0040, "IS", "Cine Rate" },
{ 0x0018, 0x0050, "DS", "Slice Thickness" },
{ 0x0018, 0x0060, "DS", "KVP" },
{ 0x0018, 0x0070, "IS", "Counts Accumulated" },
{ 0x0018, 0x0071, "CS", "Acquisition Termination Condition" },
{ 0x0018, 0x0072, "DS", "Effective Series Duration" },
{ 0x0018, 0x0073, "CS", "Acquisition Start Condition" },
{ 0x0018, 0x0074, "IS", "Acquisition Start Condition Data" },
{ 0x0018, 0x0075, "IS", "Acquisition Termination Condition Data" },
{ 0x0018, 0x0080, "DS", "Repetition Time" },
{ 0x0018, 0x0081, "DS", "Echo Time" },
{ 0x0018, 0x0082, "DS", "Inversion Time" },
{ 0x0018, 0x0083, "DS", "Number of Averages" },
{ 0x0018, 0x0084, "DS", "Imaging Frequency" },
{ 0x0018, 0x0085, "SH", "Imaged Nucleus" },
{ 0x0018, 0x0086, "IS", "Echo Number(s)" },
{ 0x0018, 0x0087, "DS", "Magnetic Field Strength" },
{ 0x0018, 0x0088, "DS", "Spacing Between Slices" },
{ 0x0018, 0x0089, "IS", "Number of Phase Encoding Steps" },
{ 0x0018, 0x0090, "DS", "Data Collection Diameter" },
{ 0x0018, 0x0091, "IS", "Echo Train Length" },
{ 0x0018, 0x0093, "DS", "Percent Sampling" },
{ 0x0018, 0x0094, "DS", "Percent Phase Field of View" },
{ 0x0018, 0x0095, "DS", "Pixel Bandwidth" },
{ 0x0018, 0x1000, "LO", "Device Serial Number" },
{ 0x0018, 0x1004, "LO", "Plate ID" },
{ 0x0018, 0x1010, "LO", "Secondary Capture Device ID" },
{ 0x0018, 0x1012, "DA", "Date of Secondary Capture" },
{ 0x0018, 0x1014, "TM", "Time of Secondary Capture" },
{ 0x0018, 0x1016, "LO", "Secondary Capture Device Manufacturer" },
{ 0x0018, 0x1018, "LO", "Secondary Capture Device Manufacturer Model Name" },
{ 0x0018, 0x1019, "LO", "Secondary Capture Device Software Version(s)" },
{ 0x0018, 0x1020, "LO", "Software Version(s)" },
{ 0x0018, 0x1022, "SH", "Video Image Format Acquired" },
{ 0x0018, 0x1023, "LO", "Digital Image Format Acquired" },
{ 0x0018, 0x1030, "LO", "Protocol Name" },
{ 0x0018, 0x1040, "LO", "Contrast/Bolus Route" },
{ 0x0018, 0x1041, "DS", "Contrast/Bolus Volume" },
{ 0x0018, 0x1042, "TM", "Contrast/Bolus Start Time" },
{ 0x0018, 0x1043, "TM", "Contrast/Bolus Stop Time" },
{ 0x0018, 0x1044, "DS", "Contrast/Bolus Total Dose" },
{ 0x0018, 0x1045, "IS", "Syringe Counts" },
{ 0x0018, 0x1046, "DS", "Contrast Flow Rate" },
{ 0x0018, 0x1047, "DS", "Contrast Flow Duration" },
{ 0x0018, 0x1048, "CS", "Contrast/Bolus Ingredient" },
{ 0x0018, 0x1049, "DS", "Contrast/Bolus Ingredient Concentration" },
{ 0x0018, 0x1050, "DS", "Spatial Resolution" },
{ 0x0018, 0x1060, "DS", "Trigger Time" },
{ 0x0018, 0x1061, "LO", "Trigger Source or Type" },
{ 0x0018, 0x1062, "IS", "Nominal Interval" },
{ 0x0018, 0x1063, "DS", "Frame Time" },
{ 0x0018, 0x1064, "LO", "Framing Type" },
{ 0x0018, 0x1065, "DS", "Frame Time Vector" },
{ 0x0018, 0x1066, "DS", "Frame Delay" },
{ 0x0018, 0x1067, "DS", "Image Trigger Delay" },
{ 0x0018, 0x1068, "DS", "Group Time Offset" },
{ 0x0018, 0x1069, "DS", "Trigger Time Offset" },
{ 0x0018, 0x106a, "CS", "Synchronization Trigger" },
{ 0x0018, 0x106b, "UI", "Synchronization Frame of Reference" },
{ 0x0018, 0x106e, "UL", "Trigger Sample Position" },
{ 0x0018, 0x1070, "LO", "Radiopharmaceutical Route" },
{ 0x0018, 0x1071, "DS", "Radiopharmaceutical Volume" },
{ 0x0018, 0x1072, "TM", "Radiopharmaceutical Start Time" },
{ 0x0018, 0x1073, "TM", "Radiopharmaceutical Stop Time" },
{ 0x0018, 0x1074, "DS", "Radionuclide Total Dose" },
{ 0x0018, 0x1075, "DS", "Radionuclide Half Life" },
{ 0x0018, 0x1076, "DS", "Radionuclide Positron Fraction" },
{ 0x0018, 0x1077, "DS", "Radiopharmaceutical Specific Activity" },
{ 0x0018, 0x1080, "CS", "Beat Rejection Flag" },
{ 0x0018, 0x1081, "IS", "Low R-R Value" },
{ 0x0018, 0x1082, "IS", "High R-R Value" },
{ 0x0018, 0x1083, "IS", "Intervals Acquired" },
{ 0x0018, 0x1084, "IS", "Intervals Rejected" },
{ 0x0018, 0x1085, "LO", "PVC Rejection" },
{ 0x0018, 0x1086, "IS", "Skip Beats" },
{ 0x0018, 0x1088, "IS", "Heart Rate" },
{ 0x0018, 0x1090, "IS", "Cardiac Number of Images" },
{ 0x0018, 0x1094, "IS", "Trigger Window" },
{ 0x0018, 0x1100, "DS", "Reconstruction Diameter" },
{ 0x0018, 0x1110, "DS", "Distance Source to Detector" },
{ 0x0018, 0x1111, "DS", "Distance Source to Patient" },
{ 0x0018, 0x1114, "DS", "Estimated Radiographic Magnification Factor" },
{ 0x0018, 0x1120, "DS", "Gantry/Detector Tilt" },
{ 0x0018, 0x1121, "DS", "Gantry/Detector Slew" },
{ 0x0018, 0x1130, "DS", "Table Height" },
{ 0x0018, 0x1131, "DS", "Table Traverse" },
{ 0x0018, 0x1134, "CS", "Table Motion" },
{ 0x0018, 0x1135, "DS", "Table Vertical Increment" },
{ 0x0018, 0x1136, "DS", "Table Lateral Increment" },
{ 0x0018, 0x1137, "DS", "Table Longitudinal Increment" },
{ 0x0018, 0x1138, "DS", "Table Angle" },
{ 0x0018, 0x113a, "CS", "Table Type" },
{ 0x0018, 0x1140, "CS", "Rotation Direction" },
{ 0x0018, 0x1141, "DS", "Angular Position" },
{ 0x0018, 0x1142, "DS", "Radial Position" },
{ 0x0018, 0x1143, "DS", "Scan Arc" },
{ 0x0018, 0x1144, "DS", "Angular Step" },
{ 0x0018, 0x1145, "DS", "Center of Rotation Offset" },
{ 0x0018, 0x1146, "DS", "Rotation Offset" },
{ 0x0018, 0x1147, "CS", "Field of View Shape" },
{ 0x0018, 0x1149, "IS", "Field of View Dimension(s)" },
{ 0x0018, 0x1150, "IS", "Exposure Time" },
{ 0x0018, 0x1151, "IS", "X-ray Tube Current" },
{ 0x0018, 0x1152, "IS", "Exposure" },
{ 0x0018, 0x1153, "IS", "Exposure in uAs" },
{ 0x0018, 0x1154, "DS", "AveragePulseWidth" },
{ 0x0018, 0x1155, "CS", "RadiationSetting" },
{ 0x0018, 0x1156, "CS", "Rectification Type" },
{ 0x0018, 0x115a, "CS", "RadiationMode" },
{ 0x0018, 0x115e, "DS", "ImageAreaDoseProduct" },
{ 0x0018, 0x1160, "SH", "Filter Type" },
{ 0x0018, 0x1161, "LO", "TypeOfFilters" },
{ 0x0018, 0x1162, "DS", "IntensifierSize" },
{ 0x0018, 0x1164, "DS", "ImagerPixelSpacing" },
{ 0x0018, 0x1166, "CS", "Grid" },
{ 0x0018, 0x1170, "IS", "Generator Power" },
{ 0x0018, 0x1180, "SH", "Collimator/Grid Name" },
{ 0x0018, 0x1181, "CS", "Collimator Type" },
{ 0x0018, 0x1182, "IS", "Focal Distance" },
{ 0x0018, 0x1183, "DS", "X Focus Center" },
{ 0x0018, 0x1184, "DS", "Y Focus Center" },
{ 0x0018, 0x1190, "DS", "Focal Spot(s)" },
{ 0x0018, 0x1191, "CS", "Anode Target Material" },
{ 0x0018, 0x11a0, "DS", "Body Part Thickness" },
{ 0x0018, 0x11a2, "DS", "Compression Force" },
{ 0x0018, 0x1200, "DA", "Date of Last Calibration" },
{ 0x0018, 0x1201, "TM", "Time of Last Calibration" },
{ 0x0018, 0x1210, "SH", "Convolution Kernel" },
{ 0x0018, 0x1240, "IS", "Upper/Lower Pixel Values" },
{ 0x0018, 0x1242, "IS", "Actual Frame Duration" },
{ 0x0018, 0x1243, "IS", "Count Rate" },
{ 0x0018, 0x1244, "US", "Preferred Playback Sequencing" },
{ 0x0018, 0x1250, "SH", "Receiving Coil" },
{ 0x0018, 0x1251, "SH", "Transmitting Coil" },
{ 0x0018, 0x1260, "SH", "Plate Type" },
{ 0x0018, 0x1261, "LO", "Phosphor Type" },
{ 0x0018, 0x1300, "DS", "Scan Velocity" },
{ 0x0018, 0x1301, "CS", "Whole Body Technique" },
{ 0x0018, 0x1302, "IS", "Scan Length" },
{ 0x0018, 0x1310, "US", "Acquisition Matrix" },
{ 0x0018, 0x1312, "CS", "Phase Encoding Direction" },
{ 0x0018, 0x1314, "DS", "Flip Angle" },
{ 0x0018, 0x1315, "CS", "Variable Flip Angle Flag" },
{ 0x0018, 0x1316, "DS", "SAR" },
{ 0x0018, 0x1318, "DS", "dB/dt" },
{ 0x0018, 0x1400, "LO", "Acquisition Device Processing Description" },
{ 0x0018, 0x1401, "LO", "Acquisition Device Processing Code" },
{ 0x0018, 0x1402, "CS", "Cassette Orientation" },
{ 0x0018, 0x1403, "CS", "Cassette Size" },
{ 0x0018, 0x1404, "US", "Exposures on Plate" },
{ 0x0018, 0x1405, "IS", "Relative X-ray Exposure" },
{ 0x0018, 0x1450, "DS", "Column Angulation" },
{ 0x0018, 0x1460, "DS", "Tomo Layer Height" },
{ 0x0018, 0x1470, "DS", "Tomo Angle" },
{ 0x0018, 0x1480, "DS", "Tomo Time" },
{ 0x0018, 0x1490, "CS", "Tomo Type" },
{ 0x0018, 0x1491, "CS", "Tomo Class" },
{ 0x0018, 0x1495, "IS", "Number of Tomosynthesis Source Images" },
{ 0x0018, 0x1500, "CS", "PositionerMotion" },
{ 0x0018, 0x1508, "CS", "Positioner Type" },
{ 0x0018, 0x1510, "DS", "PositionerPrimaryAngle" },
{ 0x0018, 0x1511, "DS", "PositionerSecondaryAngle" },
{ 0x0018, 0x1520, "DS", "PositionerPrimaryAngleIncrement" },
{ 0x0018, 0x1521, "DS", "PositionerSecondaryAngleIncrement" },
{ 0x0018, 0x1530, "DS", "DetectorPrimaryAngle" },
{ 0x0018, 0x1531, "DS", "DetectorSecondaryAngle" },
{ 0x0018, 0x1600, "CS", "Shutter Shape" },
{ 0x0018, 0x1602, "IS", "Shutter Left Vertical Edge" },
{ 0x0018, 0x1604, "IS", "Shutter Right Vertical Edge" },
{ 0x0018, 0x1606, "IS", "Shutter Upper Horizontal Edge" },
{ 0x0018, 0x1608, "IS", "Shutter Lower Horizonta lEdge" },
{ 0x0018, 0x1610, "IS", "Center of Circular Shutter" },
{ 0x0018, 0x1612, "IS", "Radius of Circular Shutter" },
{ 0x0018, 0x1620, "IS", "Vertices of Polygonal Shutter" },
{ 0x0018, 0x1622, "US", "Shutter Presentation Value" },
{ 0x0018, 0x1623, "US", "Shutter Overlay Group" },
{ 0x0018, 0x1700, "CS", "Collimator Shape" },
{ 0x0018, 0x1702, "IS", "Collimator Left Vertical Edge" },
{ 0x0018, 0x1704, "IS", "Collimator Right Vertical Edge" },
{ 0x0018, 0x1706, "IS", "Collimator Upper Horizontal Edge" },
{ 0x0018, 0x1708, "IS", "Collimator Lower Horizontal Edge" },
{ 0x0018, 0x1710, "IS", "Center of Circular Collimator" },
{ 0x0018, 0x1712, "IS", "Radius of Circular Collimator" },
{ 0x0018, 0x1720, "IS", "Vertices of Polygonal Collimator" },
{ 0x0018, 0x1800, "CS", "Acquisition Time Synchronized" },
{ 0x0018, 0x1801, "SH", "Time Source" },
{ 0x0018, 0x1802, "CS", "Time Distribution Protocol" },
{ 0x0018, 0x4000, "LT", "Acquisition Comments" },
{ 0x0018, 0x5000, "SH", "Output Power" },
{ 0x0018, 0x5010, "LO", "Transducer Data" },
{ 0x0018, 0x5012, "DS", "Focus Depth" },
{ 0x0018, 0x5020, "LO", "Processing Function" },
{ 0x0018, 0x5021, "LO", "Postprocessing Function" },
{ 0x0018, 0x5022, "DS", "Mechanical Index" },
{ 0x0018, 0x5024, "DS", "Thermal Index" },
{ 0x0018, 0x5026, "DS", "Cranial Thermal Index" },
{ 0x0018, 0x5027, "DS", "Soft Tissue Thermal Index" },
{ 0x0018, 0x5028, "DS", "Soft Tissue-Focus Thermal Index" },
{ 0x0018, 0x5029, "DS", "Soft Tissue-Surface Thermal Index" },
{ 0x0018, 0x5030, "DS", "Dynamic Range" },
{ 0x0018, 0x5040, "DS", "Total Gain" },
{ 0x0018, 0x5050, "IS", "Depth of Scan Field" },
{ 0x0018, 0x5100, "CS", "Patient Position" },
{ 0x0018, 0x5101, "CS", "View Position" },
{ 0x0018, 0x5104, "SQ", "Projection Eponymous Name Code Sequence" },
{ 0x0018, 0x5210, "DS", "Image Transformation Matrix" },
{ 0x0018, 0x5212, "DS", "Image Translation Vector" },
{ 0x0018, 0x6000, "DS", "Sensitivity" },
{ 0x0018, 0x6011, "IS", "Sequence of Ultrasound Regions" },
{ 0x0018, 0x6012, "US", "Region Spatial Format" },
{ 0x0018, 0x6014, "US", "Region Data Type" },
{ 0x0018, 0x6016, "UL", "Region Flags" },
{ 0x0018, 0x6018, "UL", "Region Location Min X0" },
{ 0x0018, 0x601a, "UL", "Region Location Min Y0" },
{ 0x0018, 0x601c, "UL", "Region Location Max X1" },
{ 0x0018, 0x601e, "UL", "Region Location Max Y1" },
{ 0x0018, 0x6020, "SL", "Reference Pixel X0" },
{ 0x0018, 0x6022, "SL", "Reference Pixel Y0" },
{ 0x0018, 0x6024, "US", "Physical Units X Direction" },
{ 0x0018, 0x6026, "US", "Physical Units Y Direction" },
{ 0x0018, 0x6028, "FD", "Reference Pixel Physical Value X" },
{ 0x0018, 0x602a, "US", "Reference Pixel Physical Value Y" },
{ 0x0018, 0x602c, "US", "Physical Delta X" },
{ 0x0018, 0x602e, "US", "Physical Delta Y" },
{ 0x0018, 0x6030, "UL", "Transducer Frequency" },
{ 0x0018, 0x6031, "CS", "Transducer Type" },
{ 0x0018, 0x6032, "UL", "Pulse Repetition Frequency" },
{ 0x0018, 0x6034, "FD", "Doppler Correction Angle" },
{ 0x0018, 0x6036, "FD", "Steering Angle" },
{ 0x0018, 0x6038, "UL", "Doppler Sample Volume X Position" },
{ 0x0018, 0x603a, "UL", "Doppler Sample Volume Y Position" },
{ 0x0018, 0x603c, "UL", "TM-Line Position X0" },
{ 0x0018, 0x603e, "UL", "TM-Line Position Y0" },
{ 0x0018, 0x6040, "UL", "TM-Line Position X1" },
{ 0x0018, 0x6042, "UL", "TM-Line Position Y1" },
{ 0x0018, 0x6044, "US", "Pixel Component Organization" },
{ 0x0018, 0x6046, "UL", "Pixel Component Mask" },
{ 0x0018, 0x6048, "UL", "Pixel Component Range Start" },
{ 0x0018, 0x604a, "UL", "Pixel Component Range Stop" },
{ 0x0018, 0x604c, "US", "Pixel Component Physical Units" },
{ 0x0018, 0x604e, "US", "Pixel Component Data Type" },
{ 0x0018, 0x6050, "UL", "Number of Table Break Points" },
{ 0x0018, 0x6052, "UL", "Table of X Break Points" },
{ 0x0018, 0x6054, "FD", "Table of Y Break Points" },
{ 0x0018, 0x6056, "UL", "Number of Table Entries" },
{ 0x0018, 0x6058, "UL", "Table of Pixel Values" },
{ 0x0018, 0x605a, "FL", "Table of Parameter Values" },
{ 0x0018, 0x7000, "CS", "Detector Conditions Nominal Flag" },
{ 0x0018, 0x7001, "DS", "Detector Temperature" },
{ 0x0018, 0x7004, "CS", "Detector Type" },
{ 0x0018, 0x7005, "CS", "Detector Configuration" },
{ 0x0018, 0x7006, "LT", "Detector Description" },
{ 0x0018, 0x7008, "LT", "Detector Mode" },
{ 0x0018, 0x700a, "SH", "Detector ID" },
{ 0x0018, 0x700c, "DA", "Date of Last Detector Calibration " },
{ 0x0018, 0x700e, "TM", "Time of Last Detector Calibration" },
{ 0x0018, 0x7010, "IS", "Exposures on Detector Since Last Calibration" },
{ 0x0018, 0x7011, "IS", "Exposures on Detector Since Manufactured" },
{ 0x0018, 0x7012, "DS", "Detector Time Since Last Exposure" },
{ 0x0018, 0x7014, "DS", "Detector Active Time" },
{ 0x0018, 0x7016, "DS", "Detector Activation Offset From Exposure" },
{ 0x0018, 0x701a, "DS", "Detector Binning" },
{ 0x0018, 0x7020, "DS", "Detector Element Physical Size" },
{ 0x0018, 0x7022, "DS", "Detector Element Spacing" },
{ 0x0018, 0x7024, "CS", "Detector Active Shape" },
{ 0x0018, 0x7026, "DS", "Detector Active Dimensions" },
{ 0x0018, 0x7028, "DS", "Detector Active Origin" },
{ 0x0018, 0x7030, "DS", "Field of View Origin" },
{ 0x0018, 0x7032, "DS", "Field of View Rotation" },
{ 0x0018, 0x7034, "CS", "Field of View Horizontal Flip" },
{ 0x0018, 0x7040, "LT", "Grid Absorbing Material" },
{ 0x0018, 0x7041, "LT", "Grid Spacing Material" },
{ 0x0018, 0x7042, "DS", "Grid Thickness" },
{ 0x0018, 0x7044, "DS", "Grid Pitch" },
{ 0x0018, 0x7046, "IS", "Grid Aspect Ratio" },
{ 0x0018, 0x7048, "DS", "Grid Period" },
{ 0x0018, 0x704c, "DS", "Grid Focal Distance" },
{ 0x0018, 0x7050, "LT", "Filter Material" },
{ 0x0018, 0x7052, "DS", "Filter Thickness Minimum" },
{ 0x0018, 0x7054, "DS", "Filter Thickness Maximum" },
{ 0x0018, 0x7060, "CS", "Exposure Control Mode" },
{ 0x0018, 0x7062, "LT", "Exposure Control Mode Description" },
{ 0x0018, 0x7064, "CS", "Exposure Status" },
{ 0x0018, 0x7065, "DS", "Phototimer Setting" },
{ 0x0019, 0x0000, "xs", "?" },
{ 0x0019, 0x0001, "xs", "?" },
{ 0x0019, 0x0002, "xs", "?" },
{ 0x0019, 0x0003, "xs", "?" },
{ 0x0019, 0x0004, "xs", "?" },
{ 0x0019, 0x0005, "xs", "?" },
{ 0x0019, 0x0006, "xs", "?" },
{ 0x0019, 0x0007, "xs", "?" },
{ 0x0019, 0x0008, "xs", "?" },
{ 0x0019, 0x0009, "xs", "?" },
{ 0x0019, 0x000a, "xs", "?" },
{ 0x0019, 0x000b, "DS", "?" },
{ 0x0019, 0x000c, "US", "?" },
{ 0x0019, 0x000d, "TM", "Time" },
{ 0x0019, 0x000e, "xs", "?" },
{ 0x0019, 0x000f, "DS", "Horizontal Frame Of Reference" },
{ 0x0019, 0x0010, "xs", "?" },
{ 0x0019, 0x0011, "xs", "?" },
{ 0x0019, 0x0012, "xs", "?" },
{ 0x0019, 0x0013, "xs", "?" },
{ 0x0019, 0x0014, "xs", "?" },
{ 0x0019, 0x0015, "xs", "?" },
{ 0x0019, 0x0016, "xs", "?" },
{ 0x0019, 0x0017, "xs", "?" },
{ 0x0019, 0x0018, "xs", "?" },
{ 0x0019, 0x0019, "xs", "?" },
{ 0x0019, 0x001a, "xs", "?" },
{ 0x0019, 0x001b, "xs", "?" },
{ 0x0019, 0x001c, "CS", "Dose" },
{ 0x0019, 0x001d, "IS", "Side Mark" },
{ 0x0019, 0x001e, "xs", "?" },
{ 0x0019, 0x001f, "DS", "Exposure Duration" },
{ 0x0019, 0x0020, "xs", "?" },
{ 0x0019, 0x0021, "xs", "?" },
{ 0x0019, 0x0022, "xs", "?" },
{ 0x0019, 0x0023, "xs", "?" },
{ 0x0019, 0x0024, "xs", "?" },
{ 0x0019, 0x0025, "xs", "?" },
{ 0x0019, 0x0026, "xs", "?" },
{ 0x0019, 0x0027, "xs", "?" },
{ 0x0019, 0x0028, "xs", "?" },
{ 0x0019, 0x0029, "IS", "?" },
{ 0x0019, 0x002a, "xs", "?" },
{ 0x0019, 0x002b, "DS", "Xray Off Position" },
{ 0x0019, 0x002c, "xs", "?" },
{ 0x0019, 0x002d, "US", "?" },
{ 0x0019, 0x002e, "xs", "?" },
{ 0x0019, 0x002f, "DS", "Trigger Frequency" },
{ 0x0019, 0x0030, "xs", "?" },
{ 0x0019, 0x0031, "xs", "?" },
{ 0x0019, 0x0032, "xs", "?" },
{ 0x0019, 0x0033, "UN", "ECG 2 Offset 2" },
{ 0x0019, 0x0034, "US", "?" },
{ 0x0019, 0x0036, "US", "?" },
{ 0x0019, 0x0038, "US", "?" },
{ 0x0019, 0x0039, "xs", "?" },
{ 0x0019, 0x003a, "xs", "?" },
{ 0x0019, 0x003b, "LT", "?" },
{ 0x0019, 0x003c, "xs", "?" },
{ 0x0019, 0x003e, "xs", "?" },
{ 0x0019, 0x003f, "UN", "?" },
{ 0x0019, 0x0040, "xs", "?" },
{ 0x0019, 0x0041, "xs", "?" },
{ 0x0019, 0x0042, "xs", "?" },
{ 0x0019, 0x0043, "xs", "?" },
{ 0x0019, 0x0044, "xs", "?" },
{ 0x0019, 0x0045, "xs", "?" },
{ 0x0019, 0x0046, "xs", "?" },
{ 0x0019, 0x0047, "xs", "?" },
{ 0x0019, 0x0048, "xs", "?" },
{ 0x0019, 0x0049, "US", "?" },
{ 0x0019, 0x004a, "xs", "?" },
{ 0x0019, 0x004b, "SL", "Data Size For Scan Data" },
{ 0x0019, 0x004c, "US", "?" },
{ 0x0019, 0x004e, "US", "?" },
{ 0x0019, 0x0050, "xs", "?" },
{ 0x0019, 0x0051, "xs", "?" },
{ 0x0019, 0x0052, "xs", "?" },
{ 0x0019, 0x0053, "LT", "Barcode" },
{ 0x0019, 0x0054, "xs", "?" },
{ 0x0019, 0x0055, "DS", "Receiver Reference Gain" },
{ 0x0019, 0x0056, "xs", "?" },
{ 0x0019, 0x0057, "SS", "CT Water Number" },
{ 0x0019, 0x0058, "xs", "?" },
{ 0x0019, 0x005a, "xs", "?" },
{ 0x0019, 0x005c, "xs", "?" },
{ 0x0019, 0x005d, "US", "?" },
{ 0x0019, 0x005e, "xs", "?" },
{ 0x0019, 0x005f, "SL", "Increment Between Channels" },
{ 0x0019, 0x0060, "xs", "?" },
{ 0x0019, 0x0061, "xs", "?" },
{ 0x0019, 0x0062, "xs", "?" },
{ 0x0019, 0x0063, "xs", "?" },
{ 0x0019, 0x0064, "xs", "?" },
{ 0x0019, 0x0065, "xs", "?" },
{ 0x0019, 0x0066, "xs", "?" },
{ 0x0019, 0x0067, "xs", "?" },
{ 0x0019, 0x0068, "xs", "?" },
{ 0x0019, 0x0069, "UL", "Convolution Mode" },
{ 0x0019, 0x006a, "xs", "?" },
{ 0x0019, 0x006b, "SS", "Field Of View In Detector Cells" },
{ 0x0019, 0x006c, "US", "?" },
{ 0x0019, 0x006e, "US", "?" },
{ 0x0019, 0x0070, "xs", "?" },
{ 0x0019, 0x0071, "xs", "?" },
{ 0x0019, 0x0072, "xs", "?" },
{ 0x0019, 0x0073, "xs", "?" },
{ 0x0019, 0x0074, "xs", "?" },
{ 0x0019, 0x0075, "xs", "?" },
{ 0x0019, 0x0076, "xs", "?" },
{ 0x0019, 0x0077, "US", "?" },
{ 0x0019, 0x0078, "US", "?" },
{ 0x0019, 0x007a, "US", "?" },
{ 0x0019, 0x007c, "US", "?" },
{ 0x0019, 0x007d, "DS", "Second Echo" },
{ 0x0019, 0x007e, "xs", "?" },
{ 0x0019, 0x007f, "DS", "Table Delta" },
{ 0x0019, 0x0080, "xs", "?" },
{ 0x0019, 0x0081, "xs", "?" },
{ 0x0019, 0x0082, "xs", "?" },
{ 0x0019, 0x0083, "xs", "?" },
{ 0x0019, 0x0084, "xs", "?" },
{ 0x0019, 0x0085, "xs", "?" },
{ 0x0019, 0x0086, "xs", "?" },
{ 0x0019, 0x0087, "xs", "?" },
{ 0x0019, 0x0088, "xs", "?" },
{ 0x0019, 0x008a, "xs", "?" },
{ 0x0019, 0x008b, "SS", "Actual Receive Gain Digital" },
{ 0x0019, 0x008c, "US", "?" },
{ 0x0019, 0x008d, "DS", "Delay After Trigger" },
{ 0x0019, 0x008e, "US", "?" },
{ 0x0019, 0x008f, "SS", "Swap Phase Frequency" },
{ 0x0019, 0x0090, "xs", "?" },
{ 0x0019, 0x0091, "xs", "?" },
{ 0x0019, 0x0092, "xs", "?" },
{ 0x0019, 0x0093, "xs", "?" },
{ 0x0019, 0x0094, "xs", "?" },
{ 0x0019, 0x0095, "SS", "Analog Receiver Gain" },
{ 0x0019, 0x0096, "xs", "?" },
{ 0x0019, 0x0097, "xs", "?" },
{ 0x0019, 0x0098, "xs", "?" },
{ 0x0019, 0x0099, "US", "?" },
{ 0x0019, 0x009a, "US", "?" },
{ 0x0019, 0x009b, "SS", "Pulse Sequence Mode" },
{ 0x0019, 0x009c, "xs", "?" },
{ 0x0019, 0x009d, "DT", "Pulse Sequence Date" },
{ 0x0019, 0x009e, "xs", "?" },
{ 0x0019, 0x009f, "xs", "?" },
{ 0x0019, 0x00a0, "xs", "?" },
{ 0x0019, 0x00a1, "xs", "?" },
{ 0x0019, 0x00a2, "xs", "?" },
{ 0x0019, 0x00a3, "xs", "?" },
{ 0x0019, 0x00a4, "xs", "?" },
{ 0x0019, 0x00a5, "xs", "?" },
{ 0x0019, 0x00a6, "xs", "?" },
{ 0x0019, 0x00a7, "xs", "?" },
{ 0x0019, 0x00a8, "xs", "?" },
{ 0x0019, 0x00a9, "xs", "?" },
{ 0x0019, 0x00aa, "xs", "?" },
{ 0x0019, 0x00ab, "xs", "?" },
{ 0x0019, 0x00ac, "xs", "?" },
{ 0x0019, 0x00ad, "xs", "?" },
{ 0x0019, 0x00ae, "xs", "?" },
{ 0x0019, 0x00af, "xs", "?" },
{ 0x0019, 0x00b0, "xs", "?" },
{ 0x0019, 0x00b1, "xs", "?" },
{ 0x0019, 0x00b2, "xs", "?" },
{ 0x0019, 0x00b3, "xs", "?" },
{ 0x0019, 0x00b4, "xs", "?" },
{ 0x0019, 0x00b5, "xs", "?" },
{ 0x0019, 0x00b6, "DS", "User Data" },
{ 0x0019, 0x00b7, "DS", "User Data" },
{ 0x0019, 0x00b8, "DS", "User Data" },
{ 0x0019, 0x00b9, "DS", "User Data" },
{ 0x0019, 0x00ba, "DS", "User Data" },
{ 0x0019, 0x00bb, "DS", "User Data" },
{ 0x0019, 0x00bc, "DS", "User Data" },
{ 0x0019, 0x00bd, "DS", "User Data" },
{ 0x0019, 0x00be, "DS", "Projection Angle" },
{ 0x0019, 0x00c0, "xs", "?" },
{ 0x0019, 0x00c1, "xs", "?" },
{ 0x0019, 0x00c2, "xs", "?" },
{ 0x0019, 0x00c3, "xs", "?" },
{ 0x0019, 0x00c4, "xs", "?" },
{ 0x0019, 0x00c5, "xs", "?" },
{ 0x0019, 0x00c6, "SS", "SAT Location H" },
{ 0x0019, 0x00c7, "SS", "SAT Location F" },
{ 0x0019, 0x00c8, "SS", "SAT Thickness R L" },
{ 0x0019, 0x00c9, "SS", "SAT Thickness A P" },
{ 0x0019, 0x00ca, "SS", "SAT Thickness H F" },
{ 0x0019, 0x00cb, "xs", "?" },
{ 0x0019, 0x00cc, "xs", "?" },
{ 0x0019, 0x00cd, "SS", "Thickness Disclaimer" },
{ 0x0019, 0x00ce, "SS", "Prescan Type" },
{ 0x0019, 0x00cf, "SS", "Prescan Status" },
{ 0x0019, 0x00d0, "SH", "Raw Data Type" },
{ 0x0019, 0x00d1, "DS", "Flow Sensitivity" },
{ 0x0019, 0x00d2, "xs", "?" },
{ 0x0019, 0x00d3, "xs", "?" },
{ 0x0019, 0x00d4, "xs", "?" },
{ 0x0019, 0x00d5, "xs", "?" },
{ 0x0019, 0x00d6, "xs", "?" },
{ 0x0019, 0x00d7, "xs", "?" },
{ 0x0019, 0x00d8, "xs", "?" },
{ 0x0019, 0x00d9, "xs", "?" },
{ 0x0019, 0x00da, "xs", "?" },
{ 0x0019, 0x00db, "DS", "Back Projector Coefficient" },
{ 0x0019, 0x00dc, "SS", "Primary Speed Correction Used" },
{ 0x0019, 0x00dd, "SS", "Overrange Correction Used" },
{ 0x0019, 0x00de, "DS", "Dynamic Z Alpha Value" },
{ 0x0019, 0x00df, "DS", "User Data" },
{ 0x0019, 0x00e0, "DS", "User Data" },
{ 0x0019, 0x00e1, "xs", "?" },
{ 0x0019, 0x00e2, "xs", "?" },
{ 0x0019, 0x00e3, "xs", "?" },
{ 0x0019, 0x00e4, "LT", "?" },
{ 0x0019, 0x00e5, "IS", "?" },
{ 0x0019, 0x00e6, "US", "?" },
{ 0x0019, 0x00e8, "DS", "?" },
{ 0x0019, 0x00e9, "DS", "?" },
{ 0x0019, 0x00eb, "DS", "?" },
{ 0x0019, 0x00ec, "US", "?" },
{ 0x0019, 0x00f0, "xs", "?" },
{ 0x0019, 0x00f1, "xs", "?" },
{ 0x0019, 0x00f2, "xs", "?" },
{ 0x0019, 0x00f3, "xs", "?" },
{ 0x0019, 0x00f4, "LT", "?" },
{ 0x0019, 0x00f9, "DS", "Transmission Gain" },
{ 0x0019, 0x1015, "UN", "?" },
{ 0x0020, 0x0000, "UL", "Relationship Group Length" },
{ 0x0020, 0x000d, "UI", "Study Instance UID" },
{ 0x0020, 0x000e, "UI", "Series Instance UID" },
{ 0x0020, 0x0010, "SH", "Study ID" },
{ 0x0020, 0x0011, "IS", "Series Number" },
{ 0x0020, 0x0012, "IS", "Acquisition Number" },
{ 0x0020, 0x0013, "IS", "Instance (formerly Image) Number" },
{ 0x0020, 0x0014, "IS", "Isotope Number" },
{ 0x0020, 0x0015, "IS", "Phase Number" },
{ 0x0020, 0x0016, "IS", "Interval Number" },
{ 0x0020, 0x0017, "IS", "Time Slot Number" },
{ 0x0020, 0x0018, "IS", "Angle Number" },
{ 0x0020, 0x0020, "CS", "Patient Orientation" },
{ 0x0020, 0x0022, "IS", "Overlay Number" },
{ 0x0020, 0x0024, "IS", "Curve Number" },
{ 0x0020, 0x0026, "IS", "LUT Number" },
{ 0x0020, 0x0030, "DS", "Image Position" },
{ 0x0020, 0x0032, "DS", "Image Position (Patient)" },
{ 0x0020, 0x0035, "DS", "Image Orientation" },
{ 0x0020, 0x0037, "DS", "Image Orientation (Patient)" },
{ 0x0020, 0x0050, "DS", "Location" },
{ 0x0020, 0x0052, "UI", "Frame of Reference UID" },
{ 0x0020, 0x0060, "CS", "Laterality" },
{ 0x0020, 0x0062, "CS", "Image Laterality" },
{ 0x0020, 0x0070, "LT", "Image Geometry Type" },
{ 0x0020, 0x0080, "LO", "Masking Image" },
{ 0x0020, 0x0100, "IS", "Temporal Position Identifier" },
{ 0x0020, 0x0105, "IS", "Number of Temporal Positions" },
{ 0x0020, 0x0110, "DS", "Temporal Resolution" },
{ 0x0020, 0x1000, "IS", "Series in Study" },
{ 0x0020, 0x1001, "DS", "Acquisitions in Series" },
{ 0x0020, 0x1002, "IS", "Images in Acquisition" },
{ 0x0020, 0x1003, "IS", "Images in Series" },
{ 0x0020, 0x1004, "IS", "Acquisitions in Study" },
{ 0x0020, 0x1005, "IS", "Images in Study" },
{ 0x0020, 0x1020, "LO", "Reference" },
{ 0x0020, 0x1040, "LO", "Position Reference Indicator" },
{ 0x0020, 0x1041, "DS", "Slice Location" },
{ 0x0020, 0x1070, "IS", "Other Study Numbers" },
{ 0x0020, 0x1200, "IS", "Number of Patient Related Studies" },
{ 0x0020, 0x1202, "IS", "Number of Patient Related Series" },
{ 0x0020, 0x1204, "IS", "Number of Patient Related Images" },
{ 0x0020, 0x1206, "IS", "Number of Study Related Series" },
{ 0x0020, 0x1208, "IS", "Number of Study Related Series" },
{ 0x0020, 0x3100, "LO", "Source Image IDs" },
{ 0x0020, 0x3401, "LO", "Modifying Device ID" },
{ 0x0020, 0x3402, "LO", "Modified Image ID" },
{ 0x0020, 0x3403, "xs", "Modified Image Date" },
{ 0x0020, 0x3404, "LO", "Modifying Device Manufacturer" },
{ 0x0020, 0x3405, "xs", "Modified Image Time" },
{ 0x0020, 0x3406, "xs", "Modified Image Description" },
{ 0x0020, 0x4000, "LT", "Image Comments" },
{ 0x0020, 0x5000, "AT", "Original Image Identification" },
{ 0x0020, 0x5002, "LO", "Original Image Identification Nomenclature" },
{ 0x0021, 0x0000, "xs", "?" },
{ 0x0021, 0x0001, "xs", "?" },
{ 0x0021, 0x0002, "xs", "?" },
{ 0x0021, 0x0003, "xs", "?" },
{ 0x0021, 0x0004, "DS", "VOI Position" },
{ 0x0021, 0x0005, "xs", "?" },
{ 0x0021, 0x0006, "IS", "CSI Matrix Size Original" },
{ 0x0021, 0x0007, "xs", "?" },
{ 0x0021, 0x0008, "DS", "Spatial Grid Shift" },
{ 0x0021, 0x0009, "DS", "Signal Limits Minimum" },
{ 0x0021, 0x0010, "xs", "?" },
{ 0x0021, 0x0011, "xs", "?" },
{ 0x0021, 0x0012, "xs", "?" },
{ 0x0021, 0x0013, "xs", "?" },
{ 0x0021, 0x0014, "xs", "?" },
{ 0x0021, 0x0015, "xs", "?" },
{ 0x0021, 0x0016, "xs", "?" },
{ 0x0021, 0x0017, "DS", "EPI Operation Mode Flag" },
{ 0x0021, 0x0018, "xs", "?" },
{ 0x0021, 0x0019, "xs", "?" },
{ 0x0021, 0x0020, "xs", "?" },
{ 0x0021, 0x0021, "xs", "?" },
{ 0x0021, 0x0022, "xs", "?" },
{ 0x0021, 0x0024, "xs", "?" },
{ 0x0021, 0x0025, "US", "?" },
{ 0x0021, 0x0026, "IS", "Image Pixel Offset" },
{ 0x0021, 0x0030, "xs", "?" },
{ 0x0021, 0x0031, "xs", "?" },
{ 0x0021, 0x0032, "xs", "?" },
{ 0x0021, 0x0034, "xs", "?" },
{ 0x0021, 0x0035, "SS", "Series From Which Prescribed" },
{ 0x0021, 0x0036, "xs", "?" },
{ 0x0021, 0x0037, "SS", "Screen Format" },
{ 0x0021, 0x0039, "DS", "Slab Thickness" },
{ 0x0021, 0x0040, "xs", "?" },
{ 0x0021, 0x0041, "xs", "?" },
{ 0x0021, 0x0042, "xs", "?" },
{ 0x0021, 0x0043, "xs", "?" },
{ 0x0021, 0x0044, "xs", "?" },
{ 0x0021, 0x0045, "xs", "?" },
{ 0x0021, 0x0046, "xs", "?" },
{ 0x0021, 0x0047, "xs", "?" },
{ 0x0021, 0x0048, "xs", "?" },
{ 0x0021, 0x0049, "xs", "?" },
{ 0x0021, 0x004a, "xs", "?" },
{ 0x0021, 0x004e, "US", "?" },
{ 0x0021, 0x004f, "xs", "?" },
{ 0x0021, 0x0050, "xs", "?" },
{ 0x0021, 0x0051, "xs", "?" },
{ 0x0021, 0x0052, "xs", "?" },
{ 0x0021, 0x0053, "xs", "?" },
{ 0x0021, 0x0054, "xs", "?" },
{ 0x0021, 0x0055, "xs", "?" },
{ 0x0021, 0x0056, "xs", "?" },
{ 0x0021, 0x0057, "xs", "?" },
{ 0x0021, 0x0058, "xs", "?" },
{ 0x0021, 0x0059, "xs", "?" },
{ 0x0021, 0x005a, "SL", "Integer Slop" },
{ 0x0021, 0x005b, "DS", "Float Slop" },
{ 0x0021, 0x005c, "DS", "Float Slop" },
{ 0x0021, 0x005d, "DS", "Float Slop" },
{ 0x0021, 0x005e, "DS", "Float Slop" },
{ 0x0021, 0x005f, "DS", "Float Slop" },
{ 0x0021, 0x0060, "xs", "?" },
{ 0x0021, 0x0061, "DS", "Image Normal" },
{ 0x0021, 0x0062, "IS", "Reference Type Code" },
{ 0x0021, 0x0063, "DS", "Image Distance" },
{ 0x0021, 0x0065, "US", "Image Positioning History Mask" },
{ 0x0021, 0x006a, "DS", "Image Row" },
{ 0x0021, 0x006b, "DS", "Image Column" },
{ 0x0021, 0x0070, "xs", "?" },
{ 0x0021, 0x0071, "xs", "?" },
{ 0x0021, 0x0072, "xs", "?" },
{ 0x0021, 0x0073, "DS", "Second Repetition Time" },
{ 0x0021, 0x0075, "DS", "Light Brightness" },
{ 0x0021, 0x0076, "DS", "Light Contrast" },
{ 0x0021, 0x007a, "IS", "Overlay Threshold" },
{ 0x0021, 0x007b, "IS", "Surface Threshold" },
{ 0x0021, 0x007c, "IS", "Grey Scale Threshold" },
{ 0x0021, 0x0080, "xs", "?" },
{ 0x0021, 0x0081, "DS", "Auto Window Level Alpha" },
{ 0x0021, 0x0082, "xs", "?" },
{ 0x0021, 0x0083, "DS", "Auto Window Level Window" },
{ 0x0021, 0x0084, "DS", "Auto Window Level Level" },
{ 0x0021, 0x0090, "xs", "?" },
{ 0x0021, 0x0091, "xs", "?" },
{ 0x0021, 0x0092, "xs", "?" },
{ 0x0021, 0x0093, "xs", "?" },
{ 0x0021, 0x0094, "DS", "EPI Change Value of X Component" },
{ 0x0021, 0x0095, "DS", "EPI Change Value of Y Component" },
{ 0x0021, 0x0096, "DS", "EPI Change Value of Z Component" },
{ 0x0021, 0x00a0, "xs", "?" },
{ 0x0021, 0x00a1, "DS", "?" },
{ 0x0021, 0x00a2, "xs", "?" },
{ 0x0021, 0x00a3, "LT", "?" },
{ 0x0021, 0x00a4, "LT", "?" },
{ 0x0021, 0x00a7, "LT", "?" },
{ 0x0021, 0x00b0, "IS", "?" },
{ 0x0021, 0x00c0, "IS", "?" },
{ 0x0023, 0x0000, "xs", "?" },
{ 0x0023, 0x0001, "SL", "Number Of Series In Study" },
{ 0x0023, 0x0002, "SL", "Number Of Unarchived Series" },
{ 0x0023, 0x0010, "xs", "?" },
{ 0x0023, 0x0020, "xs", "?" },
{ 0x0023, 0x0030, "xs", "?" },
{ 0x0023, 0x0040, "xs", "?" },
{ 0x0023, 0x0050, "xs", "?" },
{ 0x0023, 0x0060, "xs", "?" },
{ 0x0023, 0x0070, "xs", "?" },
{ 0x0023, 0x0074, "SL", "Number Of Updates To Info" },
{ 0x0023, 0x007d, "SS", "Indicates If Study Has Complete Info" },
{ 0x0023, 0x0080, "xs", "?" },
{ 0x0023, 0x0090, "xs", "?" },
{ 0x0023, 0x00ff, "US", "?" },
{ 0x0025, 0x0000, "UL", "Group Length" },
{ 0x0025, 0x0006, "SS", "Last Pulse Sequence Used" },
{ 0x0025, 0x0007, "SL", "Images In Series" },
{ 0x0025, 0x0010, "SS", "Landmark Counter" },
{ 0x0025, 0x0011, "SS", "Number Of Acquisitions" },
{ 0x0025, 0x0014, "SL", "Indicates Number Of Updates To Info" },
{ 0x0025, 0x0017, "SL", "Series Complete Flag" },
{ 0x0025, 0x0018, "SL", "Number Of Images Archived" },
{ 0x0025, 0x0019, "SL", "Last Image Number Used" },
{ 0x0025, 0x001a, "SH", "Primary Receiver Suite And Host" },
{ 0x0027, 0x0000, "US", "?" },
{ 0x0027, 0x0006, "SL", "Image Archive Flag" },
{ 0x0027, 0x0010, "SS", "Scout Type" },
{ 0x0027, 0x0011, "UN", "?" },
{ 0x0027, 0x0012, "IS", "?" },
{ 0x0027, 0x0013, "IS", "?" },
{ 0x0027, 0x0014, "IS", "?" },
{ 0x0027, 0x0015, "IS", "?" },
{ 0x0027, 0x0016, "LT", "?" },
{ 0x0027, 0x001c, "SL", "Vma Mamp" },
{ 0x0027, 0x001d, "SS", "Vma Phase" },
{ 0x0027, 0x001e, "SL", "Vma Mod" },
{ 0x0027, 0x001f, "SL", "Vma Clip" },
{ 0x0027, 0x0020, "SS", "Smart Scan On Off Flag" },
{ 0x0027, 0x0030, "SH", "Foreign Image Revision" },
{ 0x0027, 0x0031, "SS", "Imaging Mode" },
{ 0x0027, 0x0032, "SS", "Pulse Sequence" },
{ 0x0027, 0x0033, "SL", "Imaging Options" },
{ 0x0027, 0x0035, "SS", "Plane Type" },
{ 0x0027, 0x0036, "SL", "Oblique Plane" },
{ 0x0027, 0x0040, "SH", "RAS Letter Of Image Location" },
{ 0x0027, 0x0041, "FL", "Image Location" },
{ 0x0027, 0x0042, "FL", "Center R Coord Of Plane Image" },
{ 0x0027, 0x0043, "FL", "Center A Coord Of Plane Image" },
{ 0x0027, 0x0044, "FL", "Center S Coord Of Plane Image" },
{ 0x0027, 0x0045, "FL", "Normal R Coord" },
{ 0x0027, 0x0046, "FL", "Normal A Coord" },
{ 0x0027, 0x0047, "FL", "Normal S Coord" },
{ 0x0027, 0x0048, "FL", "R Coord Of Top Right Corner" },
{ 0x0027, 0x0049, "FL", "A Coord Of Top Right Corner" },
{ 0x0027, 0x004a, "FL", "S Coord Of Top Right Corner" },
{ 0x0027, 0x004b, "FL", "R Coord Of Bottom Right Corner" },
{ 0x0027, 0x004c, "FL", "A Coord Of Bottom Right Corner" },
{ 0x0027, 0x004d, "FL", "S Coord Of Bottom Right Corner" },
{ 0x0027, 0x0050, "FL", "Table Start Location" },
{ 0x0027, 0x0051, "FL", "Table End Location" },
{ 0x0027, 0x0052, "SH", "RAS Letter For Side Of Image" },
{ 0x0027, 0x0053, "SH", "RAS Letter For Anterior Posterior" },
{ 0x0027, 0x0054, "SH", "RAS Letter For Scout Start Loc" },
{ 0x0027, 0x0055, "SH", "RAS Letter For Scout End Loc" },
{ 0x0027, 0x0060, "FL", "Image Dimension X" },
{ 0x0027, 0x0061, "FL", "Image Dimension Y" },
{ 0x0027, 0x0062, "FL", "Number Of Excitations" },
{ 0x0028, 0x0000, "UL", "Image Presentation Group Length" },
{ 0x0028, 0x0002, "US", "Samples per Pixel" },
{ 0x0028, 0x0004, "CS", "Photometric Interpretation" },
{ 0x0028, 0x0005, "US", "Image Dimensions" },
{ 0x0028, 0x0006, "US", "Planar Configuration" },
{ 0x0028, 0x0008, "IS", "Number of Frames" },
{ 0x0028, 0x0009, "AT", "Frame Increment Pointer" },
{ 0x0028, 0x0010, "US", "Rows" },
{ 0x0028, 0x0011, "US", "Columns" },
{ 0x0028, 0x0012, "US", "Planes" },
{ 0x0028, 0x0014, "US", "Ultrasound Color Data Present" },
{ 0x0028, 0x0030, "DS", "Pixel Spacing" },
{ 0x0028, 0x0031, "DS", "Zoom Factor" },
{ 0x0028, 0x0032, "DS", "Zoom Center" },
{ 0x0028, 0x0034, "IS", "Pixel Aspect Ratio" },
{ 0x0028, 0x0040, "LO", "Image Format" },
{ 0x0028, 0x0050, "LT", "Manipulated Image" },
{ 0x0028, 0x0051, "CS", "Corrected Image" },
{ 0x0028, 0x005f, "LO", "Compression Recognition Code" },
{ 0x0028, 0x0060, "LO", "Compression Code" },
{ 0x0028, 0x0061, "SH", "Compression Originator" },
{ 0x0028, 0x0062, "SH", "Compression Label" },
{ 0x0028, 0x0063, "SH", "Compression Description" },
{ 0x0028, 0x0065, "LO", "Compression Sequence" },
{ 0x0028, 0x0066, "AT", "Compression Step Pointers" },
{ 0x0028, 0x0068, "US", "Repeat Interval" },
{ 0x0028, 0x0069, "US", "Bits Grouped" },
{ 0x0028, 0x0070, "US", "Perimeter Table" },
{ 0x0028, 0x0071, "xs", "Perimeter Value" },
{ 0x0028, 0x0080, "US", "Predictor Rows" },
{ 0x0028, 0x0081, "US", "Predictor Columns" },
{ 0x0028, 0x0082, "US", "Predictor Constants" },
{ 0x0028, 0x0090, "LO", "Blocked Pixels" },
{ 0x0028, 0x0091, "US", "Block Rows" },
{ 0x0028, 0x0092, "US", "Block Columns" },
{ 0x0028, 0x0093, "US", "Row Overlap" },
{ 0x0028, 0x0094, "US", "Column Overlap" },
{ 0x0028, 0x0100, "US", "Bits Allocated" },
{ 0x0028, 0x0101, "US", "Bits Stored" },
{ 0x0028, 0x0102, "US", "High Bit" },
{ 0x0028, 0x0103, "US", "Pixel Representation" },
{ 0x0028, 0x0104, "xs", "Smallest Valid Pixel Value" },
{ 0x0028, 0x0105, "xs", "Largest Valid Pixel Value" },
{ 0x0028, 0x0106, "xs", "Smallest Image Pixel Value" },
{ 0x0028, 0x0107, "xs", "Largest Image Pixel Value" },
{ 0x0028, 0x0108, "xs", "Smallest Pixel Value in Series" },
{ 0x0028, 0x0109, "xs", "Largest Pixel Value in Series" },
{ 0x0028, 0x0110, "xs", "Smallest Pixel Value in Plane" },
{ 0x0028, 0x0111, "xs", "Largest Pixel Value in Plane" },
{ 0x0028, 0x0120, "xs", "Pixel Padding Value" },
{ 0x0028, 0x0200, "xs", "Image Location" },
{ 0x0028, 0x0300, "CS", "Quality Control Image" },
{ 0x0028, 0x0301, "CS", "Burned In Annotation" },
{ 0x0028, 0x0400, "xs", "?" },
{ 0x0028, 0x0401, "xs", "?" },
{ 0x0028, 0x0402, "xs", "?" },
{ 0x0028, 0x0403, "xs", "?" },
{ 0x0028, 0x0404, "AT", "Details of Coefficients" },
{ 0x0028, 0x0700, "LO", "DCT Label" },
{ 0x0028, 0x0701, "LO", "Data Block Description" },
{ 0x0028, 0x0702, "AT", "Data Block" },
{ 0x0028, 0x0710, "US", "Normalization Factor Format" },
{ 0x0028, 0x0720, "US", "Zonal Map Number Format" },
{ 0x0028, 0x0721, "AT", "Zonal Map Location" },
{ 0x0028, 0x0722, "US", "Zonal Map Format" },
{ 0x0028, 0x0730, "US", "Adaptive Map Format" },
{ 0x0028, 0x0740, "US", "Code Number Format" },
{ 0x0028, 0x0800, "LO", "Code Label" },
{ 0x0028, 0x0802, "US", "Number of Tables" },
{ 0x0028, 0x0803, "AT", "Code Table Location" },
{ 0x0028, 0x0804, "US", "Bits For Code Word" },
{ 0x0028, 0x0808, "AT", "Image Data Location" },
{ 0x0028, 0x1040, "CS", "Pixel Intensity Relationship" },
{ 0x0028, 0x1041, "SS", "Pixel Intensity Relationship Sign" },
{ 0x0028, 0x1050, "DS", "Window Center" },
{ 0x0028, 0x1051, "DS", "Window Width" },
{ 0x0028, 0x1052, "DS", "Rescale Intercept" },
{ 0x0028, 0x1053, "DS", "Rescale Slope" },
{ 0x0028, 0x1054, "LO", "Rescale Type" },
{ 0x0028, 0x1055, "LO", "Window Center & Width Explanation" },
{ 0x0028, 0x1080, "LO", "Gray Scale" },
{ 0x0028, 0x1090, "CS", "Recommended Viewing Mode" },
{ 0x0028, 0x1100, "xs", "Gray Lookup Table Descriptor" },
{ 0x0028, 0x1101, "xs", "Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1102, "xs", "Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1103, "xs", "Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1111, "OW", "Large Red Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1112, "OW", "Large Green Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1113, "OW", "Large Blue Palette Color Lookup Table Descriptor" },
{ 0x0028, 0x1199, "UI", "Palette Color Lookup Table UID" },
{ 0x0028, 0x1200, "xs", "Gray Lookup Table Data" },
{ 0x0028, 0x1201, "OW", "Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1202, "OW", "Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1203, "OW", "Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1211, "OW", "Large Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1212, "OW", "Large Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1213, "OW", "Large Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1214, "UI", "Large Palette Color Lookup Table UID" },
{ 0x0028, 0x1221, "OW", "Segmented Red Palette Color Lookup Table Data" },
{ 0x0028, 0x1222, "OW", "Segmented Green Palette Color Lookup Table Data" },
{ 0x0028, 0x1223, "OW", "Segmented Blue Palette Color Lookup Table Data" },
{ 0x0028, 0x1300, "CS", "Implant Present" },
{ 0x0028, 0x2110, "CS", "Lossy Image Compression" },
{ 0x0028, 0x2112, "DS", "Lossy Image Compression Ratio" },
{ 0x0028, 0x3000, "SQ", "Modality LUT Sequence" },
{ 0x0028, 0x3002, "US", "LUT Descriptor" },
{ 0x0028, 0x3003, "LO", "LUT Explanation" },
{ 0x0028, 0x3004, "LO", "Modality LUT Type" },
{ 0x0028, 0x3006, "US", "LUT Data" },
{ 0x0028, 0x3010, "xs", "VOI LUT Sequence" },
{ 0x0028, 0x4000, "LT", "Image Presentation Comments" },
{ 0x0028, 0x5000, "SQ", "Biplane Acquisition Sequence" },
{ 0x0028, 0x6010, "US", "Representative Frame Number" },
{ 0x0028, 0x6020, "US", "Frame Numbers of Interest" },
{ 0x0028, 0x6022, "LO", "Frame of Interest Description" },
{ 0x0028, 0x6030, "US", "Mask Pointer" },
{ 0x0028, 0x6040, "US", "R Wave Pointer" },
{ 0x0028, 0x6100, "SQ", "Mask Subtraction Sequence" },
{ 0x0028, 0x6101, "CS", "Mask Operation" },
{ 0x0028, 0x6102, "US", "Applicable Frame Range" },
{ 0x0028, 0x6110, "US", "Mask Frame Numbers" },
{ 0x0028, 0x6112, "US", "Contrast Frame Averaging" },
{ 0x0028, 0x6114, "FL", "Mask Sub-Pixel Shift" },
{ 0x0028, 0x6120, "SS", "TID Offset" },
{ 0x0028, 0x6190, "ST", "Mask Operation Explanation" },
{ 0x0029, 0x0000, "xs", "?" },
{ 0x0029, 0x0001, "xs", "?" },
{ 0x0029, 0x0002, "xs", "?" },
{ 0x0029, 0x0003, "xs", "?" },
{ 0x0029, 0x0004, "xs", "?" },
{ 0x0029, 0x0005, "xs", "?" },
{ 0x0029, 0x0006, "xs", "?" },
{ 0x0029, 0x0007, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0008, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x0009, "SH", "Lower Range Of Pixels" },
{ 0x0029, 0x000a, "SS", "Lower Range Of Pixels" },
{ 0x0029, 0x000c, "xs", "?" },
{ 0x0029, 0x000e, "CS", "Zoom Enable Status" },
{ 0x0029, 0x000f, "CS", "Zoom Select Status" },
{ 0x0029, 0x0010, "xs", "?" },
{ 0x0029, 0x0011, "xs", "?" },
{ 0x0029, 0x0013, "LT", "?" },
{ 0x0029, 0x0015, "xs", "?" },
{ 0x0029, 0x0016, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0017, "SL", "Lower Range Of Pixels" },
{ 0x0029, 0x0018, "SL", "Upper Range Of Pixels" },
{ 0x0029, 0x001a, "SL", "Length Of Total Info In Bytes" },
{ 0x0029, 0x001e, "xs", "?" },
{ 0x0029, 0x001f, "xs", "?" },
{ 0x0029, 0x0020, "xs", "?" },
{ 0x0029, 0x0022, "IS", "Pixel Quality Value" },
{ 0x0029, 0x0025, "LT", "Processed Pixel Data Quality" },
{ 0x0029, 0x0026, "SS", "Version Of Info Structure" },
{ 0x0029, 0x0030, "xs", "?" },
{ 0x0029, 0x0031, "xs", "?" },
{ 0x0029, 0x0032, "xs", "?" },
{ 0x0029, 0x0033, "xs", "?" },
{ 0x0029, 0x0034, "xs", "?" },
{ 0x0029, 0x0035, "SL", "Advantage Comp Underflow" },
{ 0x0029, 0x0038, "US", "?" },
{ 0x0029, 0x0040, "xs", "?" },
{ 0x0029, 0x0041, "DS", "Magnifying Glass Rectangle" },
{ 0x0029, 0x0043, "DS", "Magnifying Glass Factor" },
{ 0x0029, 0x0044, "US", "Magnifying Glass Function" },
{ 0x0029, 0x004e, "CS", "Magnifying Glass Enable Status" },
{ 0x0029, 0x004f, "CS", "Magnifying Glass Select Status" },
{ 0x0029, 0x0050, "xs", "?" },
{ 0x0029, 0x0051, "LT", "Exposure Code" },
{ 0x0029, 0x0052, "LT", "Sort Code" },
{ 0x0029, 0x0053, "LT", "?" },
{ 0x0029, 0x0060, "xs", "?" },
{ 0x0029, 0x0061, "xs", "?" },
{ 0x0029, 0x0067, "LT", "?" },
{ 0x0029, 0x0070, "xs", "?" },
{ 0x0029, 0x0071, "xs", "?" },
{ 0x0029, 0x0072, "xs", "?" },
{ 0x0029, 0x0077, "CS", "Window Select Status" },
{ 0x0029, 0x0078, "LT", "ECG Display Printing ID" },
{ 0x0029, 0x0079, "CS", "ECG Display Printing" },
{ 0x0029, 0x007e, "CS", "ECG Display Printing Enable Status" },
{ 0x0029, 0x007f, "CS", "ECG Display Printing Select Status" },
{ 0x0029, 0x0080, "xs", "?" },
{ 0x0029, 0x0081, "xs", "?" },
{ 0x0029, 0x0082, "IS", "View Zoom" },
{ 0x0029, 0x0083, "IS", "View Transform" },
{ 0x0029, 0x008e, "CS", "Physiological Display Enable Status" },
{ 0x0029, 0x008f, "CS", "Physiological Display Select Status" },
{ 0x0029, 0x0090, "IS", "?" },
{ 0x0029, 0x0099, "LT", "Shutter Type" },
{ 0x0029, 0x00a0, "US", "Rows of Rectangular Shutter" },
{ 0x0029, 0x00a1, "US", "Columns of Rectangular Shutter" },
{ 0x0029, 0x00a2, "US", "Origin of Rectangular Shutter" },
{ 0x0029, 0x00b0, "US", "Radius of Circular Shutter" },
{ 0x0029, 0x00b2, "US", "Origin of Circular Shutter" },
{ 0x0029, 0x00c0, "LT", "Functional Shutter ID" },
{ 0x0029, 0x00c1, "xs", "?" },
{ 0x0029, 0x00c3, "IS", "Scan Resolution" },
{ 0x0029, 0x00c4, "IS", "Field of View" },
{ 0x0029, 0x00c5, "LT", "Field Of Shutter Rectangle" },
{ 0x0029, 0x00ce, "CS", "Shutter Enable Status" },
{ 0x0029, 0x00cf, "CS", "Shutter Select Status" },
{ 0x0029, 0x00d0, "IS", "?" },
{ 0x0029, 0x00d1, "IS", "?" },
{ 0x0029, 0x00d5, "LT", "Slice Thickness" },
{ 0x0031, 0x0010, "LT", "Request UID" },
{ 0x0031, 0x0012, "LT", "Examination Reason" },
{ 0x0031, 0x0030, "DA", "Requested Date" },
{ 0x0031, 0x0032, "TM", "Worklist Request Start Time" },
{ 0x0031, 0x0033, "TM", "Worklist Request End Time" },
{ 0x0031, 0x0045, "LT", "Requesting Physician" },
{ 0x0031, 0x004a, "TM", "Requested Time" },
{ 0x0031, 0x0050, "LT", "Requested Physician" },
{ 0x0031, 0x0080, "LT", "Requested Location" },
{ 0x0032, 0x0000, "UL", "Study Group Length" },
{ 0x0032, 0x000a, "CS", "Study Status ID" },
{ 0x0032, 0x000c, "CS", "Study Priority ID" },
{ 0x0032, 0x0012, "LO", "Study ID Issuer" },
{ 0x0032, 0x0032, "DA", "Study Verified Date" },
{ 0x0032, 0x0033, "TM", "Study Verified Time" },
{ 0x0032, 0x0034, "DA", "Study Read Date" },
{ 0x0032, 0x0035, "TM", "Study Read Time" },
{ 0x0032, 0x1000, "DA", "Scheduled Study Start Date" },
{ 0x0032, 0x1001, "TM", "Scheduled Study Start Time" },
{ 0x0032, 0x1010, "DA", "Scheduled Study Stop Date" },
{ 0x0032, 0x1011, "TM", "Scheduled Study Stop Time" },
{ 0x0032, 0x1020, "LO", "Scheduled Study Location" },
{ 0x0032, 0x1021, "AE", "Scheduled Study Location AE Title(s)" },
{ 0x0032, 0x1030, "LO", "Reason for Study" },
{ 0x0032, 0x1032, "PN", "Requesting Physician" },
{ 0x0032, 0x1033, "LO", "Requesting Service" },
{ 0x0032, 0x1040, "DA", "Study Arrival Date" },
{ 0x0032, 0x1041, "TM", "Study Arrival Time" },
{ 0x0032, 0x1050, "DA", "Study Completion Date" },
{ 0x0032, 0x1051, "TM", "Study Completion Time" },
{ 0x0032, 0x1055, "CS", "Study Component Status ID" },
{ 0x0032, 0x1060, "LO", "Requested Procedure Description" },
{ 0x0032, 0x1064, "SQ", "Requested Procedure Code Sequence" },
{ 0x0032, 0x1070, "LO", "Requested Contrast Agent" },
{ 0x0032, 0x4000, "LT", "Study Comments" },
{ 0x0033, 0x0001, "UN", "?" },
{ 0x0033, 0x0002, "UN", "?" },
{ 0x0033, 0x0005, "UN", "?" },
{ 0x0033, 0x0006, "UN", "?" },
{ 0x0033, 0x0010, "LT", "Patient Study UID" },
{ 0x0037, 0x0010, "LO", "ReferringDepartment" },
{ 0x0037, 0x0020, "US", "ScreenNumber" },
{ 0x0037, 0x0040, "SH", "LeftOrientation" },
{ 0x0037, 0x0042, "SH", "RightOrientation" },
{ 0x0037, 0x0050, "CS", "Inversion" },
{ 0x0037, 0x0060, "US", "DSA" },
{ 0x0038, 0x0000, "UL", "Visit Group Length" },
{ 0x0038, 0x0004, "SQ", "Referenced Patient Alias Sequence" },
{ 0x0038, 0x0008, "CS", "Visit Status ID" },
{ 0x0038, 0x0010, "LO", "Admission ID" },
{ 0x0038, 0x0011, "LO", "Issuer of Admission ID" },
{ 0x0038, 0x0016, "LO", "Route of Admissions" },
{ 0x0038, 0x001a, "DA", "Scheduled Admission Date" },
{ 0x0038, 0x001b, "TM", "Scheduled Admission Time" },
{ 0x0038, 0x001c, "DA", "Scheduled Discharge Date" },
{ 0x0038, 0x001d, "TM", "Scheduled Discharge Time" },
{ 0x0038, 0x001e, "LO", "Scheduled Patient Institution Residence" },
{ 0x0038, 0x0020, "DA", "Admitting Date" },
{ 0x0038, 0x0021, "TM", "Admitting Time" },
{ 0x0038, 0x0030, "DA", "Discharge Date" },
{ 0x0038, 0x0032, "TM", "Discharge Time" },
{ 0x0038, 0x0040, "LO", "Discharge Diagnosis Description" },
{ 0x0038, 0x0044, "SQ", "Discharge Diagnosis Code Sequence" },
{ 0x0038, 0x0050, "LO", "Special Needs" },
{ 0x0038, 0x0300, "LO", "Current Patient Location" },
{ 0x0038, 0x0400, "LO", "Patient's Institution Residence" },
{ 0x0038, 0x0500, "LO", "Patient State" },
{ 0x0038, 0x4000, "LT", "Visit Comments" },
{ 0x0039, 0x0080, "IS", "Private Entity Number" },
{ 0x0039, 0x0085, "DA", "Private Entity Date" },
{ 0x0039, 0x0090, "TM", "Private Entity Time" },
{ 0x0039, 0x0095, "LO", "Private Entity Launch Command" },
{ 0x0039, 0x00aa, "CS", "Private Entity Type" },
{ 0x003a, 0x0002, "SQ", "Waveform Sequence" },
{ 0x003a, 0x0005, "US", "Waveform Number of Channels" },
{ 0x003a, 0x0010, "UL", "Waveform Number of Samples" },
{ 0x003a, 0x001a, "DS", "Sampling Frequency" },
{ 0x003a, 0x0020, "SH", "Group Label" },
{ 0x003a, 0x0103, "CS", "Waveform Sample Value Representation" },
{ 0x003a, 0x0122, "OB", "Waveform Padding Value" },
{ 0x003a, 0x0200, "SQ", "Channel Definition" },
{ 0x003a, 0x0202, "IS", "Waveform Channel Number" },
{ 0x003a, 0x0203, "SH", "Channel Label" },
{ 0x003a, 0x0205, "CS", "Channel Status" },
{ 0x003a, 0x0208, "SQ", "Channel Source" },
{ 0x003a, 0x0209, "SQ", "Channel Source Modifiers" },
{ 0x003a, 0x020a, "SQ", "Differential Channel Source" },
{ 0x003a, 0x020b, "SQ", "Differential Channel Source Modifiers" },
{ 0x003a, 0x0210, "DS", "Channel Sensitivity" },
{ 0x003a, 0x0211, "SQ", "Channel Sensitivity Units" },
{ 0x003a, 0x0212, "DS", "Channel Sensitivity Correction Factor" },
{ 0x003a, 0x0213, "DS", "Channel Baseline" },
{ 0x003a, 0x0214, "DS", "Channel Time Skew" },
{ 0x003a, 0x0215, "DS", "Channel Sample Skew" },
{ 0x003a, 0x0216, "OB", "Channel Minimum Value" },
{ 0x003a, 0x0217, "OB", "Channel Maximum Value" },
{ 0x003a, 0x0218, "DS", "Channel Offset" },
{ 0x003a, 0x021a, "US", "Bits Per Sample" },
{ 0x003a, 0x0220, "DS", "Filter Low Frequency" },
{ 0x003a, 0x0221, "DS", "Filter High Frequency" },
{ 0x003a, 0x0222, "DS", "Notch Filter Frequency" },
{ 0x003a, 0x0223, "DS", "Notch Filter Bandwidth" },
{ 0x003a, 0x1000, "OB", "Waveform Data" },
{ 0x0040, 0x0001, "AE", "Scheduled Station AE Title" },
{ 0x0040, 0x0002, "DA", "Scheduled Procedure Step Start Date" },
{ 0x0040, 0x0003, "TM", "Scheduled Procedure Step Start Time" },
{ 0x0040, 0x0004, "DA", "Scheduled Procedure Step End Date" },
{ 0x0040, 0x0005, "TM", "Scheduled Procedure Step End Time" },
{ 0x0040, 0x0006, "PN", "Scheduled Performing Physician Name" },
{ 0x0040, 0x0007, "LO", "Scheduled Procedure Step Description" },
{ 0x0040, 0x0008, "SQ", "Scheduled Action Item Code Sequence" },
{ 0x0040, 0x0009, "SH", "Scheduled Procedure Step ID" },
{ 0x0040, 0x0010, "SH", "Scheduled Station Name" },
{ 0x0040, 0x0011, "SH", "Scheduled Procedure Step Location" },
{ 0x0040, 0x0012, "LO", "Pre-Medication" },
{ 0x0040, 0x0020, "CS", "Scheduled Procedure Step Status" },
{ 0x0040, 0x0100, "SQ", "Scheduled Procedure Step Sequence" },
{ 0x0040, 0x0302, "US", "Entrance Dose" },
{ 0x0040, 0x0303, "US", "Exposed Area" },
{ 0x0040, 0x0306, "DS", "Distance Source to Entrance" },
{ 0x0040, 0x0307, "DS", "Distance Source to Support" },
{ 0x0040, 0x0310, "ST", "Comments On Radiation Dose" },
{ 0x0040, 0x0312, "DS", "X-Ray Output" },
{ 0x0040, 0x0314, "DS", "Half Value Layer" },
{ 0x0040, 0x0316, "DS", "Organ Dose" },
{ 0x0040, 0x0318, "CS", "Organ Exposed" },
{ 0x0040, 0x0400, "LT", "Comments On Scheduled Procedure Step" },
{ 0x0040, 0x050a, "LO", "Specimen Accession Number" },
{ 0x0040, 0x0550, "SQ", "Specimen Sequence" },
{ 0x0040, 0x0551, "LO", "Specimen Identifier" },
{ 0x0040, 0x0552, "SQ", "Specimen Description Sequence" },
{ 0x0040, 0x0553, "ST", "Specimen Description" },
{ 0x0040, 0x0555, "SQ", "Acquisition Context Sequence" },
{ 0x0040, 0x0556, "ST", "Acquisition Context Description" },
{ 0x0040, 0x059a, "SQ", "Specimen Type Code Sequence" },
{ 0x0040, 0x06fa, "LO", "Slide Identifier" },
{ 0x0040, 0x071a, "SQ", "Image Center Point Coordinates Sequence" },
{ 0x0040, 0x072a, "DS", "X Offset In Slide Coordinate System" },
{ 0x0040, 0x073a, "DS", "Y Offset In Slide Coordinate System" },
{ 0x0040, 0x074a, "DS", "Z Offset In Slide Coordinate System" },
{ 0x0040, 0x08d8, "SQ", "Pixel Spacing Sequence" },
{ 0x0040, 0x08da, "SQ", "Coordinate System Axis Code Sequence" },
{ 0x0040, 0x08ea, "SQ", "Measurement Units Code Sequence" },
{ 0x0040, 0x09f8, "SQ", "Vital Stain Code Sequence" },
{ 0x0040, 0x1001, "SH", "Requested Procedure ID" },
{ 0x0040, 0x1002, "LO", "Reason For Requested Procedure" },
{ 0x0040, 0x1003, "SH", "Requested Procedure Priority" },
{ 0x0040, 0x1004, "LO", "Patient Transport Arrangements" },
{ 0x0040, 0x1005, "LO", "Requested Procedure Location" },
{ 0x0040, 0x1006, "SH", "Placer Order Number of Procedure" },
{ 0x0040, 0x1007, "SH", "Filler Order Number of Procedure" },
{ 0x0040, 0x1008, "LO", "Confidentiality Code" },
{ 0x0040, 0x1009, "SH", "Reporting Priority" },
{ 0x0040, 0x1010, "PN", "Names of Intended Recipients of Results" },
{ 0x0040, 0x1400, "LT", "Requested Procedure Comments" },
{ 0x0040, 0x2001, "LO", "Reason For Imaging Service Request" },
{ 0x0040, 0x2004, "DA", "Issue Date of Imaging Service Request" },
{ 0x0040, 0x2005, "TM", "Issue Time of Imaging Service Request" },
{ 0x0040, 0x2006, "SH", "Placer Order Number of Imaging Service Request" },
{ 0x0040, 0x2007, "SH", "Filler Order Number of Imaging Service Request" },
{ 0x0040, 0x2008, "PN", "Order Entered By" },
{ 0x0040, 0x2009, "SH", "Order Enterer Location" },
{ 0x0040, 0x2010, "SH", "Order Callback Phone Number" },
{ 0x0040, 0x2400, "LT", "Imaging Service Request Comments" },
{ 0x0040, 0x3001, "LO", "Confidentiality Constraint On Patient Data" },
{ 0x0040, 0xa007, "CS", "Findings Flag" },
{ 0x0040, 0xa020, "SQ", "Findings Sequence" },
{ 0x0040, 0xa021, "UI", "Findings Group UID" },
{ 0x0040, 0xa022, "UI", "Referenced Findings Group UID" },
{ 0x0040, 0xa023, "DA", "Findings Group Recording Date" },
{ 0x0040, 0xa024, "TM", "Findings Group Recording Time" },
{ 0x0040, 0xa026, "SQ", "Findings Source Category Code Sequence" },
{ 0x0040, 0xa027, "LO", "Documenting Organization" },
{ 0x0040, 0xa028, "SQ", "Documenting Organization Identifier Code Sequence" },
{ 0x0040, 0xa032, "LO", "History Reliability Qualifier Description" },
{ 0x0040, 0xa043, "SQ", "Concept Name Code Sequence" },
{ 0x0040, 0xa047, "LO", "Measurement Precision Description" },
{ 0x0040, 0xa057, "CS", "Urgency or Priority Alerts" },
{ 0x0040, 0xa060, "LO", "Sequencing Indicator" },
{ 0x0040, 0xa066, "SQ", "Document Identifier Code Sequence" },
{ 0x0040, 0xa067, "PN", "Document Author" },
{ 0x0040, 0xa068, "SQ", "Document Author Identifier Code Sequence" },
{ 0x0040, 0xa070, "SQ", "Identifier Code Sequence" },
{ 0x0040, 0xa073, "LO", "Object String Identifier" },
{ 0x0040, 0xa074, "OB", "Object Binary Identifier" },
{ 0x0040, 0xa075, "PN", "Documenting Observer" },
{ 0x0040, 0xa076, "SQ", "Documenting Observer Identifier Code Sequence" },
{ 0x0040, 0xa078, "SQ", "Observation Subject Identifier Code Sequence" },
{ 0x0040, 0xa080, "SQ", "Person Identifier Code Sequence" },
{ 0x0040, 0xa085, "SQ", "Procedure Identifier Code Sequence" },
{ 0x0040, 0xa088, "LO", "Object Directory String Identifier" },
{ 0x0040, 0xa089, "OB", "Object Directory Binary Identifier" },
{ 0x0040, 0xa090, "CS", "History Reliability Qualifier" },
{ 0x0040, 0xa0a0, "CS", "Referenced Type of Data" },
{ 0x0040, 0xa0b0, "US", "Referenced Waveform Channels" },
{ 0x0040, 0xa110, "DA", "Date of Document or Verbal Transaction" },
{ 0x0040, 0xa112, "TM", "Time of Document Creation or Verbal Transaction" },
{ 0x0040, 0xa121, "DA", "Date" },
{ 0x0040, 0xa122, "TM", "Time" },
{ 0x0040, 0xa123, "PN", "Person Name" },
{ 0x0040, 0xa124, "SQ", "Referenced Person Sequence" },
{ 0x0040, 0xa125, "CS", "Report Status ID" },
{ 0x0040, 0xa130, "CS", "Temporal Range Type" },
{ 0x0040, 0xa132, "UL", "Referenced Sample Offsets" },
{ 0x0040, 0xa136, "US", "Referenced Frame Numbers" },
{ 0x0040, 0xa138, "DS", "Referenced Time Offsets" },
{ 0x0040, 0xa13a, "DT", "Referenced Datetime" },
{ 0x0040, 0xa160, "UT", "Text Value" },
{ 0x0040, 0xa167, "SQ", "Observation Category Code Sequence" },
{ 0x0040, 0xa168, "SQ", "Concept Code Sequence" },
{ 0x0040, 0xa16a, "ST", "Bibliographic Citation" },
{ 0x0040, 0xa170, "CS", "Observation Class" },
{ 0x0040, 0xa171, "UI", "Observation UID" },
{ 0x0040, 0xa172, "UI", "Referenced Observation UID" },
{ 0x0040, 0xa173, "CS", "Referenced Observation Class" },
{ 0x0040, 0xa174, "CS", "Referenced Object Observation Class" },
{ 0x0040, 0xa180, "US", "Annotation Group Number" },
{ 0x0040, 0xa192, "DA", "Observation Date" },
{ 0x0040, 0xa193, "TM", "Observation Time" },
{ 0x0040, 0xa194, "CS", "Measurement Automation" },
{ 0x0040, 0xa195, "SQ", "Concept Name Code Sequence Modifier" },
{ 0x0040, 0xa224, "ST", "Identification Description" },
{ 0x0040, 0xa290, "CS", "Coordinates Set Geometric Type" },
{ 0x0040, 0xa296, "SQ", "Algorithm Code Sequence" },
{ 0x0040, 0xa297, "ST", "Algorithm Description" },
{ 0x0040, 0xa29a, "SL", "Pixel Coordinates Set" },
{ 0x0040, 0xa300, "SQ", "Measured Value Sequence" },
{ 0x0040, 0xa307, "PN", "Current Observer" },
{ 0x0040, 0xa30a, "DS", "Numeric Value" },
{ 0x0040, 0xa313, "SQ", "Referenced Accession Sequence" },
{ 0x0040, 0xa33a, "ST", "Report Status Comment" },
{ 0x0040, 0xa340, "SQ", "Procedure Context Sequence" },
{ 0x0040, 0xa352, "PN", "Verbal Source" },
{ 0x0040, 0xa353, "ST", "Address" },
{ 0x0040, 0xa354, "LO", "Telephone Number" },
{ 0x0040, 0xa358, "SQ", "Verbal Source Identifier Code Sequence" },
{ 0x0040, 0xa380, "SQ", "Report Detail Sequence" },
{ 0x0040, 0xa402, "UI", "Observation Subject UID" },
{ 0x0040, 0xa403, "CS", "Observation Subject Class" },
{ 0x0040, 0xa404, "SQ", "Observation Subject Type Code Sequence" },
{ 0x0040, 0xa600, "CS", "Observation Subject Context Flag" },
{ 0x0040, 0xa601, "CS", "Observer Context Flag" },
{ 0x0040, 0xa603, "CS", "Procedure Context Flag" },
{ 0x0040, 0xa730, "SQ", "Observations Sequence" },
{ 0x0040, 0xa731, "SQ", "Relationship Sequence" },
{ 0x0040, 0xa732, "SQ", "Relationship Type Code Sequence" },
{ 0x0040, 0xa744, "SQ", "Language Code Sequence" },
{ 0x0040, 0xa992, "ST", "Uniform Resource Locator" },
{ 0x0040, 0xb020, "SQ", "Annotation Sequence" },
{ 0x0040, 0xdb73, "SQ", "Relationship Type Code Sequence Modifier" },
{ 0x0041, 0x0000, "LT", "Papyrus Comments" },
{ 0x0041, 0x0010, "xs", "?" },
{ 0x0041, 0x0011, "xs", "?" },
{ 0x0041, 0x0012, "UL", "Pixel Offset" },
{ 0x0041, 0x0013, "SQ", "Image Identifier Sequence" },
{ 0x0041, 0x0014, "SQ", "External File Reference Sequence" },
{ 0x0041, 0x0015, "US", "Number of Images" },
{ 0x0041, 0x0020, "xs", "?" },
{ 0x0041, 0x0021, "UI", "Referenced SOP Class UID" },
{ 0x0041, 0x0022, "UI", "Referenced SOP Instance UID" },
{ 0x0041, 0x0030, "xs", "?" },
{ 0x0041, 0x0031, "xs", "?" },
{ 0x0041, 0x0032, "xs", "?" },
{ 0x0041, 0x0034, "DA", "Modified Date" },
{ 0x0041, 0x0036, "TM", "Modified Time" },
{ 0x0041, 0x0040, "LT", "Owner Name" },
{ 0x0041, 0x0041, "UI", "Referenced Image SOP Class UID" },
{ 0x0041, 0x0042, "UI", "Referenced Image SOP Instance UID" },
{ 0x0041, 0x0050, "xs", "?" },
{ 0x0041, 0x0060, "UL", "Number of Images" },
{ 0x0041, 0x0062, "UL", "Number of Other" },
{ 0x0041, 0x00a0, "LT", "External Folder Element DSID" },
{ 0x0041, 0x00a1, "US", "External Folder Element Data Set Type" },
{ 0x0041, 0x00a2, "LT", "External Folder Element File Location" },
{ 0x0041, 0x00a3, "UL", "External Folder Element Length" },
{ 0x0041, 0x00b0, "LT", "Internal Folder Element DSID" },
{ 0x0041, 0x00b1, "US", "Internal Folder Element Data Set Type" },
{ 0x0041, 0x00b2, "UL", "Internal Offset To Data Set" },
{ 0x0041, 0x00b3, "UL", "Internal Offset To Image" },
{ 0x0043, 0x0001, "SS", "Bitmap Of Prescan Options" },
{ 0x0043, 0x0002, "SS", "Gradient Offset In X" },
{ 0x0043, 0x0003, "SS", "Gradient Offset In Y" },
{ 0x0043, 0x0004, "SS", "Gradient Offset In Z" },
{ 0x0043, 0x0005, "SS", "Image Is Original Or Unoriginal" },
{ 0x0043, 0x0006, "SS", "Number Of EPI Shots" },
{ 0x0043, 0x0007, "SS", "Views Per Segment" },
{ 0x0043, 0x0008, "SS", "Respiratory Rate In BPM" },
{ 0x0043, 0x0009, "SS", "Respiratory Trigger Point" },
{ 0x0043, 0x000a, "SS", "Type Of Receiver Used" },
{ 0x0043, 0x000b, "DS", "Peak Rate Of Change Of Gradient Field" },
{ 0x0043, 0x000c, "DS", "Limits In Units Of Percent" },
{ 0x0043, 0x000d, "DS", "PSD Estimated Limit" },
{ 0x0043, 0x000e, "DS", "PSD Estimated Limit In Tesla Per Second" },
{ 0x0043, 0x000f, "DS", "SAR Avg Head" },
{ 0x0043, 0x0010, "US", "Window Value" },
{ 0x0043, 0x0011, "US", "Total Input Views" },
{ 0x0043, 0x0012, "SS", "Xray Chain" },
{ 0x0043, 0x0013, "SS", "Recon Kernel Parameters" },
{ 0x0043, 0x0014, "SS", "Calibration Parameters" },
{ 0x0043, 0x0015, "SS", "Total Output Views" },
{ 0x0043, 0x0016, "SS", "Number Of Overranges" },
{ 0x0043, 0x0017, "DS", "IBH Image Scale Factors" },
{ 0x0043, 0x0018, "DS", "BBH Coefficients" },
{ 0x0043, 0x0019, "SS", "Number Of BBH Chains To Blend" },
{ 0x0043, 0x001a, "SL", "Starting Channel Number" },
{ 0x0043, 0x001b, "SS", "PPScan Parameters" },
{ 0x0043, 0x001c, "SS", "GE Image Integrity" },
{ 0x0043, 0x001d, "SS", "Level Value" },
{ 0x0043, 0x001e, "xs", "?" },
{ 0x0043, 0x001f, "SL", "Max Overranges In A View" },
{ 0x0043, 0x0020, "DS", "Avg Overranges All Views" },
{ 0x0043, 0x0021, "SS", "Corrected Afterglow Terms" },
{ 0x0043, 0x0025, "SS", "Reference Channels" },
{ 0x0043, 0x0026, "US", "No Views Ref Channels Blocked" },
{ 0x0043, 0x0027, "xs", "?" },
{ 0x0043, 0x0028, "OB", "Unique Image Identifier" },
{ 0x0043, 0x0029, "OB", "Histogram Tables" },
{ 0x0043, 0x002a, "OB", "User Defined Data" },
{ 0x0043, 0x002b, "SS", "Private Scan Options" },
{ 0x0043, 0x002c, "SS", "Effective Echo Spacing" },
{ 0x0043, 0x002d, "SH", "String Slop Field 1" },
{ 0x0043, 0x002e, "SH", "String Slop Field 2" },
{ 0x0043, 0x002f, "SS", "Raw Data Type" },
{ 0x0043, 0x0030, "SS", "Raw Data Type" },
{ 0x0043, 0x0031, "DS", "RA Coord Of Target Recon Centre" },
{ 0x0043, 0x0032, "SS", "Raw Data Type" },
{ 0x0043, 0x0033, "FL", "Neg Scan Spacing" },
{ 0x0043, 0x0034, "IS", "Offset Frequency" },
{ 0x0043, 0x0035, "UL", "User Usage Tag" },
{ 0x0043, 0x0036, "UL", "User Fill Map MSW" },
{ 0x0043, 0x0037, "UL", "User Fill Map LSW" },
{ 0x0043, 0x0038, "FL", "User 25 To User 48" },
{ 0x0043, 0x0039, "IS", "Slop Integer 6 To Slop Integer 9" },
{ 0x0043, 0x0040, "FL", "Trigger On Position" },
{ 0x0043, 0x0041, "FL", "Degree Of Rotation" },
{ 0x0043, 0x0042, "SL", "DAS Trigger Source" },
{ 0x0043, 0x0043, "SL", "DAS Fpa Gain" },
{ 0x0043, 0x0044, "SL", "DAS Output Source" },
{ 0x0043, 0x0045, "SL", "DAS Ad Input" },
{ 0x0043, 0x0046, "SL", "DAS Cal Mode" },
{ 0x0043, 0x0047, "SL", "DAS Cal Frequency" },
{ 0x0043, 0x0048, "SL", "DAS Reg Xm" },
{ 0x0043, 0x0049, "SL", "DAS Auto Zero" },
{ 0x0043, 0x004a, "SS", "Starting Channel Of View" },
{ 0x0043, 0x004b, "SL", "DAS Xm Pattern" },
{ 0x0043, 0x004c, "SS", "TGGC Trigger Mode" },
{ 0x0043, 0x004d, "FL", "Start Scan To Xray On Delay" },
{ 0x0043, 0x004e, "FL", "Duration Of Xray On" },
{ 0x0044, 0x0000, "UI", "?" },
{ 0x0045, 0x0004, "CS", "AES" },
{ 0x0045, 0x0006, "DS", "Angulation" },
{ 0x0045, 0x0009, "DS", "Real Magnification Factor" },
{ 0x0045, 0x000b, "CS", "Senograph Type" },
{ 0x0045, 0x000c, "DS", "Integration Time" },
{ 0x0045, 0x000d, "DS", "ROI Origin X and Y" },
{ 0x0045, 0x0011, "DS", "Receptor Size cm X and Y" },
{ 0x0045, 0x0012, "IS", "Receptor Size Pixels X and Y" },
{ 0x0045, 0x0013, "ST", "Screen" },
{ 0x0045, 0x0014, "DS", "Pixel Pitch Microns" },
{ 0x0045, 0x0015, "IS", "Pixel Depth Bits" },
{ 0x0045, 0x0016, "IS", "Binning Factor X and Y" },
{ 0x0045, 0x001b, "CS", "Clinical View" },
{ 0x0045, 0x001d, "DS", "Mean Of Raw Gray Levels" },
{ 0x0045, 0x001e, "DS", "Mean Of Offset Gray Levels" },
{ 0x0045, 0x001f, "DS", "Mean Of Corrected Gray Levels" },
{ 0x0045, 0x0020, "DS", "Mean Of Region Gray Levels" },
{ 0x0045, 0x0021, "DS", "Mean Of Log Region Gray Levels" },
{ 0x0045, 0x0022, "DS", "Standard Deviation Of Raw Gray Levels" },
{ 0x0045, 0x0023, "DS", "Standard Deviation Of Corrected Gray Levels" },
{ 0x0045, 0x0024, "DS", "Standard Deviation Of Region Gray Levels" },
{ 0x0045, 0x0025, "DS", "Standard Deviation Of Log Region Gray Levels" },
{ 0x0045, 0x0026, "OB", "MAO Buffer" },
{ 0x0045, 0x0027, "IS", "Set Number" },
{ 0x0045, 0x0028, "CS", "WindowingType (LINEAR or GAMMA)" },
{ 0x0045, 0x0029, "DS", "WindowingParameters" },
{ 0x0045, 0x002a, "IS", "Crosshair Cursor X Coordinates" },
{ 0x0045, 0x002b, "IS", "Crosshair Cursor Y Coordinates" },
{ 0x0045, 0x0039, "US", "Vignette Rows" },
{ 0x0045, 0x003a, "US", "Vignette Columns" },
{ 0x0045, 0x003b, "US", "Vignette Bits Allocated" },
{ 0x0045, 0x003c, "US", "Vignette Bits Stored" },
{ 0x0045, 0x003d, "US", "Vignette High Bit" },
{ 0x0045, 0x003e, "US", "Vignette Pixel Representation" },
{ 0x0045, 0x003f, "OB", "Vignette Pixel Data" },
{ 0x0047, 0x0001, "SQ", "Reconstruction Parameters Sequence" },
{ 0x0047, 0x0050, "UL", "Volume Voxel Count" },
{ 0x0047, 0x0051, "UL", "Volume Segment Count" },
{ 0x0047, 0x0053, "US", "Volume Slice Size" },
{ 0x0047, 0x0054, "US", "Volume Slice Count" },
{ 0x0047, 0x0055, "SL", "Volume Threshold Value" },
{ 0x0047, 0x0057, "DS", "Volume Voxel Ratio" },
{ 0x0047, 0x0058, "DS", "Volume Voxel Size" },
{ 0x0047, 0x0059, "US", "Volume Z Position Size" },
{ 0x0047, 0x0060, "DS", "Volume Base Line" },
{ 0x0047, 0x0061, "DS", "Volume Center Point" },
{ 0x0047, 0x0063, "SL", "Volume Skew Base" },
{ 0x0047, 0x0064, "DS", "Volume Registration Transform Rotation Matrix" },
{ 0x0047, 0x0065, "DS", "Volume Registration Transform Translation Vector" },
{ 0x0047, 0x0070, "DS", "KVP List" },
{ 0x0047, 0x0071, "IS", "XRay Tube Current List" },
{ 0x0047, 0x0072, "IS", "Exposure List" },
{ 0x0047, 0x0080, "LO", "Acquisition DLX Identifier" },
{ 0x0047, 0x0085, "SQ", "Acquisition DLX 2D Series Sequence" },
{ 0x0047, 0x0089, "DS", "Contrast Agent Volume List" },
{ 0x0047, 0x008a, "US", "Number Of Injections" },
{ 0x0047, 0x008b, "US", "Frame Count" },
{ 0x0047, 0x0096, "IS", "Used Frames" },
{ 0x0047, 0x0091, "LO", "XA 3D Reconstruction Algorithm Name" },
{ 0x0047, 0x0092, "CS", "XA 3D Reconstruction Algorithm Version" },
{ 0x0047, 0x0093, "DA", "DLX Calibration Date" },
{ 0x0047, 0x0094, "TM", "DLX Calibration Time" },
{ 0x0047, 0x0095, "CS", "DLX Calibration Status" },
{ 0x0047, 0x0098, "US", "Transform Count" },
{ 0x0047, 0x0099, "SQ", "Transform Sequence" },
{ 0x0047, 0x009a, "DS", "Transform Rotation Matrix" },
{ 0x0047, 0x009b, "DS", "Transform Translation Vector" },
{ 0x0047, 0x009c, "LO", "Transform Label" },
{ 0x0047, 0x00b1, "US", "Wireframe Count" },
{ 0x0047, 0x00b2, "US", "Location System" },
{ 0x0047, 0x00b0, "SQ", "Wireframe List" },
{ 0x0047, 0x00b5, "LO", "Wireframe Name" },
{ 0x0047, 0x00b6, "LO", "Wireframe Group Name" },
{ 0x0047, 0x00b7, "LO", "Wireframe Color" },
{ 0x0047, 0x00b8, "SL", "Wireframe Attributes" },
{ 0x0047, 0x00b9, "SL", "Wireframe Point Count" },
{ 0x0047, 0x00ba, "SL", "Wireframe Timestamp" },
{ 0x0047, 0x00bb, "SQ", "Wireframe Point List" },
{ 0x0047, 0x00bc, "DS", "Wireframe Points Coordinates" },
{ 0x0047, 0x00c0, "DS", "Volume Upper Left High Corner RAS" },
{ 0x0047, 0x00c1, "DS", "Volume Slice To RAS Rotation Matrix" },
{ 0x0047, 0x00c2, "DS", "Volume Upper Left High Corner TLOC" },
{ 0x0047, 0x00d1, "OB", "Volume Segment List" },
{ 0x0047, 0x00d2, "OB", "Volume Gradient List" },
{ 0x0047, 0x00d3, "OB", "Volume Density List" },
{ 0x0047, 0x00d4, "OB", "Volume Z Position List" },
{ 0x0047, 0x00d5, "OB", "Volume Original Index List" },
{ 0x0050, 0x0000, "UL", "Calibration Group Length" },
{ 0x0050, 0x0004, "CS", "Calibration Object" },
{ 0x0050, 0x0010, "SQ", "DeviceSequence" },
{ 0x0050, 0x0014, "DS", "DeviceLength" },
{ 0x0050, 0x0016, "DS", "DeviceDiameter" },
{ 0x0050, 0x0017, "CS", "DeviceDiameterUnits" },
{ 0x0050, 0x0018, "DS", "DeviceVolume" },
{ 0x0050, 0x0019, "DS", "InterMarkerDistance" },
{ 0x0050, 0x0020, "LO", "DeviceDescription" },
{ 0x0050, 0x0030, "SQ", "CodedInterventionDeviceSequence" },
{ 0x0051, 0x0010, "xs", "Image Text" },
{ 0x0054, 0x0000, "UL", "Nuclear Acquisition Group Length" },
{ 0x0054, 0x0010, "US", "Energy Window Vector" },
{ 0x0054, 0x0011, "US", "Number of Energy Windows" },
{ 0x0054, 0x0012, "SQ", "Energy Window Information Sequence" },
{ 0x0054, 0x0013, "SQ", "Energy Window Range Sequence" },
{ 0x0054, 0x0014, "DS", "Energy Window Lower Limit" },
{ 0x0054, 0x0015, "DS", "Energy Window Upper Limit" },
{ 0x0054, 0x0016, "SQ", "Radiopharmaceutical Information Sequence" },
{ 0x0054, 0x0017, "IS", "Residual Syringe Counts" },
{ 0x0054, 0x0018, "SH", "Energy Window Name" },
{ 0x0054, 0x0020, "US", "Detector Vector" },
{ 0x0054, 0x0021, "US", "Number of Detectors" },
{ 0x0054, 0x0022, "SQ", "Detector Information Sequence" },
{ 0x0054, 0x0030, "US", "Phase Vector" },
{ 0x0054, 0x0031, "US", "Number of Phases" },
{ 0x0054, 0x0032, "SQ", "Phase Information Sequence" },
{ 0x0054, 0x0033, "US", "Number of Frames In Phase" },
{ 0x0054, 0x0036, "IS", "Phase Delay" },
{ 0x0054, 0x0038, "IS", "Pause Between Frames" },
{ 0x0054, 0x0050, "US", "Rotation Vector" },
{ 0x0054, 0x0051, "US", "Number of Rotations" },
{ 0x0054, 0x0052, "SQ", "Rotation Information Sequence" },
{ 0x0054, 0x0053, "US", "Number of Frames In Rotation" },
{ 0x0054, 0x0060, "US", "R-R Interval Vector" },
{ 0x0054, 0x0061, "US", "Number of R-R Intervals" },
{ 0x0054, 0x0062, "SQ", "Gated Information Sequence" },
{ 0x0054, 0x0063, "SQ", "Data Information Sequence" },
{ 0x0054, 0x0070, "US", "Time Slot Vector" },
{ 0x0054, 0x0071, "US", "Number of Time Slots" },
{ 0x0054, 0x0072, "SQ", "Time Slot Information Sequence" },
{ 0x0054, 0x0073, "DS", "Time Slot Time" },
{ 0x0054, 0x0080, "US", "Slice Vector" },
{ 0x0054, 0x0081, "US", "Number of Slices" },
{ 0x0054, 0x0090, "US", "Angular View Vector" },
{ 0x0054, 0x0100, "US", "Time Slice Vector" },
{ 0x0054, 0x0101, "US", "Number Of Time Slices" },
{ 0x0054, 0x0200, "DS", "Start Angle" },
{ 0x0054, 0x0202, "CS", "Type of Detector Motion" },
{ 0x0054, 0x0210, "IS", "Trigger Vector" },
{ 0x0054, 0x0211, "US", "Number of Triggers in Phase" },
{ 0x0054, 0x0220, "SQ", "View Code Sequence" },
{ 0x0054, 0x0222, "SQ", "View Modifier Code Sequence" },
{ 0x0054, 0x0300, "SQ", "Radionuclide Code Sequence" },
{ 0x0054, 0x0302, "SQ", "Radiopharmaceutical Route Code Sequence" },
{ 0x0054, 0x0304, "SQ", "Radiopharmaceutical Code Sequence" },
{ 0x0054, 0x0306, "SQ", "Calibration Data Sequence" },
{ 0x0054, 0x0308, "US", "Energy Window Number" },
{ 0x0054, 0x0400, "SH", "Image ID" },
{ 0x0054, 0x0410, "SQ", "Patient Orientation Code Sequence" },
{ 0x0054, 0x0412, "SQ", "Patient Orientation Modifier Code Sequence" },
{ 0x0054, 0x0414, "SQ", "Patient Gantry Relationship Code Sequence" },
{ 0x0054, 0x1000, "CS", "Positron Emission Tomography Series Type" },
{ 0x0054, 0x1001, "CS", "Positron Emission Tomography Units" },
{ 0x0054, 0x1002, "CS", "Counts Source" },
{ 0x0054, 0x1004, "CS", "Reprojection Method" },
{ 0x0054, 0x1100, "CS", "Randoms Correction Method" },
{ 0x0054, 0x1101, "LO", "Attenuation Correction Method" },
{ 0x0054, 0x1102, "CS", "Decay Correction" },
{ 0x0054, 0x1103, "LO", "Reconstruction Method" },
{ 0x0054, 0x1104, "LO", "Detector Lines of Response Used" },
{ 0x0054, 0x1105, "LO", "Scatter Correction Method" },
{ 0x0054, 0x1200, "DS", "Axial Acceptance" },
{ 0x0054, 0x1201, "IS", "Axial Mash" },
{ 0x0054, 0x1202, "IS", "Transverse Mash" },
{ 0x0054, 0x1203, "DS", "Detector Element Size" },
{ 0x0054, 0x1210, "DS", "Coincidence Window Width" },
{ 0x0054, 0x1220, "CS", "Secondary Counts Type" },
{ 0x0054, 0x1300, "DS", "Frame Reference Time" },
{ 0x0054, 0x1310, "IS", "Primary Prompts Counts Accumulated" },
{ 0x0054, 0x1311, "IS", "Secondary Counts Accumulated" },
{ 0x0054, 0x1320, "DS", "Slice Sensitivity Factor" },
{ 0x0054, 0x1321, "DS", "Decay Factor" },
{ 0x0054, 0x1322, "DS", "Dose Calibration Factor" },
{ 0x0054, 0x1323, "DS", "Scatter Fraction Factor" },
{ 0x0054, 0x1324, "DS", "Dead Time Factor" },
{ 0x0054, 0x1330, "US", "Image Index" },
{ 0x0054, 0x1400, "CS", "Counts Included" },
{ 0x0054, 0x1401, "CS", "Dead Time Correction Flag" },
{ 0x0055, 0x0046, "LT", "Current Ward" },
{ 0x0058, 0x0000, "SQ", "?" },
{ 0x0060, 0x3000, "SQ", "Histogram Sequence" },
{ 0x0060, 0x3002, "US", "Histogram Number of Bins" },
{ 0x0060, 0x3004, "xs", "Histogram First Bin Value" },
{ 0x0060, 0x3006, "xs", "Histogram Last Bin Value" },
{ 0x0060, 0x3008, "US", "Histogram Bin Width" },
{ 0x0060, 0x3010, "LO", "Histogram Explanation" },
{ 0x0060, 0x3020, "UL", "Histogram Data" },
{ 0x0070, 0x0001, "SQ", "Graphic Annotation Sequence" },
{ 0x0070, 0x0002, "CS", "Graphic Layer" },
{ 0x0070, 0x0003, "CS", "Bounding Box Annotation Units" },
{ 0x0070, 0x0004, "CS", "Anchor Point Annotation Units" },
{ 0x0070, 0x0005, "CS", "Graphic Annotation Units" },
{ 0x0070, 0x0006, "ST", "Unformatted Text Value" },
{ 0x0070, 0x0008, "SQ", "Text Object Sequence" },
{ 0x0070, 0x0009, "SQ", "Graphic Object Sequence" },
{ 0x0070, 0x0010, "FL", "Bounding Box TLHC" },
{ 0x0070, 0x0011, "FL", "Bounding Box BRHC" },
{ 0x0070, 0x0014, "FL", "Anchor Point" },
{ 0x0070, 0x0015, "CS", "Anchor Point Visibility" },
{ 0x0070, 0x0020, "US", "Graphic Dimensions" },
{ 0x0070, 0x0021, "US", "Number Of Graphic Points" },
{ 0x0070, 0x0022, "FL", "Graphic Data" },
{ 0x0070, 0x0023, "CS", "Graphic Type" },
{ 0x0070, 0x0024, "CS", "Graphic Filled" },
{ 0x0070, 0x0040, "IS", "Image Rotation" },
{ 0x0070, 0x0041, "CS", "Image Horizontal Flip" },
{ 0x0070, 0x0050, "US", "Displayed Area TLHC" },
{ 0x0070, 0x0051, "US", "Displayed Area BRHC" },
{ 0x0070, 0x0060, "SQ", "Graphic Layer Sequence" },
{ 0x0070, 0x0062, "IS", "Graphic Layer Order" },
{ 0x0070, 0x0066, "US", "Graphic Layer Recommended Display Value" },
{ 0x0070, 0x0068, "LO", "Graphic Layer Description" },
{ 0x0070, 0x0080, "CS", "Presentation Label" },
{ 0x0070, 0x0081, "LO", "Presentation Description" },
{ 0x0070, 0x0082, "DA", "Presentation Creation Date" },
{ 0x0070, 0x0083, "TM", "Presentation Creation Time" },
{ 0x0070, 0x0084, "PN", "Presentation Creator's Name" },
{ 0x0070, 0x031a, "UI", "Fiducial UID" },
{ 0x0087, 0x0010, "CS", "Media Type" },
{ 0x0087, 0x0020, "CS", "Media Location" },
{ 0x0087, 0x0050, "IS", "Estimated Retrieve Time" },
{ 0x0088, 0x0000, "UL", "Storage Group Length" },
{ 0x0088, 0x0130, "SH", "Storage Media FileSet ID" },
{ 0x0088, 0x0140, "UI", "Storage Media FileSet UID" },
{ 0x0088, 0x0200, "SQ", "Icon Image Sequence" },
{ 0x0088, 0x0904, "LO", "Topic Title" },
{ 0x0088, 0x0906, "ST", "Topic Subject" },
{ 0x0088, 0x0910, "LO", "Topic Author" },
{ 0x0088, 0x0912, "LO", "Topic Key Words" },
{ 0x0095, 0x0001, "LT", "Examination Folder ID" },
{ 0x0095, 0x0004, "UL", "Folder Reported Status" },
{ 0x0095, 0x0005, "LT", "Folder Reporting Radiologist" },
{ 0x0095, 0x0007, "LT", "SIENET ISA PLA" },
{ 0x0099, 0x0002, "UL", "Data Object Attributes" },
{ 0x00e1, 0x0001, "US", "Data Dictionary Version" },
{ 0x00e1, 0x0014, "LT", "?" },
{ 0x00e1, 0x0022, "DS", "?" },
{ 0x00e1, 0x0023, "DS", "?" },
{ 0x00e1, 0x0024, "LT", "?" },
{ 0x00e1, 0x0025, "LT", "?" },
{ 0x00e1, 0x0040, "SH", "Offset From CT MR Images" },
{ 0x0193, 0x0002, "DS", "RIS Key" },
{ 0x0307, 0x0001, "UN", "RIS Worklist IMGEF" },
{ 0x0309, 0x0001, "UN", "RIS Report IMGEF" },
{ 0x0601, 0x0000, "SH", "Implementation Version" },
{ 0x0601, 0x0020, "DS", "Relative Table Position" },
{ 0x0601, 0x0021, "DS", "Relative Table Height" },
{ 0x0601, 0x0030, "SH", "Surview Direction" },
{ 0x0601, 0x0031, "DS", "Surview Length" },
{ 0x0601, 0x0050, "SH", "Image View Type" },
{ 0x0601, 0x0070, "DS", "Batch Number" },
{ 0x0601, 0x0071, "DS", "Batch Size" },
{ 0x0601, 0x0072, "DS", "Batch Slice Number" },
{ 0x1000, 0x0000, "xs", "?" },
{ 0x1000, 0x0001, "US", "Run Length Triplet" },
{ 0x1000, 0x0002, "US", "Huffman Table Size" },
{ 0x1000, 0x0003, "US", "Huffman Table Triplet" },
{ 0x1000, 0x0004, "US", "Shift Table Size" },
{ 0x1000, 0x0005, "US", "Shift Table Triplet" },
{ 0x1010, 0x0000, "xs", "?" },
{ 0x1369, 0x0000, "US", "?" },
{ 0x2000, 0x0000, "UL", "Film Session Group Length" },
{ 0x2000, 0x0010, "IS", "Number of Copies" },
{ 0x2000, 0x0020, "CS", "Print Priority" },
{ 0x2000, 0x0030, "CS", "Medium Type" },
{ 0x2000, 0x0040, "CS", "Film Destination" },
{ 0x2000, 0x0050, "LO", "Film Session Label" },
{ 0x2000, 0x0060, "IS", "Memory Allocation" },
{ 0x2000, 0x0500, "SQ", "Referenced Film Box Sequence" },
{ 0x2010, 0x0000, "UL", "Film Box Group Length" },
{ 0x2010, 0x0010, "ST", "Image Display Format" },
{ 0x2010, 0x0030, "CS", "Annotation Display Format ID" },
{ 0x2010, 0x0040, "CS", "Film Orientation" },
{ 0x2010, 0x0050, "CS", "Film Size ID" },
{ 0x2010, 0x0060, "CS", "Magnification Type" },
{ 0x2010, 0x0080, "CS", "Smoothing Type" },
{ 0x2010, 0x0100, "CS", "Border Density" },
{ 0x2010, 0x0110, "CS", "Empty Image Density" },
{ 0x2010, 0x0120, "US", "Min Density" },
{ 0x2010, 0x0130, "US", "Max Density" },
{ 0x2010, 0x0140, "CS", "Trim" },
{ 0x2010, 0x0150, "ST", "Configuration Information" },
{ 0x2010, 0x0500, "SQ", "Referenced Film Session Sequence" },
{ 0x2010, 0x0510, "SQ", "Referenced Image Box Sequence" },
{ 0x2010, 0x0520, "SQ", "Referenced Basic Annotation Box Sequence" },
{ 0x2020, 0x0000, "UL", "Image Box Group Length" },
{ 0x2020, 0x0010, "US", "Image Box Position" },
{ 0x2020, 0x0020, "CS", "Polarity" },
{ 0x2020, 0x0030, "DS", "Requested Image Size" },
{ 0x2020, 0x0110, "SQ", "Preformatted Grayscale Image Sequence" },
{ 0x2020, 0x0111, "SQ", "Preformatted Color Image Sequence" },
{ 0x2020, 0x0130, "SQ", "Referenced Image Overlay Box Sequence" },
{ 0x2020, 0x0140, "SQ", "Referenced VOI LUT Box Sequence" },
{ 0x2030, 0x0000, "UL", "Annotation Group Length" },
{ 0x2030, 0x0010, "US", "Annotation Position" },
{ 0x2030, 0x0020, "LO", "Text String" },
{ 0x2040, 0x0000, "UL", "Overlay Box Group Length" },
{ 0x2040, 0x0010, "SQ", "Referenced Overlay Plane Sequence" },
{ 0x2040, 0x0011, "US", "Referenced Overlay Plane Groups" },
{ 0x2040, 0x0060, "CS", "Overlay Magnification Type" },
{ 0x2040, 0x0070, "CS", "Overlay Smoothing Type" },
{ 0x2040, 0x0080, "CS", "Overlay Foreground Density" },
{ 0x2040, 0x0090, "CS", "Overlay Mode" },
{ 0x2040, 0x0100, "CS", "Threshold Density" },
{ 0x2040, 0x0500, "SQ", "Referenced Overlay Image Box Sequence" },
{ 0x2050, 0x0010, "SQ", "Presentation LUT Sequence" },
{ 0x2050, 0x0020, "CS", "Presentation LUT Shape" },
{ 0x2100, 0x0000, "UL", "Print Job Group Length" },
{ 0x2100, 0x0020, "CS", "Execution Status" },
{ 0x2100, 0x0030, "CS", "Execution Status Info" },
{ 0x2100, 0x0040, "DA", "Creation Date" },
{ 0x2100, 0x0050, "TM", "Creation Time" },
{ 0x2100, 0x0070, "AE", "Originator" },
{ 0x2100, 0x0500, "SQ", "Referenced Print Job Sequence" },
{ 0x2110, 0x0000, "UL", "Printer Group Length" },
{ 0x2110, 0x0010, "CS", "Printer Status" },
{ 0x2110, 0x0020, "CS", "Printer Status Info" },
{ 0x2110, 0x0030, "LO", "Printer Name" },
{ 0x2110, 0x0099, "SH", "Print Queue ID" },
{ 0x3002, 0x0002, "SH", "RT Image Label" },
{ 0x3002, 0x0003, "LO", "RT Image Name" },
{ 0x3002, 0x0004, "ST", "RT Image Description" },
{ 0x3002, 0x000a, "CS", "Reported Values Origin" },
{ 0x3002, 0x000c, "CS", "RT Image Plane" },
{ 0x3002, 0x000e, "DS", "X-Ray Image Receptor Angle" },
{ 0x3002, 0x0010, "DS", "RTImageOrientation" },
{ 0x3002, 0x0011, "DS", "Image Plane Pixel Spacing" },
{ 0x3002, 0x0012, "DS", "RT Image Position" },
{ 0x3002, 0x0020, "SH", "Radiation Machine Name" },
{ 0x3002, 0x0022, "DS", "Radiation Machine SAD" },
{ 0x3002, 0x0024, "DS", "Radiation Machine SSD" },
{ 0x3002, 0x0026, "DS", "RT Image SID" },
{ 0x3002, 0x0028, "DS", "Source to Reference Object Distance" },
{ 0x3002, 0x0029, "IS", "Fraction Number" },
{ 0x3002, 0x0030, "SQ", "Exposure Sequence" },
{ 0x3002, 0x0032, "DS", "Meterset Exposure" },
{ 0x3004, 0x0001, "CS", "DVH Type" },
{ 0x3004, 0x0002, "CS", "Dose Units" },
{ 0x3004, 0x0004, "CS", "Dose Type" },
{ 0x3004, 0x0006, "LO", "Dose Comment" },
{ 0x3004, 0x0008, "DS", "Normalization Point" },
{ 0x3004, 0x000a, "CS", "Dose Summation Type" },
{ 0x3004, 0x000c, "DS", "GridFrame Offset Vector" },
{ 0x3004, 0x000e, "DS", "Dose Grid Scaling" },
{ 0x3004, 0x0010, "SQ", "RT Dose ROI Sequence" },
{ 0x3004, 0x0012, "DS", "Dose Value" },
{ 0x3004, 0x0040, "DS", "DVH Normalization Point" },
{ 0x3004, 0x0042, "DS", "DVH Normalization Dose Value" },
{ 0x3004, 0x0050, "SQ", "DVH Sequence" },
{ 0x3004, 0x0052, "DS", "DVH Dose Scaling" },
{ 0x3004, 0x0054, "CS", "DVH Volume Units" },
{ 0x3004, 0x0056, "IS", "DVH Number of Bins" },
{ 0x3004, 0x0058, "DS", "DVH Data" },
{ 0x3004, 0x0060, "SQ", "DVH Referenced ROI Sequence" },
{ 0x3004, 0x0062, "CS", "DVH ROI Contribution Type" },
{ 0x3004, 0x0070, "DS", "DVH Minimum Dose" },
{ 0x3004, 0x0072, "DS", "DVH Maximum Dose" },
{ 0x3004, 0x0074, "DS", "DVH Mean Dose" },
{ 0x3006, 0x0002, "SH", "Structure Set Label" },
{ 0x3006, 0x0004, "LO", "Structure Set Name" },
{ 0x3006, 0x0006, "ST", "Structure Set Description" },
{ 0x3006, 0x0008, "DA", "Structure Set Date" },
{ 0x3006, 0x0009, "TM", "Structure Set Time" },
{ 0x3006, 0x0010, "SQ", "Referenced Frame of Reference Sequence" },
{ 0x3006, 0x0012, "SQ", "RT Referenced Study Sequence" },
{ 0x3006, 0x0014, "SQ", "RT Referenced Series Sequence" },
{ 0x3006, 0x0016, "SQ", "Contour Image Sequence" },
{ 0x3006, 0x0020, "SQ", "Structure Set ROI Sequence" },
{ 0x3006, 0x0022, "IS", "ROI Number" },
{ 0x3006, 0x0024, "UI", "Referenced Frame of Reference UID" },
{ 0x3006, 0x0026, "LO", "ROI Name" },
{ 0x3006, 0x0028, "ST", "ROI Description" },
{ 0x3006, 0x002a, "IS", "ROI Display Color" },
{ 0x3006, 0x002c, "DS", "ROI Volume" },
{ 0x3006, 0x0030, "SQ", "RT Related ROI Sequence" },
{ 0x3006, 0x0033, "CS", "RT ROI Relationship" },
{ 0x3006, 0x0036, "CS", "ROI Generation Algorithm" },
{ 0x3006, 0x0038, "LO", "ROI Generation Description" },
{ 0x3006, 0x0039, "SQ", "ROI Contour Sequence" },
{ 0x3006, 0x0040, "SQ", "Contour Sequence" },
{ 0x3006, 0x0042, "CS", "Contour Geometric Type" },
{ 0x3006, 0x0044, "DS", "Contour SlabT hickness" },
{ 0x3006, 0x0045, "DS", "Contour Offset Vector" },
{ 0x3006, 0x0046, "IS", "Number of Contour Points" },
{ 0x3006, 0x0050, "DS", "Contour Data" },
{ 0x3006, 0x0080, "SQ", "RT ROI Observations Sequence" },
{ 0x3006, 0x0082, "IS", "Observation Number" },
{ 0x3006, 0x0084, "IS", "Referenced ROI Number" },
{ 0x3006, 0x0085, "SH", "ROI Observation Label" },
{ 0x3006, 0x0086, "SQ", "RT ROI Identification Code Sequence" },
{ 0x3006, 0x0088, "ST", "ROI Observation Description" },
{ 0x3006, 0x00a0, "SQ", "Related RT ROI Observations Sequence" },
{ 0x3006, 0x00a4, "CS", "RT ROI Interpreted Type" },
{ 0x3006, 0x00a6, "PN", "ROI Interpreter" },
{ 0x3006, 0x00b0, "SQ", "ROI Physical Properties Sequence" },
{ 0x3006, 0x00b2, "CS", "ROI Physical Property" },
{ 0x3006, 0x00b4, "DS", "ROI Physical Property Value" },
{ 0x3006, 0x00c0, "SQ", "Frame of Reference Relationship Sequence" },
{ 0x3006, 0x00c2, "UI", "Related Frame of Reference UID" },
{ 0x3006, 0x00c4, "CS", "Frame of Reference Transformation Type" },
{ 0x3006, 0x00c6, "DS", "Frame of Reference Transformation Matrix" },
{ 0x3006, 0x00c8, "LO", "Frame of Reference Transformation Comment" },
{ 0x300a, 0x0002, "SH", "RT Plan Label" },
{ 0x300a, 0x0003, "LO", "RT Plan Name" },
{ 0x300a, 0x0004, "ST", "RT Plan Description" },
{ 0x300a, 0x0006, "DA", "RT Plan Date" },
{ 0x300a, 0x0007, "TM", "RT Plan Time" },
{ 0x300a, 0x0009, "LO", "Treatment Protocols" },
{ 0x300a, 0x000a, "CS", "Treatment Intent" },
{ 0x300a, 0x000b, "LO", "Treatment Sites" },
{ 0x300a, 0x000c, "CS", "RT Plan Geometry" },
{ 0x300a, 0x000e, "ST", "Prescription Description" },
{ 0x300a, 0x0010, "SQ", "Dose ReferenceSequence" },
{ 0x300a, 0x0012, "IS", "Dose ReferenceNumber" },
{ 0x300a, 0x0014, "CS", "Dose Reference Structure Type" },
{ 0x300a, 0x0016, "LO", "Dose ReferenceDescription" },
{ 0x300a, 0x0018, "DS", "Dose Reference Point Coordinates" },
{ 0x300a, 0x001a, "DS", "Nominal Prior Dose" },
{ 0x300a, 0x0020, "CS", "Dose Reference Type" },
{ 0x300a, 0x0021, "DS", "Constraint Weight" },
{ 0x300a, 0x0022, "DS", "Delivery Warning Dose" },
{ 0x300a, 0x0023, "DS", "Delivery Maximum Dose" },
{ 0x300a, 0x0025, "DS", "Target Minimum Dose" },
{ 0x300a, 0x0026, "DS", "Target Prescription Dose" },
{ 0x300a, 0x0027, "DS", "Target Maximum Dose" },
{ 0x300a, 0x0028, "DS", "Target Underdose Volume Fraction" },
{ 0x300a, 0x002a, "DS", "Organ at Risk Full-volume Dose" },
{ 0x300a, 0x002b, "DS", "Organ at Risk Limit Dose" },
{ 0x300a, 0x002c, "DS", "Organ at Risk Maximum Dose" },
{ 0x300a, 0x002d, "DS", "Organ at Risk Overdose Volume Fraction" },
{ 0x300a, 0x0040, "SQ", "Tolerance Table Sequence" },
{ 0x300a, 0x0042, "IS", "Tolerance Table Number" },
{ 0x300a, 0x0043, "SH", "Tolerance Table Label" },
{ 0x300a, 0x0044, "DS", "Gantry Angle Tolerance" },
{ 0x300a, 0x0046, "DS", "Beam Limiting Device Angle Tolerance" },
{ 0x300a, 0x0048, "SQ", "Beam Limiting Device Tolerance Sequence" },
{ 0x300a, 0x004a, "DS", "Beam Limiting Device Position Tolerance" },
{ 0x300a, 0x004c, "DS", "Patient Support Angle Tolerance" },
{ 0x300a, 0x004e, "DS", "Table Top Eccentric Angle Tolerance" },
{ 0x300a, 0x0051, "DS", "Table Top Vertical Position Tolerance" },
{ 0x300a, 0x0052, "DS", "Table Top Longitudinal Position Tolerance" },
{ 0x300a, 0x0053, "DS", "Table Top Lateral Position Tolerance" },
{ 0x300a, 0x0055, "CS", "RT Plan Relationship" },
{ 0x300a, 0x0070, "SQ", "Fraction Group Sequence" },
{ 0x300a, 0x0071, "IS", "Fraction Group Number" },
{ 0x300a, 0x0078, "IS", "Number of Fractions Planned" },
{ 0x300a, 0x0079, "IS", "Number of Fractions Per Day" },
{ 0x300a, 0x007a, "IS", "Repeat Fraction Cycle Length" },
{ 0x300a, 0x007b, "LT", "Fraction Pattern" },
{ 0x300a, 0x0080, "IS", "Number of Beams" },
{ 0x300a, 0x0082, "DS", "Beam Dose Specification Point" },
{ 0x300a, 0x0084, "DS", "Beam Dose" },
{ 0x300a, 0x0086, "DS", "Beam Meterset" },
{ 0x300a, 0x00a0, "IS", "Number of Brachy Application Setups" },
{ 0x300a, 0x00a2, "DS", "Brachy Application Setup Dose Specification Point" },
{ 0x300a, 0x00a4, "DS", "Brachy Application Setup Dose" },
{ 0x300a, 0x00b0, "SQ", "Beam Sequence" },
{ 0x300a, 0x00b2, "SH", "Treatment Machine Name " },
{ 0x300a, 0x00b3, "CS", "Primary Dosimeter Unit" },
{ 0x300a, 0x00b4, "DS", "Source-Axis Distance" },
{ 0x300a, 0x00b6, "SQ", "Beam Limiting Device Sequence" },
{ 0x300a, 0x00b8, "CS", "RT Beam Limiting Device Type" },
{ 0x300a, 0x00ba, "DS", "Source to Beam Limiting Device Distance" },
{ 0x300a, 0x00bc, "IS", "Number of Leaf/Jaw Pairs" },
{ 0x300a, 0x00be, "DS", "Leaf Position Boundaries" },
{ 0x300a, 0x00c0, "IS", "Beam Number" },
{ 0x300a, 0x00c2, "LO", "Beam Name" },
{ 0x300a, 0x00c3, "ST", "Beam Description" },
{ 0x300a, 0x00c4, "CS", "Beam Type" },
{ 0x300a, 0x00c6, "CS", "Radiation Type" },
{ 0x300a, 0x00c8, "IS", "Reference Image Number" },
{ 0x300a, 0x00ca, "SQ", "Planned Verification Image Sequence" },
{ 0x300a, 0x00cc, "LO", "Imaging Device Specific Acquisition Parameters" },
{ 0x300a, 0x00ce, "CS", "Treatment Delivery Type" },
{ 0x300a, 0x00d0, "IS", "Number of Wedges" },
{ 0x300a, 0x00d1, "SQ", "Wedge Sequence" },
{ 0x300a, 0x00d2, "IS", "Wedge Number" },
{ 0x300a, 0x00d3, "CS", "Wedge Type" },
{ 0x300a, 0x00d4, "SH", "Wedge ID" },
{ 0x300a, 0x00d5, "IS", "Wedge Angle" },
{ 0x300a, 0x00d6, "DS", "Wedge Factor" },
{ 0x300a, 0x00d8, "DS", "Wedge Orientation" },
{ 0x300a, 0x00da, "DS", "Source to Wedge Tray Distance" },
{ 0x300a, 0x00e0, "IS", "Number of Compensators" },
{ 0x300a, 0x00e1, "SH", "Material ID" },
{ 0x300a, 0x00e2, "DS", "Total Compensator Tray Factor" },
{ 0x300a, 0x00e3, "SQ", "Compensator Sequence" },
{ 0x300a, 0x00e4, "IS", "Compensator Number" },
{ 0x300a, 0x00e5, "SH", "Compensator ID" },
{ 0x300a, 0x00e6, "DS", "Source to Compensator Tray Distance" },
{ 0x300a, 0x00e7, "IS", "Compensator Rows" },
{ 0x300a, 0x00e8, "IS", "Compensator Columns" },
{ 0x300a, 0x00e9, "DS", "Compensator Pixel Spacing" },
{ 0x300a, 0x00ea, "DS", "Compensator Position" },
{ 0x300a, 0x00eb, "DS", "Compensator Transmission Data" },
{ 0x300a, 0x00ec, "DS", "Compensator Thickness Data" },
{ 0x300a, 0x00ed, "IS", "Number of Boli" },
{ 0x300a, 0x00f0, "IS", "Number of Blocks" },
{ 0x300a, 0x00f2, "DS", "Total Block Tray Factor" },
{ 0x300a, 0x00f4, "SQ", "Block Sequence" },
{ 0x300a, 0x00f5, "SH", "Block Tray ID" },
{ 0x300a, 0x00f6, "DS", "Source to Block Tray Distance" },
{ 0x300a, 0x00f8, "CS", "Block Type" },
{ 0x300a, 0x00fa, "CS", "Block Divergence" },
{ 0x300a, 0x00fc, "IS", "Block Number" },
{ 0x300a, 0x00fe, "LO", "Block Name" },
{ 0x300a, 0x0100, "DS", "Block Thickness" },
{ 0x300a, 0x0102, "DS", "Block Transmission" },
{ 0x300a, 0x0104, "IS", "Block Number of Points" },
{ 0x300a, 0x0106, "DS", "Block Data" },
{ 0x300a, 0x0107, "SQ", "Applicator Sequence" },
{ 0x300a, 0x0108, "SH", "Applicator ID" },
{ 0x300a, 0x0109, "CS", "Applicator Type" },
{ 0x300a, 0x010a, "LO", "Applicator Description" },
{ 0x300a, 0x010c, "DS", "Cumulative Dose Reference Coefficient" },
{ 0x300a, 0x010e, "DS", "Final Cumulative Meterset Weight" },
{ 0x300a, 0x0110, "IS", "Number of Control Points" },
{ 0x300a, 0x0111, "SQ", "Control Point Sequence" },
{ 0x300a, 0x0112, "IS", "Control Point Index" },
{ 0x300a, 0x0114, "DS", "Nominal Beam Energy" },
{ 0x300a, 0x0115, "DS", "Dose Rate Set" },
{ 0x300a, 0x0116, "SQ", "Wedge Position Sequence" },
{ 0x300a, 0x0118, "CS", "Wedge Position" },
{ 0x300a, 0x011a, "SQ", "Beam Limiting Device Position Sequence" },
{ 0x300a, 0x011c, "DS", "Leaf Jaw Positions" },
{ 0x300a, 0x011e, "DS", "Gantry Angle" },
{ 0x300a, 0x011f, "CS", "Gantry Rotation Direction" },
{ 0x300a, 0x0120, "DS", "Beam Limiting Device Angle" },
{ 0x300a, 0x0121, "CS", "Beam Limiting Device Rotation Direction" },
{ 0x300a, 0x0122, "DS", "Patient Support Angle" },
{ 0x300a, 0x0123, "CS", "Patient Support Rotation Direction" },
{ 0x300a, 0x0124, "DS", "Table Top Eccentric Axis Distance" },
{ 0x300a, 0x0125, "DS", "Table Top Eccentric Angle" },
{ 0x300a, 0x0126, "CS", "Table Top Eccentric Rotation Direction" },
{ 0x300a, 0x0128, "DS", "Table Top Vertical Position" },
{ 0x300a, 0x0129, "DS", "Table Top Longitudinal Position" },
{ 0x300a, 0x012a, "DS", "Table Top Lateral Position" },
{ 0x300a, 0x012c, "DS", "Isocenter Position" },
{ 0x300a, 0x012e, "DS", "Surface Entry Point" },
{ 0x300a, 0x0130, "DS", "Source to Surface Distance" },
{ 0x300a, 0x0134, "DS", "Cumulative Meterset Weight" },
{ 0x300a, 0x0180, "SQ", "Patient Setup Sequence" },
{ 0x300a, 0x0182, "IS", "Patient Setup Number" },
{ 0x300a, 0x0184, "LO", "Patient Additional Position" },
{ 0x300a, 0x0190, "SQ", "Fixation Device Sequence" },
{ 0x300a, 0x0192, "CS", "Fixation Device Type" },
{ 0x300a, 0x0194, "SH", "Fixation Device Label" },
{ 0x300a, 0x0196, "ST", "Fixation Device Description" },
{ 0x300a, 0x0198, "SH", "Fixation Device Position" },
{ 0x300a, 0x01a0, "SQ", "Shielding Device Sequence" },
{ 0x300a, 0x01a2, "CS", "Shielding Device Type" },
{ 0x300a, 0x01a4, "SH", "Shielding Device Label" },
{ 0x300a, 0x01a6, "ST", "Shielding Device Description" },
{ 0x300a, 0x01a8, "SH", "Shielding Device Position" },
{ 0x300a, 0x01b0, "CS", "Setup Technique" },
{ 0x300a, 0x01b2, "ST", "Setup TechniqueDescription" },
{ 0x300a, 0x01b4, "SQ", "Setup Device Sequence" },
{ 0x300a, 0x01b6, "CS", "Setup Device Type" },
{ 0x300a, 0x01b8, "SH", "Setup Device Label" },
{ 0x300a, 0x01ba, "ST", "Setup Device Description" },
{ 0x300a, 0x01bc, "DS", "Setup Device Parameter" },
{ 0x300a, 0x01d0, "ST", "Setup ReferenceDescription" },
{ 0x300a, 0x01d2, "DS", "Table Top Vertical Setup Displacement" },
{ 0x300a, 0x01d4, "DS", "Table Top Longitudinal Setup Displacement" },
{ 0x300a, 0x01d6, "DS", "Table Top Lateral Setup Displacement" },
{ 0x300a, 0x0200, "CS", "Brachy Treatment Technique" },
{ 0x300a, 0x0202, "CS", "Brachy Treatment Type" },
{ 0x300a, 0x0206, "SQ", "Treatment Machine Sequence" },
{ 0x300a, 0x0210, "SQ", "Source Sequence" },
{ 0x300a, 0x0212, "IS", "Source Number" },
{ 0x300a, 0x0214, "CS", "Source Type" },
{ 0x300a, 0x0216, "LO", "Source Manufacturer" },
{ 0x300a, 0x0218, "DS", "Active Source Diameter" },
{ 0x300a, 0x021a, "DS", "Active Source Length" },
{ 0x300a, 0x0222, "DS", "Source Encapsulation Nominal Thickness" },
{ 0x300a, 0x0224, "DS", "Source Encapsulation Nominal Transmission" },
{ 0x300a, 0x0226, "LO", "Source IsotopeName" },
{ 0x300a, 0x0228, "DS", "Source Isotope Half Life" },
{ 0x300a, 0x022a, "DS", "Reference Air Kerma Rate" },
{ 0x300a, 0x022c, "DA", "Air Kerma Rate Reference Date" },
{ 0x300a, 0x022e, "TM", "Air Kerma Rate Reference Time" },
{ 0x300a, 0x0230, "SQ", "Application Setup Sequence" },
{ 0x300a, 0x0232, "CS", "Application Setup Type" },
{ 0x300a, 0x0234, "IS", "Application Setup Number" },
{ 0x300a, 0x0236, "LO", "Application Setup Name" },
{ 0x300a, 0x0238, "LO", "Application Setup Manufacturer" },
{ 0x300a, 0x0240, "IS", "Template Number" },
{ 0x300a, 0x0242, "SH", "Template Type" },
{ 0x300a, 0x0244, "LO", "Template Name" },
{ 0x300a, 0x0250, "DS", "Total Reference Air Kerma" },
{ 0x300a, 0x0260, "SQ", "Brachy Accessory Device Sequence" },
{ 0x300a, 0x0262, "IS", "Brachy Accessory Device Number" },
{ 0x300a, 0x0263, "SH", "Brachy Accessory Device ID" },
{ 0x300a, 0x0264, "CS", "Brachy Accessory Device Type" },
{ 0x300a, 0x0266, "LO", "Brachy Accessory Device Name" },
{ 0x300a, 0x026a, "DS", "Brachy Accessory Device Nominal Thickness" },
{ 0x300a, 0x026c, "DS", "Brachy Accessory Device Nominal Transmission" },
{ 0x300a, 0x0280, "SQ", "Channel Sequence" },
{ 0x300a, 0x0282, "IS", "Channel Number" },
{ 0x300a, 0x0284, "DS", "Channel Length" },
{ 0x300a, 0x0286, "DS", "Channel Total Time" },
{ 0x300a, 0x0288, "CS", "Source Movement Type" },
{ 0x300a, 0x028a, "IS", "Number of Pulses" },
{ 0x300a, 0x028c, "DS", "Pulse Repetition Interval" },
{ 0x300a, 0x0290, "IS", "Source Applicator Number" },
{ 0x300a, 0x0291, "SH", "Source Applicator ID" },
{ 0x300a, 0x0292, "CS", "Source Applicator Type" },
{ 0x300a, 0x0294, "LO", "Source Applicator Name" },
{ 0x300a, 0x0296, "DS", "Source Applicator Length" },
{ 0x300a, 0x0298, "LO", "Source Applicator Manufacturer" },
{ 0x300a, 0x029c, "DS", "Source Applicator Wall Nominal Thickness" },
{ 0x300a, 0x029e, "DS", "Source Applicator Wall Nominal Transmission" },
{ 0x300a, 0x02a0, "DS", "Source Applicator Step Size" },
{ 0x300a, 0x02a2, "IS", "Transfer Tube Number" },
{ 0x300a, 0x02a4, "DS", "Transfer Tube Length" },
{ 0x300a, 0x02b0, "SQ", "Channel Shield Sequence" },
{ 0x300a, 0x02b2, "IS", "Channel Shield Number" },
{ 0x300a, 0x02b3, "SH", "Channel Shield ID" },
{ 0x300a, 0x02b4, "LO", "Channel Shield Name" },
{ 0x300a, 0x02b8, "DS", "Channel Shield Nominal Thickness" },
{ 0x300a, 0x02ba, "DS", "Channel Shield Nominal Transmission" },
{ 0x300a, 0x02c8, "DS", "Final Cumulative Time Weight" },
{ 0x300a, 0x02d0, "SQ", "Brachy Control Point Sequence" },
{ 0x300a, 0x02d2, "DS", "Control Point Relative Position" },
{ 0x300a, 0x02d4, "DS", "Control Point 3D Position" },
{ 0x300a, 0x02d6, "DS", "Cumulative Time Weight" },
{ 0x300c, 0x0002, "SQ", "Referenced RT Plan Sequence" },
{ 0x300c, 0x0004, "SQ", "Referenced Beam Sequence" },
{ 0x300c, 0x0006, "IS", "Referenced Beam Number" },
{ 0x300c, 0x0007, "IS", "Referenced Reference Image Number" },
{ 0x300c, 0x0008, "DS", "Start Cumulative Meterset Weight" },
{ 0x300c, 0x0009, "DS", "End Cumulative Meterset Weight" },
{ 0x300c, 0x000a, "SQ", "Referenced Brachy Application Setup Sequence" },
{ 0x300c, 0x000c, "IS", "Referenced Brachy Application Setup Number" },
{ 0x300c, 0x000e, "IS", "Referenced Source Number" },
{ 0x300c, 0x0020, "SQ", "Referenced Fraction Group Sequence" },
{ 0x300c, 0x0022, "IS", "Referenced Fraction Group Number" },
{ 0x300c, 0x0040, "SQ", "Referenced Verification Image Sequence" },
{ 0x300c, 0x0042, "SQ", "Referenced Reference Image Sequence" },
{ 0x300c, 0x0050, "SQ", "Referenced Dose Reference Sequence" },
{ 0x300c, 0x0051, "IS", "Referenced Dose Reference Number" },
{ 0x300c, 0x0055, "SQ", "Brachy Referenced Dose Reference Sequence" },
{ 0x300c, 0x0060, "SQ", "Referenced Structure Set Sequence" },
{ 0x300c, 0x006a, "IS", "Referenced Patient Setup Number" },
{ 0x300c, 0x0080, "SQ", "Referenced Dose Sequence" },
{ 0x300c, 0x00a0, "IS", "Referenced Tolerance Table Number" },
{ 0x300c, 0x00b0, "SQ", "Referenced Bolus Sequence" },
{ 0x300c, 0x00c0, "IS", "Referenced Wedge Number" },
{ 0x300c, 0x00d0, "IS", "Referenced Compensato rNumber" },
{ 0x300c, 0x00e0, "IS", "Referenced Block Number" },
{ 0x300c, 0x00f0, "IS", "Referenced Control Point" },
{ 0x300e, 0x0002, "CS", "Approval Status" },
{ 0x300e, 0x0004, "DA", "Review Date" },
{ 0x300e, 0x0005, "TM", "Review Time" },
{ 0x300e, 0x0008, "PN", "Reviewer Name" },
{ 0x4000, 0x0000, "UL", "Text Group Length" },
{ 0x4000, 0x0010, "LT", "Text Arbitrary" },
{ 0x4000, 0x4000, "LT", "Text Comments" },
{ 0x4008, 0x0000, "UL", "Results Group Length" },
{ 0x4008, 0x0040, "SH", "Results ID" },
{ 0x4008, 0x0042, "LO", "Results ID Issuer" },
{ 0x4008, 0x0050, "SQ", "Referenced Interpretation Sequence" },
{ 0x4008, 0x00ff, "CS", "Report Production Status" },
{ 0x4008, 0x0100, "DA", "Interpretation Recorded Date" },
{ 0x4008, 0x0101, "TM", "Interpretation Recorded Time" },
{ 0x4008, 0x0102, "PN", "Interpretation Recorder" },
{ 0x4008, 0x0103, "LO", "Reference to Recorded Sound" },
{ 0x4008, 0x0108, "DA", "Interpretation Transcription Date" },
{ 0x4008, 0x0109, "TM", "Interpretation Transcription Time" },
{ 0x4008, 0x010a, "PN", "Interpretation Transcriber" },
{ 0x4008, 0x010b, "ST", "Interpretation Text" },
{ 0x4008, 0x010c, "PN", "Interpretation Author" },
{ 0x4008, 0x0111, "SQ", "Interpretation Approver Sequence" },
{ 0x4008, 0x0112, "DA", "Interpretation Approval Date" },
{ 0x4008, 0x0113, "TM", "Interpretation Approval Time" },
{ 0x4008, 0x0114, "PN", "Physician Approving Interpretation" },
{ 0x4008, 0x0115, "LT", "Interpretation Diagnosis Description" },
{ 0x4008, 0x0117, "SQ", "InterpretationDiagnosis Code Sequence" },
{ 0x4008, 0x0118, "SQ", "Results Distribution List Sequence" },
{ 0x4008, 0x0119, "PN", "Distribution Name" },
{ 0x4008, 0x011a, "LO", "Distribution Address" },
{ 0x4008, 0x0200, "SH", "Interpretation ID" },
{ 0x4008, 0x0202, "LO", "Interpretation ID Issuer" },
{ 0x4008, 0x0210, "CS", "Interpretation Type ID" },
{ 0x4008, 0x0212, "CS", "Interpretation Status ID" },
{ 0x4008, 0x0300, "ST", "Impressions" },
{ 0x4008, 0x4000, "ST", "Results Comments" },
{ 0x4009, 0x0001, "LT", "Report ID" },
{ 0x4009, 0x0020, "LT", "Report Status" },
{ 0x4009, 0x0030, "DA", "Report Creation Date" },
{ 0x4009, 0x0070, "LT", "Report Approving Physician" },
{ 0x4009, 0x00e0, "LT", "Report Text" },
{ 0x4009, 0x00e1, "LT", "Report Author" },
{ 0x4009, 0x00e3, "LT", "Reporting Radiologist" },
{ 0x5000, 0x0000, "UL", "Curve Group Length" },
{ 0x5000, 0x0005, "US", "Curve Dimensions" },
{ 0x5000, 0x0010, "US", "Number of Points" },
{ 0x5000, 0x0020, "CS", "Type of Data" },
{ 0x5000, 0x0022, "LO", "Curve Description" },
{ 0x5000, 0x0030, "SH", "Axis Units" },
{ 0x5000, 0x0040, "SH", "Axis Labels" },
{ 0x5000, 0x0103, "US", "Data Value Representation" },
{ 0x5000, 0x0104, "US", "Minimum Coordinate Value" },
{ 0x5000, 0x0105, "US", "Maximum Coordinate Value" },
{ 0x5000, 0x0106, "SH", "Curve Range" },
{ 0x5000, 0x0110, "US", "Curve Data Descriptor" },
{ 0x5000, 0x0112, "US", "Coordinate Start Value" },
{ 0x5000, 0x0114, "US", "Coordinate Step Value" },
{ 0x5000, 0x1001, "CS", "Curve Activation Layer" },
{ 0x5000, 0x2000, "US", "Audio Type" },
{ 0x5000, 0x2002, "US", "Audio Sample Format" },
{ 0x5000, 0x2004, "US", "Number of Channels" },
{ 0x5000, 0x2006, "UL", "Number of Samples" },
{ 0x5000, 0x2008, "UL", "Sample Rate" },
{ 0x5000, 0x200a, "UL", "Total Time" },
{ 0x5000, 0x200c, "xs", "Audio Sample Data" },
{ 0x5000, 0x200e, "LT", "Audio Comments" },
{ 0x5000, 0x2500, "LO", "Curve Label" },
{ 0x5000, 0x2600, "SQ", "CurveReferenced Overlay Sequence" },
{ 0x5000, 0x2610, "US", "CurveReferenced Overlay Group" },
{ 0x5000, 0x3000, "OW", "Curve Data" },
{ 0x6000, 0x0000, "UL", "Overlay Group Length" },
{ 0x6000, 0x0001, "US", "Gray Palette Color Lookup Table Descriptor" },
{ 0x6000, 0x0002, "US", "Gray Palette Color Lookup Table Data" },
{ 0x6000, 0x0010, "US", "Overlay Rows" },
{ 0x6000, 0x0011, "US", "Overlay Columns" },
{ 0x6000, 0x0012, "US", "Overlay Planes" },
{ 0x6000, 0x0015, "IS", "Number of Frames in Overlay" },
{ 0x6000, 0x0022, "LO", "Overlay Description" },
{ 0x6000, 0x0040, "CS", "Overlay Type" },
{ 0x6000, 0x0045, "CS", "Overlay Subtype" },
{ 0x6000, 0x0050, "SS", "Overlay Origin" },
{ 0x6000, 0x0051, "US", "Image Frame Origin" },
{ 0x6000, 0x0052, "US", "Plane Origin" },
{ 0x6000, 0x0060, "LO", "Overlay Compression Code" },
{ 0x6000, 0x0061, "SH", "Overlay Compression Originator" },
{ 0x6000, 0x0062, "SH", "Overlay Compression Label" },
{ 0x6000, 0x0063, "SH", "Overlay Compression Description" },
{ 0x6000, 0x0066, "AT", "Overlay Compression Step Pointers" },
{ 0x6000, 0x0068, "US", "Overlay Repeat Interval" },
{ 0x6000, 0x0069, "US", "Overlay Bits Grouped" },
{ 0x6000, 0x0100, "US", "Overlay Bits Allocated" },
{ 0x6000, 0x0102, "US", "Overlay Bit Position" },
{ 0x6000, 0x0110, "LO", "Overlay Format" },
{ 0x6000, 0x0200, "xs", "Overlay Location" },
{ 0x6000, 0x0800, "LO", "Overlay Code Label" },
{ 0x6000, 0x0802, "US", "Overlay Number of Tables" },
{ 0x6000, 0x0803, "AT", "Overlay Code Table Location" },
{ 0x6000, 0x0804, "US", "Overlay Bits For Code Word" },
{ 0x6000, 0x1001, "CS", "Overlay Activation Layer" },
{ 0x6000, 0x1100, "US", "Overlay Descriptor - Gray" },
{ 0x6000, 0x1101, "US", "Overlay Descriptor - Red" },
{ 0x6000, 0x1102, "US", "Overlay Descriptor - Green" },
{ 0x6000, 0x1103, "US", "Overlay Descriptor - Blue" },
{ 0x6000, 0x1200, "US", "Overlays - Gray" },
{ 0x6000, 0x1201, "US", "Overlays - Red" },
{ 0x6000, 0x1202, "US", "Overlays - Green" },
{ 0x6000, 0x1203, "US", "Overlays - Blue" },
{ 0x6000, 0x1301, "IS", "ROI Area" },
{ 0x6000, 0x1302, "DS", "ROI Mean" },
{ 0x6000, 0x1303, "DS", "ROI Standard Deviation" },
{ 0x6000, 0x1500, "LO", "Overlay Label" },
{ 0x6000, 0x3000, "OW", "Overlay Data" },
{ 0x6000, 0x4000, "LT", "Overlay Comments" },
{ 0x6001, 0x0000, "UN", "?" },
{ 0x6001, 0x0010, "LO", "?" },
{ 0x6001, 0x1010, "xs", "?" },
{ 0x6001, 0x1030, "xs", "?" },
{ 0x6021, 0x0000, "xs", "?" },
{ 0x6021, 0x0010, "xs", "?" },
{ 0x7001, 0x0010, "LT", "Dummy" },
{ 0x7003, 0x0010, "LT", "Info" },
{ 0x7005, 0x0010, "LT", "Dummy" },
{ 0x7000, 0x0004, "ST", "TextAnnotation" },
{ 0x7000, 0x0005, "IS", "Box" },
{ 0x7000, 0x0007, "IS", "ArrowEnd" },
{ 0x7001, 0x0001, "SL", "Private Group Length To End" },
{ 0x7001, 0x0002, "OB", "Unknown" },
{ 0x7001, 0x0011, "SL", "Private Creator" },
{ 0x7001, 0x0021, "SL", "Private Creator" },
{ 0x7001, 0x0022, "SQ", "Private Creator" },
{ 0x7001, 0x0041, "SL", "Private Creator" },
{ 0x7001, 0x0042, "SL", "Private Creator" },
{ 0x7001, 0x0051, "SL", "Private Creator" },
{ 0x7001, 0x0052, "SL", "Private Creator" },
{ 0x7001, 0x0075, "SL", "Private Creator" },
{ 0x7001, 0x0076, "SL", "Private Creator" },
{ 0x7001, 0x0077, "OB", "Private Creator" },
{ 0x7001, 0x0101, "SL", "Unknown" },
{ 0x7001, 0x0121, "SL", "Unknown" },
{ 0x7001, 0x0122, "SQ", "Unknown" },
{ 0x7fe0, 0x0000, "UL", "Pixel Data Group Length" },
{ 0x7fe0, 0x0010, "xs", "Pixel Data" },
{ 0x7fe0, 0x0020, "OW", "Coefficients SDVN" },
{ 0x7fe0, 0x0030, "OW", "Coefficients SDHN" },
{ 0x7fe0, 0x0040, "OW", "Coefficients SDDN" },
{ 0x7fe1, 0x0010, "xs", "Pixel Data" },
{ 0x7f00, 0x0000, "UL", "Variable Pixel Data Group Length" },
{ 0x7f00, 0x0010, "xs", "Variable Pixel Data" },
{ 0x7f00, 0x0011, "US", "Variable Next Data Group" },
{ 0x7f00, 0x0020, "OW", "Variable Coefficients SDVN" },
{ 0x7f00, 0x0030, "OW", "Variable Coefficients SDHN" },
{ 0x7f00, 0x0040, "OW", "Variable Coefficients SDDN" },
{ 0x7fe1, 0x0000, "OB", "Binary Data" },
{ 0x7fe3, 0x0000, "LT", "Image Graphics Format Code" },
{ 0x7fe3, 0x0010, "OB", "Image Graphics" },
{ 0x7fe3, 0x0020, "OB", "Image Graphics Dummy" },
{ 0x7ff1, 0x0001, "US", "?" },
{ 0x7ff1, 0x0002, "US", "?" },
{ 0x7ff1, 0x0003, "xs", "?" },
{ 0x7ff1, 0x0004, "IS", "?" },
{ 0x7ff1, 0x0005, "US", "?" },
{ 0x7ff1, 0x0007, "US", "?" },
{ 0x7ff1, 0x0008, "US", "?" },
{ 0x7ff1, 0x0009, "US", "?" },
{ 0x7ff1, 0x000a, "LT", "?" },
{ 0x7ff1, 0x000b, "US", "?" },
{ 0x7ff1, 0x000c, "US", "?" },
{ 0x7ff1, 0x000d, "US", "?" },
{ 0x7ff1, 0x0010, "US", "?" },
{ 0xfffc, 0xfffc, "OB", "Data Set Trailing Padding" },
{ 0xfffe, 0xe000, "!!", "Item" },
{ 0xfffe, 0xe00d, "!!", "Item Delimitation Item" },
{ 0xfffe, 0xe0dd, "!!", "Sequence Delimitation Item" },
{ 0xffff, 0xffff, "xs", (char *) NULL }
};
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D C M %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDCM() returns MagickTrue if the image format type, identified by the
% magick string, is DCM.
%
% The format of the IsDCM method is:
%
% MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDCM(const unsigned char *magick,const size_t length)
{
if (length < 132)
return(MagickFalse);
if (LocaleNCompare((char *) (magick+128),"DICM",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDCMImage() reads a Digital Imaging and Communications in Medicine
% (DICOM) file and returns it. It allocates the memory necessary for the
% new Image structure and returns a pointer to the new image.
%
% The format of the ReadDCMImage method is:
%
% Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
typedef struct _DCMInfo
{
MagickBooleanType
polarity;
Quantum
*scale;
size_t
bits_allocated,
bytes_per_pixel,
depth,
mask,
max_value,
samples_per_pixel,
signed_data,
significant_bits;
MagickBooleanType
rescale;
double
rescale_intercept,
rescale_slope,
window_center,
window_width;
} DCMInfo;
typedef struct _DCMStreamInfo
{
size_t
remaining,
segment_count;
ssize_t
segments[15];
size_t
offset_count;
ssize_t
*offsets;
ssize_t
count;
int
byte;
} DCMStreamInfo;
static int ReadDCMByte(DCMStreamInfo *stream_info,Image *image)
{
if (image->compression != RLECompression)
return(ReadBlobByte(image));
if (stream_info->count == 0)
{
int
byte;
ssize_t
count;
if (stream_info->remaining <= 2)
stream_info->remaining=0;
else
stream_info->remaining-=2;
count=(ssize_t) ReadBlobByte(image);
byte=ReadBlobByte(image);
if (count == 128)
return(0);
else
if (count < 128)
{
/*
Literal bytes.
*/
stream_info->count=count;
stream_info->byte=(-1);
return(byte);
}
else
{
/*
Repeated bytes.
*/
stream_info->count=256-count;
stream_info->byte=byte;
return(byte);
}
}
stream_info->count--;
if (stream_info->byte >= 0)
return(stream_info->byte);
if (stream_info->remaining > 0)
stream_info->remaining--;
return(ReadBlobByte(image));
}
static unsigned short ReadDCMShort(DCMStreamInfo *stream_info,Image *image)
{
int
shift,
byte;
unsigned short
value;
if (image->compression != RLECompression)
return(ReadBlobLSBShort(image));
shift=image->depth < 16 ? 4 : 8;
value=(unsigned short) ReadDCMByte(stream_info,image);
byte=ReadDCMByte(stream_info,image);
if (byte < 0)
return(0);
value|=(unsigned short) (byte << shift);
return(value);
}
static signed short ReadDCMSignedShort(DCMStreamInfo *stream_info,Image *image)
{
union
{
unsigned short
unsigned_value;
signed short
signed_value;
} quantum;
quantum.unsigned_value=ReadDCMShort(stream_info,image);
return(quantum.signed_value);
}
static MagickBooleanType ReadDCMPixels(Image *image,DCMInfo *info,
DCMStreamInfo *stream_info,MagickBooleanType first_segment,
ExceptionInfo *exception)
{
int
byte,
index;
MagickBooleanType
status;
PixelPacket
pixel;
register ssize_t
i,
x;
register Quantum
*q;
ssize_t
y;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
status=MagickTrue;
(void) memset(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (info->samples_per_pixel == 1)
{
int
pixel_value;
if (info->bytes_per_pixel == 1)
pixel_value=info->polarity != MagickFalse ?
((int) info->max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((info->bits_allocated != 12) || (info->significant_bits != 12))
{
if (info->signed_data)
pixel_value=ReadDCMSignedShort(stream_info,image);
else
pixel_value=(int) ReadDCMShort(stream_info,image);
if (info->polarity != MagickFalse)
pixel_value=(int)info->max_value-pixel_value;
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMSignedShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
if (info->signed_data == 1)
pixel_value-=32767;
index=pixel_value;
if (info->rescale != MagickFalse)
{
double
scaled_value;
scaled_value=pixel_value*info->rescale_slope+
info->rescale_intercept;
index=(int) scaled_value;
if (info->window_width != 0)
{
double
window_max,
window_min;
window_min=ceil(info->window_center-
(info->window_width-1.0)/2.0-0.5);
window_max=floor(info->window_center+
(info->window_width-1.0)/2.0+0.5);
if (scaled_value <= window_min)
index=0;
else
if (scaled_value > window_max)
index=(int) info->max_value;
else
index=(int) (info->max_value*(((scaled_value-
info->window_center-0.5)/(info->window_width-1))+0.5));
}
}
index&=info->mask;
index=(int) ConstrainColormapIndex(image,(ssize_t) index,exception);
if (first_segment)
SetPixelIndex(image,(Quantum) index,q);
else
SetPixelIndex(image,(Quantum) (((size_t) index) |
(((size_t) GetPixelIndex(image,q)) << 8)),q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (info->bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=info->mask;
pixel.green&=info->mask;
pixel.blue&=info->mask;
if (info->scale != (Quantum *) NULL)
{
if ((MagickSizeType) pixel.red <= GetQuantumRange(info->depth))
pixel.red=info->scale[pixel.red];
if ((MagickSizeType) pixel.green <= GetQuantumRange(info->depth))
pixel.green=info->scale[pixel.green];
if ((MagickSizeType) pixel.blue <= GetQuantumRange(info->depth))
pixel.blue=info->scale[pixel.blue];
}
}
if (first_segment != MagickFalse)
{
SetPixelRed(image,(Quantum) pixel.red,q);
SetPixelGreen(image,(Quantum) pixel.green,q);
SetPixelBlue(image,(Quantum) pixel.blue,q);
}
else
{
SetPixelRed(image,(Quantum) (((size_t) pixel.red) |
(((size_t) GetPixelRed(image,q)) << 8)),q);
SetPixelGreen(image,(Quantum) (((size_t) pixel.green) |
(((size_t) GetPixelGreen(image,q)) << 8)),q);
SetPixelBlue(image,(Quantum) (((size_t) pixel.blue) |
(((size_t) GetPixelBlue(image,q)) << 8)),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
return(status);
}
static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowDCMException(exception,message) \
{ \
if (info.scale != (Quantum *) NULL) \
info.scale=(Quantum *) RelinquishMagickMemory(info.scale); \
if (data != (unsigned char *) NULL) \
data=(unsigned char *) RelinquishMagickMemory(data); \
if (graymap != (int *) NULL) \
graymap=(int *) RelinquishMagickMemory(graymap); \
if (bluemap != (int *) NULL) \
bluemap=(int *) RelinquishMagickMemory(bluemap); \
if (greenmap != (int *) NULL) \
greenmap=(int *) RelinquishMagickMemory(greenmap); \
if (redmap != (int *) NULL) \
redmap=(int *) RelinquishMagickMemory(redmap); \
if (stream_info->offsets != (ssize_t *) NULL) \
stream_info->offsets=(ssize_t *) RelinquishMagickMemory( \
stream_info->offsets); \
if (stream_info != (DCMStreamInfo *) NULL) \
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info); \
ThrowReaderException((exception),(message)); \
}
char
explicit_vr[MagickPathExtent],
implicit_vr[MagickPathExtent],
magick[MagickPathExtent],
photometric[MagickPathExtent];
DCMInfo
info;
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
use_explicit;
MagickOffsetType
offset;
register unsigned char
*p;
register ssize_t
i;
size_t
colors,
height,
length,
number_scenes,
quantum,
status,
width;
ssize_t
count,
scene;
unsigned char
*data;
unsigned short
group,
element;
/*
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);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
(void) memset(&info,0,sizeof(info));
data=(unsigned char *) NULL;
graymap=(int *) NULL;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent);
info.bits_allocated=8;
info.bytes_per_pixel=1;
info.depth=8;
info.mask=0xffff;
info.max_value=255UL;
info.samples_per_pixel=1;
info.signed_data=(~0UL);
info.rescale_slope=1.0;
data=(unsigned char *) NULL;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
number_scenes=1;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
while (TellBlob(image) < (MagickOffsetType) GetBlobSize(image))
{
for (group=0; (group != 0x7FE0) || (element != 0x0010) ; )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group == 0xfffc) && (element == 0xfffc))
break;
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"OW",2) == 0) ||
(strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"FL",2) == 0) ||
(strncmp(implicit_vr,"OF",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"UL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) == 0)
quantum=8;
else
quantum=1;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowDCMException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowDCMException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
if ((((unsigned int) group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MagickPathExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MagickPathExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=(ssize_t) sscanf(transfer_syntax+17,".%d.%d",&type,
&subtype);
if (count < 1)
ThrowDCMException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
info.samples_per_pixel=(size_t) datum;
if ((info.samples_per_pixel == 0) || (info.samples_per_pixel > 4))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
if (data == (unsigned char *) NULL)
break;
for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
info.polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
if (data == (unsigned char *) NULL)
break;
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
info.bits_allocated=(size_t) datum;
info.bytes_per_pixel=1;
if (datum > 8)
info.bytes_per_pixel=2;
info.depth=info.bits_allocated;
if ((info.depth == 0) || (info.depth > 32))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.bits_allocated)-1;
image->depth=info.depth;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
info.significant_bits=(size_t) datum;
info.bytes_per_pixel=1;
if (info.significant_bits > 8)
info.bytes_per_pixel=2;
info.depth=info.significant_bits;
if ((info.depth == 0) || (info.depth > 16))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
info.max_value=(1UL << info.significant_bits)-1;
info.mask=(size_t) GetQuantumRange(info.significant_bits);
image->depth=info.depth;
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
info.signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
info.window_center=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
info.window_width=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
info.rescale_intercept=StringToDouble((char *) data,
(char **) NULL);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
info.rescale_slope=StringToDouble((char *) data,(char **) NULL);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/info.bytes_per_pixel);
datum=(int) colors;
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
graymap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(graymap,0,MagickMax(colors,65536)*
sizeof(*graymap));
for (i=0; i < (ssize_t) colors; i++)
if (info.bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
redmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(redmap,0,MagickMax(colors,65536)*
sizeof(*redmap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
greenmap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(greenmap,0,MagickMax(colors,65536)*
sizeof(*greenmap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
bluemap=(int *) AcquireQuantumMemory(MagickMax(colors,65536),
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(bluemap,0,MagickMax(colors,65536)*
sizeof(*bluemap));
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
info.polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data,
exception);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((group == 0xfffc) && (element == 0xfffc))
{
Image
*last;
last=RemoveLastImageFromList(&image);
if (last != (Image *) NULL)
last=DestroyImage(last);
break;
}
if ((width == 0) || (height == 0))
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (info.signed_data == 0xffff)
info.signed_data=(size_t) (info.significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
if (ReadBlobByte(image) == EOF)
break;
(void) (((ssize_t) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image));
length=(size_t) ReadBlobLSBLong(image);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *) RelinquishMagickMemory(
stream_info->offsets);
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MagickPathExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
{
read_info=DestroyImageInfo(read_info);
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for (c=EOF; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
if (fputc(c,file) != c)
break;
}
(void) fclose(file);
if (c == EOF)
break;
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"jpeg:%s",filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"j2k:%s",filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property,exception),exception);
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
image=DestroyImageList(image);
return(GetFirstImageInList(images));
}
if (info.depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(info.depth)+1);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
info.scale=(Quantum *) AcquireQuantumMemory(MagickMax(length,256),
sizeof(*info.scale));
if (info.scale == (Quantum *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
(void) memset(info.scale,0,MagickMax(length,256)*
sizeof(*info.scale));
range=GetQuantumRange(info.depth);
for (i=0; i <= (ssize_t) GetQuantumRange(info.depth); i++)
info.scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
if (length > (size_t) GetBlobSize(image))
ThrowDCMException(CorruptImageError,"InsufficientImageDataInFile");
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
{
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
if (EOFBlob(image) != MagickFalse)
break;
}
offset=TellBlob(image)+8;
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=info.depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
image->colorspace=RGBColorspace;
(void) SetImageBackgroundColor(image,exception);
if ((image->colormap == (PixelInfo *) NULL) &&
(info.samples_per_pixel == 1))
{
int
index;
size_t
one;
one=1;
if (colors == 0)
colors=one << info.depth;
if (AcquireImageColormap(image,colors,exception) == MagickFalse)
ThrowDCMException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(MagickRealType) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].green=(MagickRealType) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].blue=(MagickRealType) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((info.scale != (Quantum *) NULL) && (index >= 0) &&
(index <= (int) info.max_value))
index=(int) info.scale[index];
image->colormap[i].red=(MagickRealType) index;
image->colormap[i].green=(MagickRealType) index;
image->colormap[i].blue=(MagickRealType) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
}
tag=((unsigned int) ReadBlobLSBShort(image) << 16) |
ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
{
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
ThrowDCMException(CorruptImageError,"ImproperImageHeader");
}
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
if (stream_info->segment_count > 1)
{
info.bytes_per_pixel=1;
info.depth=8;
if (stream_info->offset_count > 0)
(void) SeekBlob(image,(MagickOffsetType)
stream_info->offsets[0]+stream_info->segments[0],SEEK_SET);
}
}
if ((info.samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
register ssize_t
x;
register Quantum
*q;
ssize_t
y;
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) info.samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 3:
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType)
y,image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
/*
Convert DCM Medical image to pixel packets.
*/
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
info.window_width=0;
}
option=GetImageOption(image_info,"dcm:window");
if (option != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(option,&geometry_info);
if (flags & RhoValue)
info.window_center=geometry_info.rho;
if (flags & SigmaValue)
info.window_width=geometry_info.sigma;
info.rescale=MagickTrue;
}
option=GetImageOption(image_info,"dcm:rescale");
if (option != (char *) NULL)
info.rescale=IsStringTrue(option);
if ((info.window_center != 0) && (info.window_width == 0))
info.window_width=info.window_center;
status=ReadDCMPixels(image,&info,stream_info,MagickTrue,exception);
if ((status != MagickFalse) && (stream_info->segment_count > 1))
{
if (stream_info->offset_count > 0)
(void) SeekBlob(image,(MagickOffsetType)
stream_info->offsets[0]+stream_info->segments[1],SEEK_SET);
(void) ReadDCMPixels(image,&info,stream_info,MagickFalse,
exception);
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
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;
}
}
if (TellBlob(image) < (MagickOffsetType) GetBlobSize(image))
{
/*
Allocate next image structure.
*/
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;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (info.scale != (Quantum *) NULL)
info.scale=(Quantum *) RelinquishMagickMemory(info.scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDCMImage() adds attributes for the DCM image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDCMImage method is:
%
% size_t RegisterDCMImage(void)
%
*/
ModuleExport size_t RegisterDCMImage(void)
{
MagickInfo
*entry;
static const char
*DCMNote=
{
"DICOM is used by the medical community for images like X-rays. The\n"
"specification, \"Digital Imaging and Communications in Medicine\n"
"(DICOM)\", is available at http://medical.nema.org/. In particular,\n"
"see part 5 which describes the image encoding (RLE, JPEG, JPEG-LS),\n"
"and supplement 61 which adds JPEG-2000 encoding."
};
entry=AcquireMagickInfo("DCM","DCM",
"Digital Imaging and Communications in Medicine image");
entry->decoder=(DecodeImageHandler *) ReadDCMImage;
entry->magick=(IsImageFormatHandler *) IsDCM;
entry->flags^=CoderAdjoinFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
entry->note=ConstantString(DCMNote);
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D C M I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDCMImage() removes format registrations made by the
% DCM module from the list of supported formats.
%
% The format of the UnregisterDCMImage method is:
%
% UnregisterDCMImage(void)
%
*/
ModuleExport void UnregisterDCMImage(void)
{
(void) UnregisterMagickInfo("DCM");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_364_1 |
crossvul-cpp_data_bad_5845_21 | /*
* NETLINK Kernel-user communication protocol.
*
* Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
* Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
* added netlink_proto_exit
* Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
* use nlk_sk, as sk->protinfo is on a diet 8)
* Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
* - inc module use count of module that owns
* the kernel socket in case userspace opens
* socket of same protocol
* - remove all module support, since netlink is
* mandatory if CONFIG_NET=y these days
*/
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/notifier.h>
#include <linux/security.h>
#include <linux/jhash.h>
#include <linux/jiffies.h>
#include <linux/random.h>
#include <linux/bitops.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/audit.h>
#include <linux/mutex.h>
#include <linux/vmalloc.h>
#include <linux/if_arp.h>
#include <asm/cacheflush.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/scm.h>
#include <net/netlink.h>
#include "af_netlink.h"
struct listeners {
struct rcu_head rcu;
unsigned long masks[0];
};
/* state bits */
#define NETLINK_CONGESTED 0x0
/* flags */
#define NETLINK_KERNEL_SOCKET 0x1
#define NETLINK_RECV_PKTINFO 0x2
#define NETLINK_BROADCAST_SEND_ERROR 0x4
#define NETLINK_RECV_NO_ENOBUFS 0x8
static inline int netlink_is_kernel(struct sock *sk)
{
return nlk_sk(sk)->flags & NETLINK_KERNEL_SOCKET;
}
struct netlink_table *nl_table;
EXPORT_SYMBOL_GPL(nl_table);
static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
static int netlink_dump(struct sock *sk);
static void netlink_skb_destructor(struct sk_buff *skb);
DEFINE_RWLOCK(nl_table_lock);
EXPORT_SYMBOL_GPL(nl_table_lock);
static atomic_t nl_table_users = ATOMIC_INIT(0);
#define nl_deref_protected(X) rcu_dereference_protected(X, lockdep_is_held(&nl_table_lock));
static ATOMIC_NOTIFIER_HEAD(netlink_chain);
static DEFINE_SPINLOCK(netlink_tap_lock);
static struct list_head netlink_tap_all __read_mostly;
static inline u32 netlink_group_mask(u32 group)
{
return group ? 1 << (group - 1) : 0;
}
static inline struct hlist_head *nl_portid_hashfn(struct nl_portid_hash *hash, u32 portid)
{
return &hash->table[jhash_1word(portid, hash->rnd) & hash->mask];
}
int netlink_add_tap(struct netlink_tap *nt)
{
if (unlikely(nt->dev->type != ARPHRD_NETLINK))
return -EINVAL;
spin_lock(&netlink_tap_lock);
list_add_rcu(&nt->list, &netlink_tap_all);
spin_unlock(&netlink_tap_lock);
if (nt->module)
__module_get(nt->module);
return 0;
}
EXPORT_SYMBOL_GPL(netlink_add_tap);
int __netlink_remove_tap(struct netlink_tap *nt)
{
bool found = false;
struct netlink_tap *tmp;
spin_lock(&netlink_tap_lock);
list_for_each_entry(tmp, &netlink_tap_all, list) {
if (nt == tmp) {
list_del_rcu(&nt->list);
found = true;
goto out;
}
}
pr_warn("__netlink_remove_tap: %p not found\n", nt);
out:
spin_unlock(&netlink_tap_lock);
if (found && nt->module)
module_put(nt->module);
return found ? 0 : -ENODEV;
}
EXPORT_SYMBOL_GPL(__netlink_remove_tap);
int netlink_remove_tap(struct netlink_tap *nt)
{
int ret;
ret = __netlink_remove_tap(nt);
synchronize_net();
return ret;
}
EXPORT_SYMBOL_GPL(netlink_remove_tap);
static bool netlink_filter_tap(const struct sk_buff *skb)
{
struct sock *sk = skb->sk;
bool pass = false;
/* We take the more conservative approach and
* whitelist socket protocols that may pass.
*/
switch (sk->sk_protocol) {
case NETLINK_ROUTE:
case NETLINK_USERSOCK:
case NETLINK_SOCK_DIAG:
case NETLINK_NFLOG:
case NETLINK_XFRM:
case NETLINK_FIB_LOOKUP:
case NETLINK_NETFILTER:
case NETLINK_GENERIC:
pass = true;
break;
}
return pass;
}
static int __netlink_deliver_tap_skb(struct sk_buff *skb,
struct net_device *dev)
{
struct sk_buff *nskb;
struct sock *sk = skb->sk;
int ret = -ENOMEM;
dev_hold(dev);
nskb = skb_clone(skb, GFP_ATOMIC);
if (nskb) {
nskb->dev = dev;
nskb->protocol = htons((u16) sk->sk_protocol);
ret = dev_queue_xmit(nskb);
if (unlikely(ret > 0))
ret = net_xmit_errno(ret);
}
dev_put(dev);
return ret;
}
static void __netlink_deliver_tap(struct sk_buff *skb)
{
int ret;
struct netlink_tap *tmp;
if (!netlink_filter_tap(skb))
return;
list_for_each_entry_rcu(tmp, &netlink_tap_all, list) {
ret = __netlink_deliver_tap_skb(skb, tmp->dev);
if (unlikely(ret))
break;
}
}
static void netlink_deliver_tap(struct sk_buff *skb)
{
rcu_read_lock();
if (unlikely(!list_empty(&netlink_tap_all)))
__netlink_deliver_tap(skb);
rcu_read_unlock();
}
static void netlink_overrun(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (!(nlk->flags & NETLINK_RECV_NO_ENOBUFS)) {
if (!test_and_set_bit(NETLINK_CONGESTED, &nlk_sk(sk)->state)) {
sk->sk_err = ENOBUFS;
sk->sk_error_report(sk);
}
}
atomic_inc(&sk->sk_drops);
}
static void netlink_rcv_wake(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (skb_queue_empty(&sk->sk_receive_queue))
clear_bit(NETLINK_CONGESTED, &nlk->state);
if (!test_bit(NETLINK_CONGESTED, &nlk->state))
wake_up_interruptible(&nlk->wait);
}
#ifdef CONFIG_NETLINK_MMAP
static bool netlink_skb_is_mmaped(const struct sk_buff *skb)
{
return NETLINK_CB(skb).flags & NETLINK_SKB_MMAPED;
}
static bool netlink_rx_is_mmaped(struct sock *sk)
{
return nlk_sk(sk)->rx_ring.pg_vec != NULL;
}
static bool netlink_tx_is_mmaped(struct sock *sk)
{
return nlk_sk(sk)->tx_ring.pg_vec != NULL;
}
static __pure struct page *pgvec_to_page(const void *addr)
{
if (is_vmalloc_addr(addr))
return vmalloc_to_page(addr);
else
return virt_to_page(addr);
}
static void free_pg_vec(void **pg_vec, unsigned int order, unsigned int len)
{
unsigned int i;
for (i = 0; i < len; i++) {
if (pg_vec[i] != NULL) {
if (is_vmalloc_addr(pg_vec[i]))
vfree(pg_vec[i]);
else
free_pages((unsigned long)pg_vec[i], order);
}
}
kfree(pg_vec);
}
static void *alloc_one_pg_vec_page(unsigned long order)
{
void *buffer;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP | __GFP_ZERO |
__GFP_NOWARN | __GFP_NORETRY;
buffer = (void *)__get_free_pages(gfp_flags, order);
if (buffer != NULL)
return buffer;
buffer = vzalloc((1 << order) * PAGE_SIZE);
if (buffer != NULL)
return buffer;
gfp_flags &= ~__GFP_NORETRY;
return (void *)__get_free_pages(gfp_flags, order);
}
static void **alloc_pg_vec(struct netlink_sock *nlk,
struct nl_mmap_req *req, unsigned int order)
{
unsigned int block_nr = req->nm_block_nr;
unsigned int i;
void **pg_vec;
pg_vec = kcalloc(block_nr, sizeof(void *), GFP_KERNEL);
if (pg_vec == NULL)
return NULL;
for (i = 0; i < block_nr; i++) {
pg_vec[i] = alloc_one_pg_vec_page(order);
if (pg_vec[i] == NULL)
goto err1;
}
return pg_vec;
err1:
free_pg_vec(pg_vec, order, block_nr);
return NULL;
}
static int netlink_set_ring(struct sock *sk, struct nl_mmap_req *req,
bool closing, bool tx_ring)
{
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_ring *ring;
struct sk_buff_head *queue;
void **pg_vec = NULL;
unsigned int order = 0;
int err;
ring = tx_ring ? &nlk->tx_ring : &nlk->rx_ring;
queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
if (!closing) {
if (atomic_read(&nlk->mapped))
return -EBUSY;
if (atomic_read(&ring->pending))
return -EBUSY;
}
if (req->nm_block_nr) {
if (ring->pg_vec != NULL)
return -EBUSY;
if ((int)req->nm_block_size <= 0)
return -EINVAL;
if (!IS_ALIGNED(req->nm_block_size, PAGE_SIZE))
return -EINVAL;
if (req->nm_frame_size < NL_MMAP_HDRLEN)
return -EINVAL;
if (!IS_ALIGNED(req->nm_frame_size, NL_MMAP_MSG_ALIGNMENT))
return -EINVAL;
ring->frames_per_block = req->nm_block_size /
req->nm_frame_size;
if (ring->frames_per_block == 0)
return -EINVAL;
if (ring->frames_per_block * req->nm_block_nr !=
req->nm_frame_nr)
return -EINVAL;
order = get_order(req->nm_block_size);
pg_vec = alloc_pg_vec(nlk, req, order);
if (pg_vec == NULL)
return -ENOMEM;
} else {
if (req->nm_frame_nr)
return -EINVAL;
}
err = -EBUSY;
mutex_lock(&nlk->pg_vec_lock);
if (closing || atomic_read(&nlk->mapped) == 0) {
err = 0;
spin_lock_bh(&queue->lock);
ring->frame_max = req->nm_frame_nr - 1;
ring->head = 0;
ring->frame_size = req->nm_frame_size;
ring->pg_vec_pages = req->nm_block_size / PAGE_SIZE;
swap(ring->pg_vec_len, req->nm_block_nr);
swap(ring->pg_vec_order, order);
swap(ring->pg_vec, pg_vec);
__skb_queue_purge(queue);
spin_unlock_bh(&queue->lock);
WARN_ON(atomic_read(&nlk->mapped));
}
mutex_unlock(&nlk->pg_vec_lock);
if (pg_vec)
free_pg_vec(pg_vec, order, req->nm_block_nr);
return err;
}
static void netlink_mm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_inc(&nlk_sk(sk)->mapped);
}
static void netlink_mm_close(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_dec(&nlk_sk(sk)->mapped);
}
static const struct vm_operations_struct netlink_mmap_ops = {
.open = netlink_mm_open,
.close = netlink_mm_close,
};
static int netlink_mmap(struct file *file, struct socket *sock,
struct vm_area_struct *vma)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_ring *ring;
unsigned long start, size, expected;
unsigned int i;
int err = -EINVAL;
if (vma->vm_pgoff)
return -EINVAL;
mutex_lock(&nlk->pg_vec_lock);
expected = 0;
for (ring = &nlk->rx_ring; ring <= &nlk->tx_ring; ring++) {
if (ring->pg_vec == NULL)
continue;
expected += ring->pg_vec_len * ring->pg_vec_pages * PAGE_SIZE;
}
if (expected == 0)
goto out;
size = vma->vm_end - vma->vm_start;
if (size != expected)
goto out;
start = vma->vm_start;
for (ring = &nlk->rx_ring; ring <= &nlk->tx_ring; ring++) {
if (ring->pg_vec == NULL)
continue;
for (i = 0; i < ring->pg_vec_len; i++) {
struct page *page;
void *kaddr = ring->pg_vec[i];
unsigned int pg_num;
for (pg_num = 0; pg_num < ring->pg_vec_pages; pg_num++) {
page = pgvec_to_page(kaddr);
err = vm_insert_page(vma, start, page);
if (err < 0)
goto out;
start += PAGE_SIZE;
kaddr += PAGE_SIZE;
}
}
}
atomic_inc(&nlk->mapped);
vma->vm_ops = &netlink_mmap_ops;
err = 0;
out:
mutex_unlock(&nlk->pg_vec_lock);
return err;
}
static void netlink_frame_flush_dcache(const struct nl_mmap_hdr *hdr)
{
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
struct page *p_start, *p_end;
/* First page is flushed through netlink_{get,set}_status */
p_start = pgvec_to_page(hdr + PAGE_SIZE);
p_end = pgvec_to_page((void *)hdr + NL_MMAP_HDRLEN + hdr->nm_len - 1);
while (p_start <= p_end) {
flush_dcache_page(p_start);
p_start++;
}
#endif
}
static enum nl_mmap_status netlink_get_status(const struct nl_mmap_hdr *hdr)
{
smp_rmb();
flush_dcache_page(pgvec_to_page(hdr));
return hdr->nm_status;
}
static void netlink_set_status(struct nl_mmap_hdr *hdr,
enum nl_mmap_status status)
{
hdr->nm_status = status;
flush_dcache_page(pgvec_to_page(hdr));
smp_wmb();
}
static struct nl_mmap_hdr *
__netlink_lookup_frame(const struct netlink_ring *ring, unsigned int pos)
{
unsigned int pg_vec_pos, frame_off;
pg_vec_pos = pos / ring->frames_per_block;
frame_off = pos % ring->frames_per_block;
return ring->pg_vec[pg_vec_pos] + (frame_off * ring->frame_size);
}
static struct nl_mmap_hdr *
netlink_lookup_frame(const struct netlink_ring *ring, unsigned int pos,
enum nl_mmap_status status)
{
struct nl_mmap_hdr *hdr;
hdr = __netlink_lookup_frame(ring, pos);
if (netlink_get_status(hdr) != status)
return NULL;
return hdr;
}
static struct nl_mmap_hdr *
netlink_current_frame(const struct netlink_ring *ring,
enum nl_mmap_status status)
{
return netlink_lookup_frame(ring, ring->head, status);
}
static struct nl_mmap_hdr *
netlink_previous_frame(const struct netlink_ring *ring,
enum nl_mmap_status status)
{
unsigned int prev;
prev = ring->head ? ring->head - 1 : ring->frame_max;
return netlink_lookup_frame(ring, prev, status);
}
static void netlink_increment_head(struct netlink_ring *ring)
{
ring->head = ring->head != ring->frame_max ? ring->head + 1 : 0;
}
static void netlink_forward_ring(struct netlink_ring *ring)
{
unsigned int head = ring->head, pos = head;
const struct nl_mmap_hdr *hdr;
do {
hdr = __netlink_lookup_frame(ring, pos);
if (hdr->nm_status == NL_MMAP_STATUS_UNUSED)
break;
if (hdr->nm_status != NL_MMAP_STATUS_SKIP)
break;
netlink_increment_head(ring);
} while (ring->head != head);
}
static bool netlink_dump_space(struct netlink_sock *nlk)
{
struct netlink_ring *ring = &nlk->rx_ring;
struct nl_mmap_hdr *hdr;
unsigned int n;
hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
if (hdr == NULL)
return false;
n = ring->head + ring->frame_max / 2;
if (n > ring->frame_max)
n -= ring->frame_max;
hdr = __netlink_lookup_frame(ring, n);
return hdr->nm_status == NL_MMAP_STATUS_UNUSED;
}
static unsigned int netlink_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
unsigned int mask;
int err;
if (nlk->rx_ring.pg_vec != NULL) {
/* Memory mapped sockets don't call recvmsg(), so flow control
* for dumps is performed here. A dump is allowed to continue
* if at least half the ring is unused.
*/
while (nlk->cb_running && netlink_dump_space(nlk)) {
err = netlink_dump(sk);
if (err < 0) {
sk->sk_err = err;
sk->sk_error_report(sk);
break;
}
}
netlink_rcv_wake(sk);
}
mask = datagram_poll(file, sock, wait);
spin_lock_bh(&sk->sk_receive_queue.lock);
if (nlk->rx_ring.pg_vec) {
netlink_forward_ring(&nlk->rx_ring);
if (!netlink_previous_frame(&nlk->rx_ring, NL_MMAP_STATUS_UNUSED))
mask |= POLLIN | POLLRDNORM;
}
spin_unlock_bh(&sk->sk_receive_queue.lock);
spin_lock_bh(&sk->sk_write_queue.lock);
if (nlk->tx_ring.pg_vec) {
if (netlink_current_frame(&nlk->tx_ring, NL_MMAP_STATUS_UNUSED))
mask |= POLLOUT | POLLWRNORM;
}
spin_unlock_bh(&sk->sk_write_queue.lock);
return mask;
}
static struct nl_mmap_hdr *netlink_mmap_hdr(struct sk_buff *skb)
{
return (struct nl_mmap_hdr *)(skb->head - NL_MMAP_HDRLEN);
}
static void netlink_ring_setup_skb(struct sk_buff *skb, struct sock *sk,
struct netlink_ring *ring,
struct nl_mmap_hdr *hdr)
{
unsigned int size;
void *data;
size = ring->frame_size - NL_MMAP_HDRLEN;
data = (void *)hdr + NL_MMAP_HDRLEN;
skb->head = data;
skb->data = data;
skb_reset_tail_pointer(skb);
skb->end = skb->tail + size;
skb->len = 0;
skb->destructor = netlink_skb_destructor;
NETLINK_CB(skb).flags |= NETLINK_SKB_MMAPED;
NETLINK_CB(skb).sk = sk;
}
static int netlink_mmap_sendmsg(struct sock *sk, struct msghdr *msg,
u32 dst_portid, u32 dst_group,
struct sock_iocb *siocb)
{
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_ring *ring;
struct nl_mmap_hdr *hdr;
struct sk_buff *skb;
unsigned int maxlen;
bool excl = true;
int err = 0, len = 0;
/* Netlink messages are validated by the receiver before processing.
* In order to avoid userspace changing the contents of the message
* after validation, the socket and the ring may only be used by a
* single process, otherwise we fall back to copying.
*/
if (atomic_long_read(&sk->sk_socket->file->f_count) > 2 ||
atomic_read(&nlk->mapped) > 1)
excl = false;
mutex_lock(&nlk->pg_vec_lock);
ring = &nlk->tx_ring;
maxlen = ring->frame_size - NL_MMAP_HDRLEN;
do {
hdr = netlink_current_frame(ring, NL_MMAP_STATUS_VALID);
if (hdr == NULL) {
if (!(msg->msg_flags & MSG_DONTWAIT) &&
atomic_read(&nlk->tx_ring.pending))
schedule();
continue;
}
if (hdr->nm_len > maxlen) {
err = -EINVAL;
goto out;
}
netlink_frame_flush_dcache(hdr);
if (likely(dst_portid == 0 && dst_group == 0 && excl)) {
skb = alloc_skb_head(GFP_KERNEL);
if (skb == NULL) {
err = -ENOBUFS;
goto out;
}
sock_hold(sk);
netlink_ring_setup_skb(skb, sk, ring, hdr);
NETLINK_CB(skb).flags |= NETLINK_SKB_TX;
__skb_put(skb, hdr->nm_len);
netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED);
atomic_inc(&ring->pending);
} else {
skb = alloc_skb(hdr->nm_len, GFP_KERNEL);
if (skb == NULL) {
err = -ENOBUFS;
goto out;
}
__skb_put(skb, hdr->nm_len);
memcpy(skb->data, (void *)hdr + NL_MMAP_HDRLEN, hdr->nm_len);
netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED);
}
netlink_increment_head(ring);
NETLINK_CB(skb).portid = nlk->portid;
NETLINK_CB(skb).dst_group = dst_group;
NETLINK_CB(skb).creds = siocb->scm->creds;
err = security_netlink_send(sk, skb);
if (err) {
kfree_skb(skb);
goto out;
}
if (unlikely(dst_group)) {
atomic_inc(&skb->users);
netlink_broadcast(sk, skb, dst_portid, dst_group,
GFP_KERNEL);
}
err = netlink_unicast(sk, skb, dst_portid,
msg->msg_flags & MSG_DONTWAIT);
if (err < 0)
goto out;
len += err;
} while (hdr != NULL ||
(!(msg->msg_flags & MSG_DONTWAIT) &&
atomic_read(&nlk->tx_ring.pending)));
if (len > 0)
err = len;
out:
mutex_unlock(&nlk->pg_vec_lock);
return err;
}
static void netlink_queue_mmaped_skb(struct sock *sk, struct sk_buff *skb)
{
struct nl_mmap_hdr *hdr;
hdr = netlink_mmap_hdr(skb);
hdr->nm_len = skb->len;
hdr->nm_group = NETLINK_CB(skb).dst_group;
hdr->nm_pid = NETLINK_CB(skb).creds.pid;
hdr->nm_uid = from_kuid(sk_user_ns(sk), NETLINK_CB(skb).creds.uid);
hdr->nm_gid = from_kgid(sk_user_ns(sk), NETLINK_CB(skb).creds.gid);
netlink_frame_flush_dcache(hdr);
netlink_set_status(hdr, NL_MMAP_STATUS_VALID);
NETLINK_CB(skb).flags |= NETLINK_SKB_DELIVERED;
kfree_skb(skb);
}
static void netlink_ring_set_copied(struct sock *sk, struct sk_buff *skb)
{
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_ring *ring = &nlk->rx_ring;
struct nl_mmap_hdr *hdr;
spin_lock_bh(&sk->sk_receive_queue.lock);
hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
if (hdr == NULL) {
spin_unlock_bh(&sk->sk_receive_queue.lock);
kfree_skb(skb);
netlink_overrun(sk);
return;
}
netlink_increment_head(ring);
__skb_queue_tail(&sk->sk_receive_queue, skb);
spin_unlock_bh(&sk->sk_receive_queue.lock);
hdr->nm_len = skb->len;
hdr->nm_group = NETLINK_CB(skb).dst_group;
hdr->nm_pid = NETLINK_CB(skb).creds.pid;
hdr->nm_uid = from_kuid(sk_user_ns(sk), NETLINK_CB(skb).creds.uid);
hdr->nm_gid = from_kgid(sk_user_ns(sk), NETLINK_CB(skb).creds.gid);
netlink_set_status(hdr, NL_MMAP_STATUS_COPY);
}
#else /* CONFIG_NETLINK_MMAP */
#define netlink_skb_is_mmaped(skb) false
#define netlink_rx_is_mmaped(sk) false
#define netlink_tx_is_mmaped(sk) false
#define netlink_mmap sock_no_mmap
#define netlink_poll datagram_poll
#define netlink_mmap_sendmsg(sk, msg, dst_portid, dst_group, siocb) 0
#endif /* CONFIG_NETLINK_MMAP */
static void netlink_skb_destructor(struct sk_buff *skb)
{
#ifdef CONFIG_NETLINK_MMAP
struct nl_mmap_hdr *hdr;
struct netlink_ring *ring;
struct sock *sk;
/* If a packet from the kernel to userspace was freed because of an
* error without being delivered to userspace, the kernel must reset
* the status. In the direction userspace to kernel, the status is
* always reset here after the packet was processed and freed.
*/
if (netlink_skb_is_mmaped(skb)) {
hdr = netlink_mmap_hdr(skb);
sk = NETLINK_CB(skb).sk;
if (NETLINK_CB(skb).flags & NETLINK_SKB_TX) {
netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED);
ring = &nlk_sk(sk)->tx_ring;
} else {
if (!(NETLINK_CB(skb).flags & NETLINK_SKB_DELIVERED)) {
hdr->nm_len = 0;
netlink_set_status(hdr, NL_MMAP_STATUS_VALID);
}
ring = &nlk_sk(sk)->rx_ring;
}
WARN_ON(atomic_read(&ring->pending) == 0);
atomic_dec(&ring->pending);
sock_put(sk);
skb->head = NULL;
}
#endif
if (is_vmalloc_addr(skb->head)) {
if (!skb->cloned ||
!atomic_dec_return(&(skb_shinfo(skb)->dataref)))
vfree(skb->head);
skb->head = NULL;
}
if (skb->sk != NULL)
sock_rfree(skb);
}
static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
{
WARN_ON(skb->sk != NULL);
skb->sk = sk;
skb->destructor = netlink_skb_destructor;
atomic_add(skb->truesize, &sk->sk_rmem_alloc);
sk_mem_charge(sk, skb->truesize);
}
static void netlink_sock_destruct(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (nlk->cb_running) {
if (nlk->cb.done)
nlk->cb.done(&nlk->cb);
module_put(nlk->cb.module);
kfree_skb(nlk->cb.skb);
}
skb_queue_purge(&sk->sk_receive_queue);
#ifdef CONFIG_NETLINK_MMAP
if (1) {
struct nl_mmap_req req;
memset(&req, 0, sizeof(req));
if (nlk->rx_ring.pg_vec)
netlink_set_ring(sk, &req, true, false);
memset(&req, 0, sizeof(req));
if (nlk->tx_ring.pg_vec)
netlink_set_ring(sk, &req, true, true);
}
#endif /* CONFIG_NETLINK_MMAP */
if (!sock_flag(sk, SOCK_DEAD)) {
printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
return;
}
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(nlk_sk(sk)->groups);
}
/* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
* SMP. Look, when several writers sleep and reader wakes them up, all but one
* immediately hit write lock and grab all the cpus. Exclusive sleep solves
* this, _but_ remember, it adds useless work on UP machines.
*/
void netlink_table_grab(void)
__acquires(nl_table_lock)
{
might_sleep();
write_lock_irq(&nl_table_lock);
if (atomic_read(&nl_table_users)) {
DECLARE_WAITQUEUE(wait, current);
add_wait_queue_exclusive(&nl_table_wait, &wait);
for (;;) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (atomic_read(&nl_table_users) == 0)
break;
write_unlock_irq(&nl_table_lock);
schedule();
write_lock_irq(&nl_table_lock);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(&nl_table_wait, &wait);
}
}
void netlink_table_ungrab(void)
__releases(nl_table_lock)
{
write_unlock_irq(&nl_table_lock);
wake_up(&nl_table_wait);
}
static inline void
netlink_lock_table(void)
{
/* read_lock() synchronizes us to netlink_table_grab */
read_lock(&nl_table_lock);
atomic_inc(&nl_table_users);
read_unlock(&nl_table_lock);
}
static inline void
netlink_unlock_table(void)
{
if (atomic_dec_and_test(&nl_table_users))
wake_up(&nl_table_wait);
}
static bool netlink_compare(struct net *net, struct sock *sk)
{
return net_eq(sock_net(sk), net);
}
static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
{
struct netlink_table *table = &nl_table[protocol];
struct nl_portid_hash *hash = &table->hash;
struct hlist_head *head;
struct sock *sk;
read_lock(&nl_table_lock);
head = nl_portid_hashfn(hash, portid);
sk_for_each(sk, head) {
if (table->compare(net, sk) &&
(nlk_sk(sk)->portid == portid)) {
sock_hold(sk);
goto found;
}
}
sk = NULL;
found:
read_unlock(&nl_table_lock);
return sk;
}
static struct hlist_head *nl_portid_hash_zalloc(size_t size)
{
if (size <= PAGE_SIZE)
return kzalloc(size, GFP_ATOMIC);
else
return (struct hlist_head *)
__get_free_pages(GFP_ATOMIC | __GFP_ZERO,
get_order(size));
}
static void nl_portid_hash_free(struct hlist_head *table, size_t size)
{
if (size <= PAGE_SIZE)
kfree(table);
else
free_pages((unsigned long)table, get_order(size));
}
static int nl_portid_hash_rehash(struct nl_portid_hash *hash, int grow)
{
unsigned int omask, mask, shift;
size_t osize, size;
struct hlist_head *otable, *table;
int i;
omask = mask = hash->mask;
osize = size = (mask + 1) * sizeof(*table);
shift = hash->shift;
if (grow) {
if (++shift > hash->max_shift)
return 0;
mask = mask * 2 + 1;
size *= 2;
}
table = nl_portid_hash_zalloc(size);
if (!table)
return 0;
otable = hash->table;
hash->table = table;
hash->mask = mask;
hash->shift = shift;
get_random_bytes(&hash->rnd, sizeof(hash->rnd));
for (i = 0; i <= omask; i++) {
struct sock *sk;
struct hlist_node *tmp;
sk_for_each_safe(sk, tmp, &otable[i])
__sk_add_node(sk, nl_portid_hashfn(hash, nlk_sk(sk)->portid));
}
nl_portid_hash_free(otable, osize);
hash->rehash_time = jiffies + 10 * 60 * HZ;
return 1;
}
static inline int nl_portid_hash_dilute(struct nl_portid_hash *hash, int len)
{
int avg = hash->entries >> hash->shift;
if (unlikely(avg > 1) && nl_portid_hash_rehash(hash, 1))
return 1;
if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
nl_portid_hash_rehash(hash, 0);
return 1;
}
return 0;
}
static const struct proto_ops netlink_ops;
static void
netlink_update_listeners(struct sock *sk)
{
struct netlink_table *tbl = &nl_table[sk->sk_protocol];
unsigned long mask;
unsigned int i;
struct listeners *listeners;
listeners = nl_deref_protected(tbl->listeners);
if (!listeners)
return;
for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
mask = 0;
sk_for_each_bound(sk, &tbl->mc_list) {
if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
mask |= nlk_sk(sk)->groups[i];
}
listeners->masks[i] = mask;
}
/* this function is only called with the netlink table "grabbed", which
* makes sure updates are visible before bind or setsockopt return. */
}
static int netlink_insert(struct sock *sk, struct net *net, u32 portid)
{
struct netlink_table *table = &nl_table[sk->sk_protocol];
struct nl_portid_hash *hash = &table->hash;
struct hlist_head *head;
int err = -EADDRINUSE;
struct sock *osk;
int len;
netlink_table_grab();
head = nl_portid_hashfn(hash, portid);
len = 0;
sk_for_each(osk, head) {
if (table->compare(net, osk) &&
(nlk_sk(osk)->portid == portid))
break;
len++;
}
if (osk)
goto err;
err = -EBUSY;
if (nlk_sk(sk)->portid)
goto err;
err = -ENOMEM;
if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
goto err;
if (len && nl_portid_hash_dilute(hash, len))
head = nl_portid_hashfn(hash, portid);
hash->entries++;
nlk_sk(sk)->portid = portid;
sk_add_node(sk, head);
err = 0;
err:
netlink_table_ungrab();
return err;
}
static void netlink_remove(struct sock *sk)
{
netlink_table_grab();
if (sk_del_node_init(sk))
nl_table[sk->sk_protocol].hash.entries--;
if (nlk_sk(sk)->subscriptions)
__sk_del_bind_node(sk);
netlink_table_ungrab();
}
static struct proto netlink_proto = {
.name = "NETLINK",
.owner = THIS_MODULE,
.obj_size = sizeof(struct netlink_sock),
};
static int __netlink_create(struct net *net, struct socket *sock,
struct mutex *cb_mutex, int protocol)
{
struct sock *sk;
struct netlink_sock *nlk;
sock->ops = &netlink_ops;
sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
nlk = nlk_sk(sk);
if (cb_mutex) {
nlk->cb_mutex = cb_mutex;
} else {
nlk->cb_mutex = &nlk->cb_def_mutex;
mutex_init(nlk->cb_mutex);
}
init_waitqueue_head(&nlk->wait);
#ifdef CONFIG_NETLINK_MMAP
mutex_init(&nlk->pg_vec_lock);
#endif
sk->sk_destruct = netlink_sock_destruct;
sk->sk_protocol = protocol;
return 0;
}
static int netlink_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct module *module = NULL;
struct mutex *cb_mutex;
struct netlink_sock *nlk;
void (*bind)(int group);
int err = 0;
sock->state = SS_UNCONNECTED;
if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
if (protocol < 0 || protocol >= MAX_LINKS)
return -EPROTONOSUPPORT;
netlink_lock_table();
#ifdef CONFIG_MODULES
if (!nl_table[protocol].registered) {
netlink_unlock_table();
request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
netlink_lock_table();
}
#endif
if (nl_table[protocol].registered &&
try_module_get(nl_table[protocol].module))
module = nl_table[protocol].module;
else
err = -EPROTONOSUPPORT;
cb_mutex = nl_table[protocol].cb_mutex;
bind = nl_table[protocol].bind;
netlink_unlock_table();
if (err < 0)
goto out;
err = __netlink_create(net, sock, cb_mutex, protocol);
if (err < 0)
goto out_module;
local_bh_disable();
sock_prot_inuse_add(net, &netlink_proto, 1);
local_bh_enable();
nlk = nlk_sk(sock->sk);
nlk->module = module;
nlk->netlink_bind = bind;
out:
return err;
out_module:
module_put(module);
goto out;
}
static int netlink_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk;
if (!sk)
return 0;
netlink_remove(sk);
sock_orphan(sk);
nlk = nlk_sk(sk);
/*
* OK. Socket is unlinked, any packets that arrive now
* will be purged.
*/
sock->sk = NULL;
wake_up_interruptible_all(&nlk->wait);
skb_queue_purge(&sk->sk_write_queue);
if (nlk->portid) {
struct netlink_notify n = {
.net = sock_net(sk),
.protocol = sk->sk_protocol,
.portid = nlk->portid,
};
atomic_notifier_call_chain(&netlink_chain,
NETLINK_URELEASE, &n);
}
module_put(nlk->module);
netlink_table_grab();
if (netlink_is_kernel(sk)) {
BUG_ON(nl_table[sk->sk_protocol].registered == 0);
if (--nl_table[sk->sk_protocol].registered == 0) {
struct listeners *old;
old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
kfree_rcu(old, rcu);
nl_table[sk->sk_protocol].module = NULL;
nl_table[sk->sk_protocol].bind = NULL;
nl_table[sk->sk_protocol].flags = 0;
nl_table[sk->sk_protocol].registered = 0;
}
} else if (nlk->subscriptions) {
netlink_update_listeners(sk);
}
netlink_table_ungrab();
kfree(nlk->groups);
nlk->groups = NULL;
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
local_bh_enable();
sock_put(sk);
return 0;
}
static int netlink_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct netlink_table *table = &nl_table[sk->sk_protocol];
struct nl_portid_hash *hash = &table->hash;
struct hlist_head *head;
struct sock *osk;
s32 portid = task_tgid_vnr(current);
int err;
static s32 rover = -4097;
retry:
cond_resched();
netlink_table_grab();
head = nl_portid_hashfn(hash, portid);
sk_for_each(osk, head) {
if (!table->compare(net, osk))
continue;
if (nlk_sk(osk)->portid == portid) {
/* Bind collision, search negative portid values. */
portid = rover--;
if (rover > -4097)
rover = -4097;
netlink_table_ungrab();
goto retry;
}
}
netlink_table_ungrab();
err = netlink_insert(sk, net, portid);
if (err == -EADDRINUSE)
goto retry;
/* If 2 threads race to autobind, that is fine. */
if (err == -EBUSY)
err = 0;
return err;
}
static inline int netlink_capable(const struct socket *sock, unsigned int flag)
{
return (nl_table[sock->sk->sk_protocol].flags & flag) ||
ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
}
static void
netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (nlk->subscriptions && !subscriptions)
__sk_del_bind_node(sk);
else if (!nlk->subscriptions && subscriptions)
sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
nlk->subscriptions = subscriptions;
}
static int netlink_realloc_groups(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
unsigned int groups;
unsigned long *new_groups;
int err = 0;
netlink_table_grab();
groups = nl_table[sk->sk_protocol].groups;
if (!nl_table[sk->sk_protocol].registered) {
err = -ENOENT;
goto out_unlock;
}
if (nlk->ngroups >= groups)
goto out_unlock;
new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
if (new_groups == NULL) {
err = -ENOMEM;
goto out_unlock;
}
memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
nlk->groups = new_groups;
nlk->ngroups = groups;
out_unlock:
netlink_table_ungrab();
return err;
}
static int netlink_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
int err;
if (addr_len < sizeof(struct sockaddr_nl))
return -EINVAL;
if (nladdr->nl_family != AF_NETLINK)
return -EINVAL;
/* Only superuser is allowed to listen multicasts */
if (nladdr->nl_groups) {
if (!netlink_capable(sock, NL_CFG_F_NONROOT_RECV))
return -EPERM;
err = netlink_realloc_groups(sk);
if (err)
return err;
}
if (nlk->portid) {
if (nladdr->nl_pid != nlk->portid)
return -EINVAL;
} else {
err = nladdr->nl_pid ?
netlink_insert(sk, net, nladdr->nl_pid) :
netlink_autobind(sock);
if (err)
return err;
}
if (!nladdr->nl_groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
return 0;
netlink_table_grab();
netlink_update_subscriptions(sk, nlk->subscriptions +
hweight32(nladdr->nl_groups) -
hweight32(nlk->groups[0]));
nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | nladdr->nl_groups;
netlink_update_listeners(sk);
netlink_table_ungrab();
if (nlk->netlink_bind && nlk->groups[0]) {
int i;
for (i=0; i<nlk->ngroups; i++) {
if (test_bit(i, nlk->groups))
nlk->netlink_bind(i);
}
}
return 0;
}
static int netlink_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
int err = 0;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
if (alen < sizeof(addr->sa_family))
return -EINVAL;
if (addr->sa_family == AF_UNSPEC) {
sk->sk_state = NETLINK_UNCONNECTED;
nlk->dst_portid = 0;
nlk->dst_group = 0;
return 0;
}
if (addr->sa_family != AF_NETLINK)
return -EINVAL;
/* Only superuser is allowed to send multicasts */
if (nladdr->nl_groups && !netlink_capable(sock, NL_CFG_F_NONROOT_SEND))
return -EPERM;
if (!nlk->portid)
err = netlink_autobind(sock);
if (err == 0) {
sk->sk_state = NETLINK_CONNECTED;
nlk->dst_portid = nladdr->nl_pid;
nlk->dst_group = ffs(nladdr->nl_groups);
}
return err;
}
static int netlink_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
nladdr->nl_family = AF_NETLINK;
nladdr->nl_pad = 0;
*addr_len = sizeof(*nladdr);
if (peer) {
nladdr->nl_pid = nlk->dst_portid;
nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
} else {
nladdr->nl_pid = nlk->portid;
nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
}
return 0;
}
static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
{
struct sock *sock;
struct netlink_sock *nlk;
sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
if (!sock)
return ERR_PTR(-ECONNREFUSED);
/* Don't bother queuing skb if kernel socket has no input function */
nlk = nlk_sk(sock);
if (sock->sk_state == NETLINK_CONNECTED &&
nlk->dst_portid != nlk_sk(ssk)->portid) {
sock_put(sock);
return ERR_PTR(-ECONNREFUSED);
}
return sock;
}
struct sock *netlink_getsockbyfilp(struct file *filp)
{
struct inode *inode = file_inode(filp);
struct sock *sock;
if (!S_ISSOCK(inode->i_mode))
return ERR_PTR(-ENOTSOCK);
sock = SOCKET_I(inode)->sk;
if (sock->sk_family != AF_NETLINK)
return ERR_PTR(-EINVAL);
sock_hold(sock);
return sock;
}
static struct sk_buff *netlink_alloc_large_skb(unsigned int size,
int broadcast)
{
struct sk_buff *skb;
void *data;
if (size <= NLMSG_GOODSIZE || broadcast)
return alloc_skb(size, GFP_KERNEL);
size = SKB_DATA_ALIGN(size) +
SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
data = vmalloc(size);
if (data == NULL)
return NULL;
skb = build_skb(data, size);
if (skb == NULL)
vfree(data);
else {
skb->head_frag = 0;
skb->destructor = netlink_skb_destructor;
}
return skb;
}
/*
* Attach a skb to a netlink socket.
* The caller must hold a reference to the destination socket. On error, the
* reference is dropped. The skb is not send to the destination, just all
* all error checks are performed and memory in the queue is reserved.
* Return values:
* < 0: error. skb freed, reference to sock dropped.
* 0: continue
* 1: repeat lookup - reference dropped while waiting for socket memory.
*/
int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
long *timeo, struct sock *ssk)
{
struct netlink_sock *nlk;
nlk = nlk_sk(sk);
if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
test_bit(NETLINK_CONGESTED, &nlk->state)) &&
!netlink_skb_is_mmaped(skb)) {
DECLARE_WAITQUEUE(wait, current);
if (!*timeo) {
if (!ssk || netlink_is_kernel(ssk))
netlink_overrun(sk);
sock_put(sk);
kfree_skb(skb);
return -EAGAIN;
}
__set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&nlk->wait, &wait);
if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
test_bit(NETLINK_CONGESTED, &nlk->state)) &&
!sock_flag(sk, SOCK_DEAD))
*timeo = schedule_timeout(*timeo);
__set_current_state(TASK_RUNNING);
remove_wait_queue(&nlk->wait, &wait);
sock_put(sk);
if (signal_pending(current)) {
kfree_skb(skb);
return sock_intr_errno(*timeo);
}
return 1;
}
netlink_skb_set_owner_r(skb, sk);
return 0;
}
static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
{
int len = skb->len;
netlink_deliver_tap(skb);
#ifdef CONFIG_NETLINK_MMAP
if (netlink_skb_is_mmaped(skb))
netlink_queue_mmaped_skb(sk, skb);
else if (netlink_rx_is_mmaped(sk))
netlink_ring_set_copied(sk, skb);
else
#endif /* CONFIG_NETLINK_MMAP */
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_data_ready(sk, len);
return len;
}
int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
{
int len = __netlink_sendskb(sk, skb);
sock_put(sk);
return len;
}
void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
{
kfree_skb(skb);
sock_put(sk);
}
static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
{
int delta;
WARN_ON(skb->sk != NULL);
if (netlink_skb_is_mmaped(skb))
return skb;
delta = skb->end - skb->tail;
if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
return skb;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, allocation);
if (!nskb)
return skb;
consume_skb(skb);
skb = nskb;
}
if (!pskb_expand_head(skb, 0, -delta, allocation))
skb->truesize -= delta;
return skb;
}
static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
struct sock *ssk)
{
int ret;
struct netlink_sock *nlk = nlk_sk(sk);
ret = -ECONNREFUSED;
if (nlk->netlink_rcv != NULL) {
/* We could do a netlink_deliver_tap(skb) here as well
* but since this is intended for the kernel only, we
* should rather let it stay under the hood.
*/
ret = skb->len;
netlink_skb_set_owner_r(skb, sk);
NETLINK_CB(skb).sk = ssk;
nlk->netlink_rcv(skb);
consume_skb(skb);
} else {
kfree_skb(skb);
}
sock_put(sk);
return ret;
}
int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
u32 portid, int nonblock)
{
struct sock *sk;
int err;
long timeo;
skb = netlink_trim(skb, gfp_any());
timeo = sock_sndtimeo(ssk, nonblock);
retry:
sk = netlink_getsockbyportid(ssk, portid);
if (IS_ERR(sk)) {
kfree_skb(skb);
return PTR_ERR(sk);
}
if (netlink_is_kernel(sk))
return netlink_unicast_kernel(sk, skb, ssk);
if (sk_filter(sk, skb)) {
err = skb->len;
kfree_skb(skb);
sock_put(sk);
return err;
}
err = netlink_attachskb(sk, skb, &timeo, ssk);
if (err == 1)
goto retry;
if (err)
return err;
return netlink_sendskb(sk, skb);
}
EXPORT_SYMBOL(netlink_unicast);
struct sk_buff *netlink_alloc_skb(struct sock *ssk, unsigned int size,
u32 dst_portid, gfp_t gfp_mask)
{
#ifdef CONFIG_NETLINK_MMAP
struct sock *sk = NULL;
struct sk_buff *skb;
struct netlink_ring *ring;
struct nl_mmap_hdr *hdr;
unsigned int maxlen;
sk = netlink_getsockbyportid(ssk, dst_portid);
if (IS_ERR(sk))
goto out;
ring = &nlk_sk(sk)->rx_ring;
/* fast-path without atomic ops for common case: non-mmaped receiver */
if (ring->pg_vec == NULL)
goto out_put;
skb = alloc_skb_head(gfp_mask);
if (skb == NULL)
goto err1;
spin_lock_bh(&sk->sk_receive_queue.lock);
/* check again under lock */
if (ring->pg_vec == NULL)
goto out_free;
maxlen = ring->frame_size - NL_MMAP_HDRLEN;
if (maxlen < size)
goto out_free;
netlink_forward_ring(ring);
hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
if (hdr == NULL)
goto err2;
netlink_ring_setup_skb(skb, sk, ring, hdr);
netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED);
atomic_inc(&ring->pending);
netlink_increment_head(ring);
spin_unlock_bh(&sk->sk_receive_queue.lock);
return skb;
err2:
kfree_skb(skb);
spin_unlock_bh(&sk->sk_receive_queue.lock);
netlink_overrun(sk);
err1:
sock_put(sk);
return NULL;
out_free:
kfree_skb(skb);
spin_unlock_bh(&sk->sk_receive_queue.lock);
out_put:
sock_put(sk);
out:
#endif
return alloc_skb(size, gfp_mask);
}
EXPORT_SYMBOL_GPL(netlink_alloc_skb);
int netlink_has_listeners(struct sock *sk, unsigned int group)
{
int res = 0;
struct listeners *listeners;
BUG_ON(!netlink_is_kernel(sk));
rcu_read_lock();
listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
res = test_bit(group - 1, listeners->masks);
rcu_read_unlock();
return res;
}
EXPORT_SYMBOL_GPL(netlink_has_listeners);
static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
!test_bit(NETLINK_CONGESTED, &nlk->state)) {
netlink_skb_set_owner_r(skb, sk);
__netlink_sendskb(sk, skb);
return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
}
return -1;
}
struct netlink_broadcast_data {
struct sock *exclude_sk;
struct net *net;
u32 portid;
u32 group;
int failure;
int delivery_failure;
int congested;
int delivered;
gfp_t allocation;
struct sk_buff *skb, *skb2;
int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
void *tx_data;
};
static int do_one_broadcast(struct sock *sk,
struct netlink_broadcast_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int val;
if (p->exclude_sk == sk)
goto out;
if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (!net_eq(sock_net(sk), p->net))
goto out;
if (p->failure) {
netlink_overrun(sk);
goto out;
}
sock_hold(sk);
if (p->skb2 == NULL) {
if (skb_shared(p->skb)) {
p->skb2 = skb_clone(p->skb, p->allocation);
} else {
p->skb2 = skb_get(p->skb);
/*
* skb ownership may have been set when
* delivered to a previous socket.
*/
skb_orphan(p->skb2);
}
}
if (p->skb2 == NULL) {
netlink_overrun(sk);
/* Clone failed. Notify ALL listeners. */
p->failure = 1;
if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
p->delivery_failure = 1;
} else if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
kfree_skb(p->skb2);
p->skb2 = NULL;
} else if (sk_filter(sk, p->skb2)) {
kfree_skb(p->skb2);
p->skb2 = NULL;
} else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
netlink_overrun(sk);
if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
p->delivery_failure = 1;
} else {
p->congested |= val;
p->delivered = 1;
p->skb2 = NULL;
}
sock_put(sk);
out:
return 0;
}
int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
u32 group, gfp_t allocation,
int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
void *filter_data)
{
struct net *net = sock_net(ssk);
struct netlink_broadcast_data info;
struct sock *sk;
skb = netlink_trim(skb, allocation);
info.exclude_sk = ssk;
info.net = net;
info.portid = portid;
info.group = group;
info.failure = 0;
info.delivery_failure = 0;
info.congested = 0;
info.delivered = 0;
info.allocation = allocation;
info.skb = skb;
info.skb2 = NULL;
info.tx_filter = filter;
info.tx_data = filter_data;
/* While we sleep in clone, do not allow to change socket list */
netlink_lock_table();
sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
do_one_broadcast(sk, &info);
consume_skb(skb);
netlink_unlock_table();
if (info.delivery_failure) {
kfree_skb(info.skb2);
return -ENOBUFS;
}
consume_skb(info.skb2);
if (info.delivered) {
if (info.congested && (allocation & __GFP_WAIT))
yield();
return 0;
}
return -ESRCH;
}
EXPORT_SYMBOL(netlink_broadcast_filtered);
int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
u32 group, gfp_t allocation)
{
return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
NULL, NULL);
}
EXPORT_SYMBOL(netlink_broadcast);
struct netlink_set_err_data {
struct sock *exclude_sk;
u32 portid;
u32 group;
int code;
};
static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int ret = 0;
if (sk == p->exclude_sk)
goto out;
if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
goto out;
if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
ret = 1;
goto out;
}
sk->sk_err = p->code;
sk->sk_error_report(sk);
out:
return ret;
}
/**
* netlink_set_err - report error to broadcast listeners
* @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
* @portid: the PORTID of a process that we want to skip (if any)
* @group: the broadcast group that will notice the error
* @code: error code, must be negative (as usual in kernelspace)
*
* This function returns the number of broadcast listeners that have set the
* NETLINK_RECV_NO_ENOBUFS socket option.
*/
int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
{
struct netlink_set_err_data info;
struct sock *sk;
int ret = 0;
info.exclude_sk = ssk;
info.portid = portid;
info.group = group;
/* sk->sk_err wants a positive error value */
info.code = -code;
read_lock(&nl_table_lock);
sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
ret += do_one_set_err(sk, &info);
read_unlock(&nl_table_lock);
return ret;
}
EXPORT_SYMBOL(netlink_set_err);
/* must be called with netlink table grabbed */
static void netlink_update_socket_mc(struct netlink_sock *nlk,
unsigned int group,
int is_new)
{
int old, new = !!is_new, subscriptions;
old = test_bit(group - 1, nlk->groups);
subscriptions = nlk->subscriptions - old + new;
if (new)
__set_bit(group - 1, nlk->groups);
else
__clear_bit(group - 1, nlk->groups);
netlink_update_subscriptions(&nlk->sk, subscriptions);
netlink_update_listeners(&nlk->sk);
}
static int netlink_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
unsigned int val = 0;
int err;
if (level != SOL_NETLINK)
return -ENOPROTOOPT;
if (optname != NETLINK_RX_RING && optname != NETLINK_TX_RING &&
optlen >= sizeof(int) &&
get_user(val, (unsigned int __user *)optval))
return -EFAULT;
switch (optname) {
case NETLINK_PKTINFO:
if (val)
nlk->flags |= NETLINK_RECV_PKTINFO;
else
nlk->flags &= ~NETLINK_RECV_PKTINFO;
err = 0;
break;
case NETLINK_ADD_MEMBERSHIP:
case NETLINK_DROP_MEMBERSHIP: {
if (!netlink_capable(sock, NL_CFG_F_NONROOT_RECV))
return -EPERM;
err = netlink_realloc_groups(sk);
if (err)
return err;
if (!val || val - 1 >= nlk->ngroups)
return -EINVAL;
netlink_table_grab();
netlink_update_socket_mc(nlk, val,
optname == NETLINK_ADD_MEMBERSHIP);
netlink_table_ungrab();
if (nlk->netlink_bind)
nlk->netlink_bind(val);
err = 0;
break;
}
case NETLINK_BROADCAST_ERROR:
if (val)
nlk->flags |= NETLINK_BROADCAST_SEND_ERROR;
else
nlk->flags &= ~NETLINK_BROADCAST_SEND_ERROR;
err = 0;
break;
case NETLINK_NO_ENOBUFS:
if (val) {
nlk->flags |= NETLINK_RECV_NO_ENOBUFS;
clear_bit(NETLINK_CONGESTED, &nlk->state);
wake_up_interruptible(&nlk->wait);
} else {
nlk->flags &= ~NETLINK_RECV_NO_ENOBUFS;
}
err = 0;
break;
#ifdef CONFIG_NETLINK_MMAP
case NETLINK_RX_RING:
case NETLINK_TX_RING: {
struct nl_mmap_req req;
/* Rings might consume more memory than queue limits, require
* CAP_NET_ADMIN.
*/
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (optlen < sizeof(req))
return -EINVAL;
if (copy_from_user(&req, optval, sizeof(req)))
return -EFAULT;
err = netlink_set_ring(sk, &req, false,
optname == NETLINK_TX_RING);
break;
}
#endif /* CONFIG_NETLINK_MMAP */
default:
err = -ENOPROTOOPT;
}
return err;
}
static int netlink_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int len, val, err;
if (level != SOL_NETLINK)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case NETLINK_PKTINFO:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
case NETLINK_BROADCAST_ERROR:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_BROADCAST_SEND_ERROR ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
case NETLINK_NO_ENOBUFS:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_RECV_NO_ENOBUFS ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
{
struct nl_pktinfo info;
info.group = NETLINK_CB(skb).dst_group;
put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
}
static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *addr = msg->msg_name;
u32 dst_portid;
u32 dst_group;
struct sk_buff *skb;
int err;
struct scm_cookie scm;
if (msg->msg_flags&MSG_OOB)
return -EOPNOTSUPP;
if (NULL == siocb->scm)
siocb->scm = &scm;
err = scm_send(sock, msg, siocb->scm, true);
if (err < 0)
return err;
if (msg->msg_namelen) {
err = -EINVAL;
if (addr->nl_family != AF_NETLINK)
goto out;
dst_portid = addr->nl_pid;
dst_group = ffs(addr->nl_groups);
err = -EPERM;
if ((dst_group || dst_portid) &&
!netlink_capable(sock, NL_CFG_F_NONROOT_SEND))
goto out;
} else {
dst_portid = nlk->dst_portid;
dst_group = nlk->dst_group;
}
if (!nlk->portid) {
err = netlink_autobind(sock);
if (err)
goto out;
}
if (netlink_tx_is_mmaped(sk) &&
msg->msg_iov->iov_base == NULL) {
err = netlink_mmap_sendmsg(sk, msg, dst_portid, dst_group,
siocb);
goto out;
}
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
err = -ENOBUFS;
skb = netlink_alloc_large_skb(len, dst_group);
if (skb == NULL)
goto out;
NETLINK_CB(skb).portid = nlk->portid;
NETLINK_CB(skb).dst_group = dst_group;
NETLINK_CB(skb).creds = siocb->scm->creds;
err = -EFAULT;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
kfree_skb(skb);
goto out;
}
err = security_netlink_send(sk, skb);
if (err) {
kfree_skb(skb);
goto out;
}
if (dst_group) {
atomic_inc(&skb->users);
netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
}
err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
out:
scm_destroy(siocb->scm);
return err;
}
static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int noblock = flags&MSG_DONTWAIT;
size_t copied;
struct sk_buff *skb, *data_skb;
int err, ret;
if (flags&MSG_OOB)
return -EOPNOTSUPP;
copied = 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (skb == NULL)
goto out;
data_skb = skb;
#ifdef CONFIG_COMPAT_NETLINK_MESSAGES
if (unlikely(skb_shinfo(skb)->frag_list)) {
/*
* If this skb has a frag_list, then here that means that we
* will have to use the frag_list skb's data for compat tasks
* and the regular skb's data for normal (non-compat) tasks.
*
* If we need to send the compat skb, assign it to the
* 'data_skb' variable so that it will be used below for data
* copying. We keep 'skb' for everything else, including
* freeing both later.
*/
if (flags & MSG_CMSG_COMPAT)
data_skb = skb_shinfo(skb)->frag_list;
}
#endif
msg->msg_namelen = 0;
copied = data_skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(data_skb);
err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
if (msg->msg_name) {
struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name;
addr->nl_family = AF_NETLINK;
addr->nl_pad = 0;
addr->nl_pid = NETLINK_CB(skb).portid;
addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
msg->msg_namelen = sizeof(*addr);
}
if (nlk->flags & NETLINK_RECV_PKTINFO)
netlink_cmsg_recv_pktinfo(msg, skb);
if (NULL == siocb->scm) {
memset(&scm, 0, sizeof(scm));
siocb->scm = &scm;
}
siocb->scm->creds = *NETLINK_CREDS(skb);
if (flags & MSG_TRUNC)
copied = data_skb->len;
skb_free_datagram(sk, skb);
if (nlk->cb_running &&
atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
ret = netlink_dump(sk);
if (ret) {
sk->sk_err = ret;
sk->sk_error_report(sk);
}
}
scm_recv(sock, msg, siocb->scm, flags);
out:
netlink_rcv_wake(sk);
return err ? : copied;
}
static void netlink_data_ready(struct sock *sk, int len)
{
BUG();
}
/*
* We export these functions to other modules. They provide a
* complete set of kernel non-blocking support for message
* queueing.
*/
struct sock *
__netlink_kernel_create(struct net *net, int unit, struct module *module,
struct netlink_kernel_cfg *cfg)
{
struct socket *sock;
struct sock *sk;
struct netlink_sock *nlk;
struct listeners *listeners = NULL;
struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
unsigned int groups;
BUG_ON(!nl_table);
if (unit < 0 || unit >= MAX_LINKS)
return NULL;
if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
return NULL;
/*
* We have to just have a reference on the net from sk, but don't
* get_net it. Besides, we cannot get and then put the net here.
* So we create one inside init_net and the move it to net.
*/
if (__netlink_create(&init_net, sock, cb_mutex, unit) < 0)
goto out_sock_release_nosk;
sk = sock->sk;
sk_change_net(sk, net);
if (!cfg || cfg->groups < 32)
groups = 32;
else
groups = cfg->groups;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
goto out_sock_release;
sk->sk_data_ready = netlink_data_ready;
if (cfg && cfg->input)
nlk_sk(sk)->netlink_rcv = cfg->input;
if (netlink_insert(sk, net, 0))
goto out_sock_release;
nlk = nlk_sk(sk);
nlk->flags |= NETLINK_KERNEL_SOCKET;
netlink_table_grab();
if (!nl_table[unit].registered) {
nl_table[unit].groups = groups;
rcu_assign_pointer(nl_table[unit].listeners, listeners);
nl_table[unit].cb_mutex = cb_mutex;
nl_table[unit].module = module;
if (cfg) {
nl_table[unit].bind = cfg->bind;
nl_table[unit].flags = cfg->flags;
if (cfg->compare)
nl_table[unit].compare = cfg->compare;
}
nl_table[unit].registered = 1;
} else {
kfree(listeners);
nl_table[unit].registered++;
}
netlink_table_ungrab();
return sk;
out_sock_release:
kfree(listeners);
netlink_kernel_release(sk);
return NULL;
out_sock_release_nosk:
sock_release(sock);
return NULL;
}
EXPORT_SYMBOL(__netlink_kernel_create);
void
netlink_kernel_release(struct sock *sk)
{
sk_release_kernel(sk);
}
EXPORT_SYMBOL(netlink_kernel_release);
int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
{
struct listeners *new, *old;
struct netlink_table *tbl = &nl_table[sk->sk_protocol];
if (groups < 32)
groups = 32;
if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
if (!new)
return -ENOMEM;
old = nl_deref_protected(tbl->listeners);
memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
rcu_assign_pointer(tbl->listeners, new);
kfree_rcu(old, rcu);
}
tbl->groups = groups;
return 0;
}
/**
* netlink_change_ngroups - change number of multicast groups
*
* This changes the number of multicast groups that are available
* on a certain netlink family. Note that it is not possible to
* change the number of groups to below 32. Also note that it does
* not implicitly call netlink_clear_multicast_users() when the
* number of groups is reduced.
*
* @sk: The kernel netlink socket, as returned by netlink_kernel_create().
* @groups: The new number of groups.
*/
int netlink_change_ngroups(struct sock *sk, unsigned int groups)
{
int err;
netlink_table_grab();
err = __netlink_change_ngroups(sk, groups);
netlink_table_ungrab();
return err;
}
void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
{
struct sock *sk;
struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
sk_for_each_bound(sk, &tbl->mc_list)
netlink_update_socket_mc(nlk_sk(sk), group, 0);
}
/**
* netlink_clear_multicast_users - kick off multicast listeners
*
* This function removes all listeners from the given group.
* @ksk: The kernel netlink socket, as returned by
* netlink_kernel_create().
* @group: The multicast group to clear.
*/
void netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
{
netlink_table_grab();
__netlink_clear_multicast_users(ksk, group);
netlink_table_ungrab();
}
struct nlmsghdr *
__nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
{
struct nlmsghdr *nlh;
int size = nlmsg_msg_size(len);
nlh = (struct nlmsghdr*)skb_put(skb, NLMSG_ALIGN(size));
nlh->nlmsg_type = type;
nlh->nlmsg_len = size;
nlh->nlmsg_flags = flags;
nlh->nlmsg_pid = portid;
nlh->nlmsg_seq = seq;
if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
return nlh;
}
EXPORT_SYMBOL(__nlmsg_put);
/*
* It looks a bit ugly.
* It would be better to create kernel thread.
*/
static int netlink_dump(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_callback *cb;
struct sk_buff *skb = NULL;
struct nlmsghdr *nlh;
int len, err = -ENOBUFS;
int alloc_size;
mutex_lock(nlk->cb_mutex);
if (!nlk->cb_running) {
err = -EINVAL;
goto errout_skb;
}
cb = &nlk->cb;
alloc_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
if (!netlink_rx_is_mmaped(sk) &&
atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
goto errout_skb;
skb = netlink_alloc_skb(sk, alloc_size, nlk->portid, GFP_KERNEL);
if (!skb)
goto errout_skb;
netlink_skb_set_owner_r(skb, sk);
len = cb->dump(skb, cb);
if (len > 0) {
mutex_unlock(nlk->cb_mutex);
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
return 0;
}
nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
if (!nlh)
goto errout_skb;
nl_dump_check_consistent(cb, nlh);
memcpy(nlmsg_data(nlh), &len, sizeof(len));
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
if (cb->done)
cb->done(cb);
nlk->cb_running = false;
mutex_unlock(nlk->cb_mutex);
module_put(cb->module);
consume_skb(cb->skb);
return 0;
errout_skb:
mutex_unlock(nlk->cb_mutex);
kfree_skb(skb);
return err;
}
int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
const struct nlmsghdr *nlh,
struct netlink_dump_control *control)
{
struct netlink_callback *cb;
struct sock *sk;
struct netlink_sock *nlk;
int ret;
/* Memory mapped dump requests need to be copied to avoid looping
* on the pending state in netlink_mmap_sendmsg() while the CB hold
* a reference to the skb.
*/
if (netlink_skb_is_mmaped(skb)) {
skb = skb_copy(skb, GFP_KERNEL);
if (skb == NULL)
return -ENOBUFS;
} else
atomic_inc(&skb->users);
sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
if (sk == NULL) {
ret = -ECONNREFUSED;
goto error_free;
}
nlk = nlk_sk(sk);
mutex_lock(nlk->cb_mutex);
/* A dump is in progress... */
if (nlk->cb_running) {
ret = -EBUSY;
goto error_unlock;
}
/* add reference of module which cb->dump belongs to */
if (!try_module_get(control->module)) {
ret = -EPROTONOSUPPORT;
goto error_unlock;
}
cb = &nlk->cb;
memset(cb, 0, sizeof(*cb));
cb->dump = control->dump;
cb->done = control->done;
cb->nlh = nlh;
cb->data = control->data;
cb->module = control->module;
cb->min_dump_alloc = control->min_dump_alloc;
cb->skb = skb;
nlk->cb_running = true;
mutex_unlock(nlk->cb_mutex);
ret = netlink_dump(sk);
sock_put(sk);
if (ret)
return ret;
/* We successfully started a dump, by returning -EINTR we
* signal not to send ACK even if it was requested.
*/
return -EINTR;
error_unlock:
sock_put(sk);
mutex_unlock(nlk->cb_mutex);
error_free:
kfree_skb(skb);
return ret;
}
EXPORT_SYMBOL(__netlink_dump_start);
void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
{
struct sk_buff *skb;
struct nlmsghdr *rep;
struct nlmsgerr *errmsg;
size_t payload = sizeof(*errmsg);
/* error messages get the original request appened */
if (err)
payload += nlmsg_len(nlh);
skb = netlink_alloc_skb(in_skb->sk, nlmsg_total_size(payload),
NETLINK_CB(in_skb).portid, GFP_KERNEL);
if (!skb) {
struct sock *sk;
sk = netlink_lookup(sock_net(in_skb->sk),
in_skb->sk->sk_protocol,
NETLINK_CB(in_skb).portid);
if (sk) {
sk->sk_err = ENOBUFS;
sk->sk_error_report(sk);
sock_put(sk);
}
return;
}
rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
NLMSG_ERROR, payload, 0);
errmsg = nlmsg_data(rep);
errmsg->error = err;
memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh));
netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
}
EXPORT_SYMBOL(netlink_ack);
int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
struct nlmsghdr *))
{
struct nlmsghdr *nlh;
int err;
while (skb->len >= nlmsg_total_size(0)) {
int msglen;
nlh = nlmsg_hdr(skb);
err = 0;
if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
return 0;
/* Only requests are handled by the kernel */
if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
goto ack;
/* Skip control messages */
if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
goto ack;
err = cb(skb, nlh);
if (err == -EINTR)
goto skip;
ack:
if (nlh->nlmsg_flags & NLM_F_ACK || err)
netlink_ack(skb, nlh, err);
skip:
msglen = NLMSG_ALIGN(nlh->nlmsg_len);
if (msglen > skb->len)
msglen = skb->len;
skb_pull(skb, msglen);
}
return 0;
}
EXPORT_SYMBOL(netlink_rcv_skb);
/**
* nlmsg_notify - send a notification netlink message
* @sk: netlink socket to use
* @skb: notification message
* @portid: destination netlink portid for reports or 0
* @group: destination multicast group or 0
* @report: 1 to report back, 0 to disable
* @flags: allocation flags
*/
int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
unsigned int group, int report, gfp_t flags)
{
int err = 0;
if (group) {
int exclude_portid = 0;
if (report) {
atomic_inc(&skb->users);
exclude_portid = portid;
}
/* errors reported via destination sk->sk_err, but propagate
* delivery errors if NETLINK_BROADCAST_ERROR flag is set */
err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
}
if (report) {
int err2;
err2 = nlmsg_unicast(sk, skb, portid);
if (!err || err == -ESRCH)
err = err2;
}
return err;
}
EXPORT_SYMBOL(nlmsg_notify);
#ifdef CONFIG_PROC_FS
struct nl_seq_iter {
struct seq_net_private p;
int link;
int hash_idx;
};
static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
{
struct nl_seq_iter *iter = seq->private;
int i, j;
struct sock *s;
loff_t off = 0;
for (i = 0; i < MAX_LINKS; i++) {
struct nl_portid_hash *hash = &nl_table[i].hash;
for (j = 0; j <= hash->mask; j++) {
sk_for_each(s, &hash->table[j]) {
if (sock_net(s) != seq_file_net(seq))
continue;
if (off == pos) {
iter->link = i;
iter->hash_idx = j;
return s;
}
++off;
}
}
}
return NULL;
}
static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(nl_table_lock)
{
read_lock(&nl_table_lock);
return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *s;
struct nl_seq_iter *iter;
struct net *net;
int i, j;
++*pos;
if (v == SEQ_START_TOKEN)
return netlink_seq_socket_idx(seq, 0);
net = seq_file_net(seq);
iter = seq->private;
s = v;
do {
s = sk_next(s);
} while (s && !nl_table[s->sk_protocol].compare(net, s));
if (s)
return s;
i = iter->link;
j = iter->hash_idx + 1;
do {
struct nl_portid_hash *hash = &nl_table[i].hash;
for (; j <= hash->mask; j++) {
s = sk_head(&hash->table[j]);
while (s && !nl_table[s->sk_protocol].compare(net, s))
s = sk_next(s);
if (s) {
iter->link = i;
iter->hash_idx = j;
return s;
}
}
j = 0;
} while (++i < MAX_LINKS);
return NULL;
}
static void netlink_seq_stop(struct seq_file *seq, void *v)
__releases(nl_table_lock)
{
read_unlock(&nl_table_lock);
}
static int netlink_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN) {
seq_puts(seq,
"sk Eth Pid Groups "
"Rmem Wmem Dump Locks Drops Inode\n");
} else {
struct sock *s = v;
struct netlink_sock *nlk = nlk_sk(s);
seq_printf(seq, "%pK %-3d %-6u %08x %-8d %-8d %d %-8d %-8d %-8lu\n",
s,
s->sk_protocol,
nlk->portid,
nlk->groups ? (u32)nlk->groups[0] : 0,
sk_rmem_alloc_get(s),
sk_wmem_alloc_get(s),
nlk->cb_running,
atomic_read(&s->sk_refcnt),
atomic_read(&s->sk_drops),
sock_i_ino(s)
);
}
return 0;
}
static const struct seq_operations netlink_seq_ops = {
.start = netlink_seq_start,
.next = netlink_seq_next,
.stop = netlink_seq_stop,
.show = netlink_seq_show,
};
static int netlink_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &netlink_seq_ops,
sizeof(struct nl_seq_iter));
}
static const struct file_operations netlink_seq_fops = {
.owner = THIS_MODULE,
.open = netlink_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
int netlink_register_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&netlink_chain, nb);
}
EXPORT_SYMBOL(netlink_register_notifier);
int netlink_unregister_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_unregister(&netlink_chain, nb);
}
EXPORT_SYMBOL(netlink_unregister_notifier);
static const struct proto_ops netlink_ops = {
.family = PF_NETLINK,
.owner = THIS_MODULE,
.release = netlink_release,
.bind = netlink_bind,
.connect = netlink_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = netlink_getname,
.poll = netlink_poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = netlink_setsockopt,
.getsockopt = netlink_getsockopt,
.sendmsg = netlink_sendmsg,
.recvmsg = netlink_recvmsg,
.mmap = netlink_mmap,
.sendpage = sock_no_sendpage,
};
static const struct net_proto_family netlink_family_ops = {
.family = PF_NETLINK,
.create = netlink_create,
.owner = THIS_MODULE, /* for consistency 8) */
};
static int __net_init netlink_net_init(struct net *net)
{
#ifdef CONFIG_PROC_FS
if (!proc_create("netlink", 0, net->proc_net, &netlink_seq_fops))
return -ENOMEM;
#endif
return 0;
}
static void __net_exit netlink_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
remove_proc_entry("netlink", net->proc_net);
#endif
}
static void __init netlink_add_usersock_entry(void)
{
struct listeners *listeners;
int groups = 32;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
netlink_table_grab();
nl_table[NETLINK_USERSOCK].groups = groups;
rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
nl_table[NETLINK_USERSOCK].registered = 1;
nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
netlink_table_ungrab();
}
static struct pernet_operations __net_initdata netlink_net_ops = {
.init = netlink_net_init,
.exit = netlink_net_exit,
};
static int __init netlink_proto_init(void)
{
int i;
unsigned long limit;
unsigned int order;
int err = proto_register(&netlink_proto, 0);
if (err != 0)
goto out;
BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
if (!nl_table)
goto panic;
if (totalram_pages >= (128 * 1024))
limit = totalram_pages >> (21 - PAGE_SHIFT);
else
limit = totalram_pages >> (23 - PAGE_SHIFT);
order = get_bitmask_order(limit) - 1 + PAGE_SHIFT;
limit = (1UL << order) / sizeof(struct hlist_head);
order = get_bitmask_order(min(limit, (unsigned long)UINT_MAX)) - 1;
for (i = 0; i < MAX_LINKS; i++) {
struct nl_portid_hash *hash = &nl_table[i].hash;
hash->table = nl_portid_hash_zalloc(1 * sizeof(*hash->table));
if (!hash->table) {
while (i-- > 0)
nl_portid_hash_free(nl_table[i].hash.table,
1 * sizeof(*hash->table));
kfree(nl_table);
goto panic;
}
hash->max_shift = order;
hash->shift = 0;
hash->mask = 0;
hash->rehash_time = jiffies;
nl_table[i].compare = netlink_compare;
}
INIT_LIST_HEAD(&netlink_tap_all);
netlink_add_usersock_entry();
sock_register(&netlink_family_ops);
register_pernet_subsys(&netlink_net_ops);
/* The netlink device handler may be needed early. */
rtnetlink_init();
out:
return err;
panic:
panic("netlink_init: Cannot allocate nl_table\n");
}
core_initcall(netlink_proto_init);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_21 |
crossvul-cpp_data_bad_5660_0 | /*
* IPv6 output functions
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Based on linux/net/ipv4/ip_output.c
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Changes:
* A.N.Kuznetsov : airthmetics in fragmentation.
* extension headers are implemented.
* route changes now work.
* ip6_forward does not confuse sniffers.
* etc.
*
* H. von Brand : Added missing #include <linux/string.h>
* Imran Patel : frag id should be in NBO
* Kazunori MIYAZAWA @USAGI
* : add ip6_append_data and related functions
* for datagram xmit
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/in6.h>
#include <linux/tcp.h>
#include <linux/route.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv6.h>
#include <net/sock.h>
#include <net/snmp.h>
#include <net/ipv6.h>
#include <net/ndisc.h>
#include <net/protocol.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/rawv6.h>
#include <net/icmp.h>
#include <net/xfrm.h>
#include <net/checksum.h>
#include <linux/mroute6.h>
int __ip6_local_out(struct sk_buff *skb)
{
int len;
len = skb->len - sizeof(struct ipv6hdr);
if (len > IPV6_MAXPLEN)
len = 0;
ipv6_hdr(skb)->payload_len = htons(len);
return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL,
skb_dst(skb)->dev, dst_output);
}
int ip6_local_out(struct sk_buff *skb)
{
int err;
err = __ip6_local_out(skb);
if (likely(err == 1))
err = dst_output(skb);
return err;
}
EXPORT_SYMBOL_GPL(ip6_local_out);
static int ip6_finish_output2(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct net_device *dev = dst->dev;
struct neighbour *neigh;
struct in6_addr *nexthop;
int ret;
skb->protocol = htons(ETH_P_IPV6);
skb->dev = dev;
if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(skb->sk) &&
((mroute6_socket(dev_net(dev), skb) &&
!(IP6CB(skb)->flags & IP6SKB_FORWARDED)) ||
ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr))) {
struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC);
/* Do not check for IFF_ALLMULTI; multicast routing
is not supported in any case.
*/
if (newskb)
NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING,
newskb, NULL, newskb->dev,
dev_loopback_xmit);
if (ipv6_hdr(skb)->hop_limit == 0) {
IP6_INC_STATS(dev_net(dev), idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
}
IP6_UPD_PO_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTMCAST,
skb->len);
if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <=
IPV6_ADDR_SCOPE_NODELOCAL &&
!(dev->flags & IFF_LOOPBACK)) {
kfree_skb(skb);
return 0;
}
}
rcu_read_lock_bh();
nexthop = rt6_nexthop((struct rt6_info *)dst, &ipv6_hdr(skb)->daddr);
neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop);
if (unlikely(!neigh))
neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false);
if (!IS_ERR(neigh)) {
ret = dst_neigh_output(dst, neigh, skb);
rcu_read_unlock_bh();
return ret;
}
rcu_read_unlock_bh();
IP6_INC_STATS_BH(dev_net(dst->dev),
ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
return -EINVAL;
}
static int ip6_finish_output(struct sk_buff *skb)
{
if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) ||
dst_allfrag(skb_dst(skb)))
return ip6_fragment(skb, ip6_finish_output2);
else
return ip6_finish_output2(skb);
}
int ip6_output(struct sk_buff *skb)
{
struct net_device *dev = skb_dst(skb)->dev;
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
if (unlikely(idev->cnf.disable_ipv6)) {
IP6_INC_STATS(dev_net(dev), idev,
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return 0;
}
return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, skb, NULL, dev,
ip6_finish_output,
!(IP6CB(skb)->flags & IP6SKB_REROUTED));
}
/*
* xmit an sk_buff (used by TCP, SCTP and DCCP)
*/
int ip6_xmit(struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6,
struct ipv6_txoptions *opt, int tclass)
{
struct net *net = sock_net(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct in6_addr *first_hop = &fl6->daddr;
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr;
u8 proto = fl6->flowi6_proto;
int seg_len = skb->len;
int hlimit = -1;
u32 mtu;
if (opt) {
unsigned int head_room;
/* First: exthdrs may take lots of space (~8K for now)
MAX_HEADER is not enough.
*/
head_room = opt->opt_nflen + opt->opt_flen;
seg_len += head_room;
head_room += sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev);
if (skb_headroom(skb) < head_room) {
struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room);
if (skb2 == NULL) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
return -ENOBUFS;
}
consume_skb(skb);
skb = skb2;
skb_set_owner_w(skb, sk);
}
if (opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop);
}
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
/*
* Fill in the IPv6 header
*/
if (np)
hlimit = np->hop_limit;
if (hlimit < 0)
hlimit = ip6_dst_hoplimit(dst);
ip6_flow_hdr(hdr, tclass, fl6->flowlabel);
hdr->payload_len = htons(seg_len);
hdr->nexthdr = proto;
hdr->hop_limit = hlimit;
hdr->saddr = fl6->saddr;
hdr->daddr = *first_hop;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
mtu = dst_mtu(dst);
if ((skb->len <= mtu) || skb->local_df || skb_is_gso(skb)) {
IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUT, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL,
dst->dev, dst_output);
}
skb->dev = dst->dev;
ipv6_local_error(sk, EMSGSIZE, fl6, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
EXPORT_SYMBOL(ip6_xmit);
static int ip6_call_ra_chain(struct sk_buff *skb, int sel)
{
struct ip6_ra_chain *ra;
struct sock *last = NULL;
read_lock(&ip6_ra_lock);
for (ra = ip6_ra_chain; ra; ra = ra->next) {
struct sock *sk = ra->sk;
if (sk && ra->sel == sel &&
(!sk->sk_bound_dev_if ||
sk->sk_bound_dev_if == skb->dev->ifindex)) {
if (last) {
struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2)
rawv6_rcv(last, skb2);
}
last = sk;
}
}
if (last) {
rawv6_rcv(last, skb);
read_unlock(&ip6_ra_lock);
return 1;
}
read_unlock(&ip6_ra_lock);
return 0;
}
static int ip6_forward_proxy_check(struct sk_buff *skb)
{
struct ipv6hdr *hdr = ipv6_hdr(skb);
u8 nexthdr = hdr->nexthdr;
__be16 frag_off;
int offset;
if (ipv6_ext_hdr(nexthdr)) {
offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off);
if (offset < 0)
return 0;
} else
offset = sizeof(struct ipv6hdr);
if (nexthdr == IPPROTO_ICMPV6) {
struct icmp6hdr *icmp6;
if (!pskb_may_pull(skb, (skb_network_header(skb) +
offset + 1 - skb->data)))
return 0;
icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset);
switch (icmp6->icmp6_type) {
case NDISC_ROUTER_SOLICITATION:
case NDISC_ROUTER_ADVERTISEMENT:
case NDISC_NEIGHBOUR_SOLICITATION:
case NDISC_NEIGHBOUR_ADVERTISEMENT:
case NDISC_REDIRECT:
/* For reaction involving unicast neighbor discovery
* message destined to the proxied address, pass it to
* input function.
*/
return 1;
default:
break;
}
}
/*
* The proxying router can't forward traffic sent to a link-local
* address, so signal the sender and discard the packet. This
* behavior is clarified by the MIPv6 specification.
*/
if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) {
dst_link_failure(skb);
return -1;
}
return 0;
}
static inline int ip6_forward_finish(struct sk_buff *skb)
{
return dst_output(skb);
}
int ip6_forward(struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct ipv6hdr *hdr = ipv6_hdr(skb);
struct inet6_skb_parm *opt = IP6CB(skb);
struct net *net = dev_net(dst->dev);
u32 mtu;
if (net->ipv6.devconf_all->forwarding == 0)
goto error;
if (skb_warn_if_lro(skb))
goto drop;
if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS);
goto drop;
}
if (skb->pkt_type != PACKET_HOST)
goto drop;
skb_forward_csum(skb);
/*
* We DO NOT make any processing on
* RA packets, pushing them to user level AS IS
* without ane WARRANTY that application will be able
* to interpret them. The reason is that we
* cannot make anything clever here.
*
* We are not end-node, so that if packet contains
* AH/ESP, we cannot make anything.
* Defragmentation also would be mistake, RA packets
* cannot be fragmented, because there is no warranty
* that different fragments will go along one path. --ANK
*/
if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) {
if (ip6_call_ra_chain(skb, ntohs(opt->ra)))
return 0;
}
/*
* check and decrement ttl
*/
if (hdr->hop_limit <= 1) {
/* Force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS);
kfree_skb(skb);
return -ETIMEDOUT;
}
/* XXX: idev->cnf.proxy_ndp? */
if (net->ipv6.devconf_all->proxy_ndp &&
pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) {
int proxied = ip6_forward_proxy_check(skb);
if (proxied > 0)
return ip6_input(skb);
else if (proxied < 0) {
IP6_INC_STATS(net, ip6_dst_idev(dst),
IPSTATS_MIB_INDISCARDS);
goto drop;
}
}
if (!xfrm6_route_forward(skb)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS);
goto drop;
}
dst = skb_dst(skb);
/* IPv6 specs say nothing about it, but it is clear that we cannot
send redirects to source routed frames.
We don't send redirects to frames decapsulated from IPsec.
*/
if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) {
struct in6_addr *target = NULL;
struct inet_peer *peer;
struct rt6_info *rt;
/*
* incoming and outgoing devices are the same
* send a redirect.
*/
rt = (struct rt6_info *) dst;
if (rt->rt6i_flags & RTF_GATEWAY)
target = &rt->rt6i_gateway;
else
target = &hdr->daddr;
peer = inet_getpeer_v6(net->ipv6.peers, &rt->rt6i_dst.addr, 1);
/* Limit redirects both by destination (here)
and by source (inside ndisc_send_redirect)
*/
if (inet_peer_xrlim_allow(peer, 1*HZ))
ndisc_send_redirect(skb, target);
if (peer)
inet_putpeer(peer);
} else {
int addrtype = ipv6_addr_type(&hdr->saddr);
/* This check is security critical. */
if (addrtype == IPV6_ADDR_ANY ||
addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK))
goto error;
if (addrtype & IPV6_ADDR_LINKLOCAL) {
icmpv6_send(skb, ICMPV6_DEST_UNREACH,
ICMPV6_NOT_NEIGHBOUR, 0);
goto error;
}
}
mtu = dst_mtu(dst);
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
if ((!skb->local_df && skb->len > mtu && !skb_is_gso(skb)) ||
(IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu)) {
/* Again, force OUTPUT device used as source address */
skb->dev = dst->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS);
IP6_INC_STATS_BH(net,
ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (skb_cow(skb, dst->dev->hard_header_len)) {
IP6_INC_STATS(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS);
goto drop;
}
hdr = ipv6_hdr(skb);
/* Mangling hops number delayed to point after skb COW */
hdr->hop_limit--;
IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS);
IP6_ADD_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len);
return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, skb, skb->dev, dst->dev,
ip6_forward_finish);
error:
IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS);
drop:
kfree_skb(skb);
return -EINVAL;
}
static void ip6_copy_metadata(struct sk_buff *to, struct sk_buff *from)
{
to->pkt_type = from->pkt_type;
to->priority = from->priority;
to->protocol = from->protocol;
skb_dst_drop(to);
skb_dst_set(to, dst_clone(skb_dst(from)));
to->dev = from->dev;
to->mark = from->mark;
#ifdef CONFIG_NET_SCHED
to->tc_index = from->tc_index;
#endif
nf_copy(to, from);
#if IS_ENABLED(CONFIG_NETFILTER_XT_TARGET_TRACE)
to->nf_trace = from->nf_trace;
#endif
skb_copy_secmark(to, from);
}
int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info*)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk ? inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id = 0;
int ptr, offset = 0, err=0;
u8 *prevhdr, nexthdr = 0;
struct net *net = dev_net(skb_dst(skb)->dev);
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (unlikely(!skb->local_df && skb->len > mtu) ||
(IP6CB(skb)->frag_max_size &&
IP6CB(skb)->frag_max_size > mtu)) {
if (skb->sk && dst_allfrag(skb_dst(skb)))
sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK);
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return -EMSGSIZE;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
mtu -= hlen + sizeof(struct frag_hdr);
if (skb_has_frag_list(skb)) {
int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < hlen)
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
return -ENOMEM;
}
__skb_pull(skb, hlen);
fh = (struct frag_hdr*)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
ipv6_select_ident(fh, rt);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
frag_id = fh->identification;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr*)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next != NULL)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(skb);
if(!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
ip6_rt_put(rt);
return 0;
}
while (frag) {
skb = frag->next;
kfree_skb(frag);
frag = skb;
}
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
ip6_rt_put(rt);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
if ((skb->ip_summed == CHECKSUM_PARTIAL) &&
skb_checksum_help(skb))
goto fail;
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
*prevhdr = NEXTHDR_FRAGMENT;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while(left > 0) {
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/*
* Allocate buffer.
*/
if ((frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC)) == NULL) {
NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n");
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
if (!frag_id) {
ipv6_select_ident(fh, rt);
frag_id = fh->identification;
} else
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
if (skb_copy_bits(skb, ptr, skb_transport_header(frag), len))
BUG();
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
consume_skb(skb);
return err;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
static inline int ip6_rt_check(const struct rt6key *rt_key,
const struct in6_addr *fl_addr,
const struct in6_addr *addr_cache)
{
return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) &&
(addr_cache == NULL || !ipv6_addr_equal(fl_addr, addr_cache));
}
static struct dst_entry *ip6_sk_dst_check(struct sock *sk,
struct dst_entry *dst,
const struct flowi6 *fl6)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct rt6_info *rt = (struct rt6_info *)dst;
if (!dst)
goto out;
/* Yes, checking route validity in not connected
* case is not very simple. Take into account,
* that we do not support routing by source, TOS,
* and MSG_DONTROUTE --ANK (980726)
*
* 1. ip6_rt_check(): If route was host route,
* check that cached destination is current.
* If it is network route, we still may
* check its validity using saved pointer
* to the last used address: daddr_cache.
* We do not want to save whole address now,
* (because main consumer of this service
* is tcp, which has not this problem),
* so that the last trick works only on connected
* sockets.
* 2. oif also should be the same.
*/
if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) ||
#ifdef CONFIG_IPV6_SUBTREES
ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) ||
#endif
(fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) {
dst_release(dst);
dst = NULL;
}
out:
return dst;
}
static int ip6_dst_lookup_tail(struct sock *sk,
struct dst_entry **dst, struct flowi6 *fl6)
{
struct net *net = sock_net(sk);
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
struct neighbour *n;
struct rt6_info *rt;
#endif
int err;
if (*dst == NULL)
*dst = ip6_route_output(net, sk, fl6);
if ((err = (*dst)->error))
goto out_err_release;
if (ipv6_addr_any(&fl6->saddr)) {
struct rt6_info *rt = (struct rt6_info *) *dst;
err = ip6_route_get_saddr(net, rt, &fl6->daddr,
sk ? inet6_sk(sk)->srcprefs : 0,
&fl6->saddr);
if (err)
goto out_err_release;
}
#ifdef CONFIG_IPV6_OPTIMISTIC_DAD
/*
* Here if the dst entry we've looked up
* has a neighbour entry that is in the INCOMPLETE
* state and the src address from the flow is
* marked as OPTIMISTIC, we release the found
* dst entry and replace it instead with the
* dst entry of the nexthop router
*/
rt = (struct rt6_info *) *dst;
rcu_read_lock_bh();
n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt, &fl6->daddr));
err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0;
rcu_read_unlock_bh();
if (err) {
struct inet6_ifaddr *ifp;
struct flowi6 fl_gw6;
int redirect;
ifp = ipv6_get_ifaddr(net, &fl6->saddr,
(*dst)->dev, 1);
redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC);
if (ifp)
in6_ifa_put(ifp);
if (redirect) {
/*
* We need to get the dst entry for the
* default router instead
*/
dst_release(*dst);
memcpy(&fl_gw6, fl6, sizeof(struct flowi6));
memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr));
*dst = ip6_route_output(net, sk, &fl_gw6);
if ((err = (*dst)->error))
goto out_err_release;
}
}
#endif
return 0;
out_err_release:
if (err == -ENETUNREACH)
IP6_INC_STATS_BH(net, NULL, IPSTATS_MIB_OUTNOROUTES);
dst_release(*dst);
*dst = NULL;
return err;
}
/**
* ip6_dst_lookup - perform route lookup on flow
* @sk: socket which provides route info
* @dst: pointer to dst_entry * for result
* @fl6: flow to lookup
*
* This function performs a route lookup on the given flow.
*
* It returns zero on success, or a standard errno code on error.
*/
int ip6_dst_lookup(struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6)
{
*dst = NULL;
return ip6_dst_lookup_tail(sk, dst, fl6);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup);
/**
* ip6_dst_lookup_flow - perform route lookup on flow with ipsec
* @sk: socket which provides route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
* @can_sleep: we are in a sleepable context
*
* This function performs a route lookup on the given flow.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst,
bool can_sleep)
{
struct dst_entry *dst = NULL;
int err;
err = ip6_dst_lookup_tail(sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
if (can_sleep)
fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP;
return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow);
/**
* ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow
* @sk: socket which provides the dst cache and route info
* @fl6: flow to lookup
* @final_dst: final destination address for ipsec lookup
* @can_sleep: we are in a sleepable context
*
* This function performs a route lookup on the given flow with the
* possibility of using the cached route in the socket if it is valid.
* It will take the socket dst lock when operating on the dst cache.
* As a result, this function can only be used in process context.
*
* It returns a valid dst pointer on success, or a pointer encoded
* error code.
*/
struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6,
const struct in6_addr *final_dst,
bool can_sleep)
{
struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie);
int err;
dst = ip6_sk_dst_check(sk, dst, fl6);
err = ip6_dst_lookup_tail(sk, &dst, fl6);
if (err)
return ERR_PTR(err);
if (final_dst)
fl6->daddr = *final_dst;
if (can_sleep)
fl6->flowi6_flags |= FLOWI_FLAG_CAN_SLEEP;
return xfrm_lookup(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0);
}
EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow);
static inline int ip6_ufo_append_data(struct sock *sk,
int getfrag(void *from, char *to, int offset, int len,
int odd, struct sk_buff *skb),
void *from, int length, int hh_len, int fragheaderlen,
int transhdrlen, int mtu,unsigned int flags,
struct rt6_info *rt)
{
struct sk_buff *skb;
int err;
/* There is support for UDP large send offload by network
* device, so create one single skb packet containing complete
* udp datagram
*/
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) {
skb = sock_alloc_send_skb(sk,
hh_len + fragheaderlen + transhdrlen + 20,
(flags & MSG_DONTWAIT), &err);
if (skb == NULL)
return err;
/* reserve space for Hardware header */
skb_reserve(skb, hh_len);
/* create space for UDP/IP header */
skb_put(skb,fragheaderlen + transhdrlen);
/* initialize network header pointer */
skb_reset_network_header(skb);
/* initialize protocol header pointer */
skb->transport_header = skb->network_header + fragheaderlen;
skb->ip_summed = CHECKSUM_PARTIAL;
skb->csum = 0;
}
err = skb_append_datato_frags(sk,skb, getfrag, from,
(length - transhdrlen));
if (!err) {
struct frag_hdr fhdr;
/* Specify the length of each IPv6 datagram fragment.
* It has to be a multiple of 8.
*/
skb_shinfo(skb)->gso_size = (mtu - fragheaderlen -
sizeof(struct frag_hdr)) & ~7;
skb_shinfo(skb)->gso_type = SKB_GSO_UDP;
ipv6_select_ident(&fhdr, rt);
skb_shinfo(skb)->ip6_frag_id = fhdr.identification;
__skb_queue_tail(&sk->sk_write_queue, skb);
return 0;
}
/* There is not enough support do UPD LSO,
* so follow normal path
*/
kfree_skb(skb);
return err;
}
static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src,
gfp_t gfp)
{
return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL;
}
static void ip6_append_data_mtu(int *mtu,
int *maxfraglen,
unsigned int fragheaderlen,
struct sk_buff *skb,
struct rt6_info *rt)
{
if (!(rt->dst.flags & DST_XFRM_TUNNEL)) {
if (skb == NULL) {
/* first fragment, reserve header_len */
*mtu = *mtu - rt->dst.header_len;
} else {
/*
* this fragment is not first, the headers
* space is regarded as data space.
*/
*mtu = dst_mtu(rt->dst.path);
}
*maxfraglen = ((*mtu - fragheaderlen) & ~7)
+ fragheaderlen - sizeof(struct frag_hdr);
}
}
int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen;
int exthdrlen;
int dst_exthdrlen;
int hh_len;
int mtu;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
exthdrlen = (opt ? opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM)
sock_tx_timestamp(sk, &tx_flags);
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if (length > mtu) {
int proto = sk->sk_protocol;
if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
if (proto == IPPROTO_UDP &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
}
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (skb == NULL || skb_prev == NULL)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->ip_summed = CHECKSUM_NONE;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
EXPORT_SYMBOL_GPL(ip6_append_data);
static void ip6_cork_release(struct inet_sock *inet, struct ipv6_pinfo *np)
{
if (np->cork.opt) {
kfree(np->cork.opt->dst0opt);
kfree(np->cork.opt->dst1opt);
kfree(np->cork.opt->hopopt);
kfree(np->cork.opt->srcrt);
kfree(np->cork.opt);
np->cork.opt = NULL;
}
if (inet->cork.base.dst) {
dst_release(inet->cork.base.dst);
inet->cork.base.dst = NULL;
inet->cork.base.flags &= ~IPCORK_ALLFRAG;
}
memset(&inet->cork.fl, 0, sizeof(inet->cork.fl));
}
int ip6_push_pending_frames(struct sock *sk)
{
struct sk_buff *skb, *tmp_skb;
struct sk_buff **tail_skb;
struct in6_addr final_dst_buf, *final_dst = &final_dst_buf;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
struct ipv6hdr *hdr;
struct ipv6_txoptions *opt = np->cork.opt;
struct rt6_info *rt = (struct rt6_info *)inet->cork.base.dst;
struct flowi6 *fl6 = &inet->cork.fl.u.ip6;
unsigned char proto = fl6->flowi6_proto;
int err = 0;
if ((skb = __skb_dequeue(&sk->sk_write_queue)) == NULL)
goto out;
tail_skb = &(skb_shinfo(skb)->frag_list);
/* move skb->data to ip header from ext header */
if (skb->data < skb_network_header(skb))
__skb_pull(skb, skb_network_offset(skb));
while ((tmp_skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) {
__skb_pull(tmp_skb, skb_network_header_len(skb));
*tail_skb = tmp_skb;
tail_skb = &(tmp_skb->next);
skb->len += tmp_skb->len;
skb->data_len += tmp_skb->len;
skb->truesize += tmp_skb->truesize;
tmp_skb->destructor = NULL;
tmp_skb->sk = NULL;
}
/* Allow local fragmentation. */
if (np->pmtudisc < IPV6_PMTUDISC_DO)
skb->local_df = 1;
*final_dst = fl6->daddr;
__skb_pull(skb, skb_network_header_len(skb));
if (opt && opt->opt_flen)
ipv6_push_frag_opts(skb, opt, &proto);
if (opt && opt->opt_nflen)
ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst);
skb_push(skb, sizeof(struct ipv6hdr));
skb_reset_network_header(skb);
hdr = ipv6_hdr(skb);
ip6_flow_hdr(hdr, np->cork.tclass, fl6->flowlabel);
hdr->hop_limit = np->cork.hop_limit;
hdr->nexthdr = proto;
hdr->saddr = fl6->saddr;
hdr->daddr = *final_dst;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, dst_clone(&rt->dst));
IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len);
if (proto == IPPROTO_ICMPV6) {
struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb));
ICMP6MSGOUT_INC_STATS_BH(net, idev, icmp6_hdr(skb)->icmp6_type);
ICMP6_INC_STATS_BH(net, idev, ICMP6_MIB_OUTMSGS);
}
err = ip6_local_out(skb);
if (err) {
if (err > 0)
err = net_xmit_errno(err);
if (err)
goto error;
}
out:
ip6_cork_release(inet, np);
return err;
error:
IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
goto out;
}
EXPORT_SYMBOL_GPL(ip6_push_pending_frames);
void ip6_flush_pending_frames(struct sock *sk)
{
struct sk_buff *skb;
while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL) {
if (skb_dst(skb))
IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_OUTDISCARDS);
kfree_skb(skb);
}
ip6_cork_release(inet_sk(sk), inet6_sk(sk));
}
EXPORT_SYMBOL_GPL(ip6_flush_pending_frames);
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5660_0 |
crossvul-cpp_data_good_3012_1 | /*
* fs/f2fs/segment.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/fs.h>
#include <linux/f2fs_fs.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/prefetch.h>
#include <linux/kthread.h>
#include <linux/swap.h>
#include <linux/timer.h>
#include <linux/freezer.h>
#include <linux/sched/signal.h>
#include "f2fs.h"
#include "segment.h"
#include "node.h"
#include "gc.h"
#include "trace.h"
#include <trace/events/f2fs.h>
#define __reverse_ffz(x) __reverse_ffs(~(x))
static struct kmem_cache *discard_entry_slab;
static struct kmem_cache *discard_cmd_slab;
static struct kmem_cache *sit_entry_set_slab;
static struct kmem_cache *inmem_entry_slab;
static unsigned long __reverse_ulong(unsigned char *str)
{
unsigned long tmp = 0;
int shift = 24, idx = 0;
#if BITS_PER_LONG == 64
shift = 56;
#endif
while (shift >= 0) {
tmp |= (unsigned long)str[idx++] << shift;
shift -= BITS_PER_BYTE;
}
return tmp;
}
/*
* __reverse_ffs is copied from include/asm-generic/bitops/__ffs.h since
* MSB and LSB are reversed in a byte by f2fs_set_bit.
*/
static inline unsigned long __reverse_ffs(unsigned long word)
{
int num = 0;
#if BITS_PER_LONG == 64
if ((word & 0xffffffff00000000UL) == 0)
num += 32;
else
word >>= 32;
#endif
if ((word & 0xffff0000) == 0)
num += 16;
else
word >>= 16;
if ((word & 0xff00) == 0)
num += 8;
else
word >>= 8;
if ((word & 0xf0) == 0)
num += 4;
else
word >>= 4;
if ((word & 0xc) == 0)
num += 2;
else
word >>= 2;
if ((word & 0x2) == 0)
num += 1;
return num;
}
/*
* __find_rev_next(_zero)_bit is copied from lib/find_next_bit.c because
* f2fs_set_bit makes MSB and LSB reversed in a byte.
* @size must be integral times of unsigned long.
* Example:
* MSB <--> LSB
* f2fs_set_bit(0, bitmap) => 1000 0000
* f2fs_set_bit(7, bitmap) => 0000 0001
*/
static unsigned long __find_rev_next_bit(const unsigned long *addr,
unsigned long size, unsigned long offset)
{
const unsigned long *p = addr + BIT_WORD(offset);
unsigned long result = size;
unsigned long tmp;
if (offset >= size)
return size;
size -= (offset & ~(BITS_PER_LONG - 1));
offset %= BITS_PER_LONG;
while (1) {
if (*p == 0)
goto pass;
tmp = __reverse_ulong((unsigned char *)p);
tmp &= ~0UL >> offset;
if (size < BITS_PER_LONG)
tmp &= (~0UL << (BITS_PER_LONG - size));
if (tmp)
goto found;
pass:
if (size <= BITS_PER_LONG)
break;
size -= BITS_PER_LONG;
offset = 0;
p++;
}
return result;
found:
return result - size + __reverse_ffs(tmp);
}
static unsigned long __find_rev_next_zero_bit(const unsigned long *addr,
unsigned long size, unsigned long offset)
{
const unsigned long *p = addr + BIT_WORD(offset);
unsigned long result = size;
unsigned long tmp;
if (offset >= size)
return size;
size -= (offset & ~(BITS_PER_LONG - 1));
offset %= BITS_PER_LONG;
while (1) {
if (*p == ~0UL)
goto pass;
tmp = __reverse_ulong((unsigned char *)p);
if (offset)
tmp |= ~0UL << (BITS_PER_LONG - offset);
if (size < BITS_PER_LONG)
tmp |= ~0UL >> size;
if (tmp != ~0UL)
goto found;
pass:
if (size <= BITS_PER_LONG)
break;
size -= BITS_PER_LONG;
offset = 0;
p++;
}
return result;
found:
return result - size + __reverse_ffz(tmp);
}
bool need_SSR(struct f2fs_sb_info *sbi)
{
int node_secs = get_blocktype_secs(sbi, F2FS_DIRTY_NODES);
int dent_secs = get_blocktype_secs(sbi, F2FS_DIRTY_DENTS);
int imeta_secs = get_blocktype_secs(sbi, F2FS_DIRTY_IMETA);
if (test_opt(sbi, LFS))
return false;
if (sbi->gc_thread && sbi->gc_thread->gc_urgent)
return true;
return free_sections(sbi) <= (node_secs + 2 * dent_secs + imeta_secs +
2 * reserved_sections(sbi));
}
void register_inmem_page(struct inode *inode, struct page *page)
{
struct f2fs_inode_info *fi = F2FS_I(inode);
struct inmem_pages *new;
f2fs_trace_pid(page);
set_page_private(page, (unsigned long)ATOMIC_WRITTEN_PAGE);
SetPagePrivate(page);
new = f2fs_kmem_cache_alloc(inmem_entry_slab, GFP_NOFS);
/* add atomic page indices to the list */
new->page = page;
INIT_LIST_HEAD(&new->list);
/* increase reference count with clean state */
mutex_lock(&fi->inmem_lock);
get_page(page);
list_add_tail(&new->list, &fi->inmem_pages);
inc_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
mutex_unlock(&fi->inmem_lock);
trace_f2fs_register_inmem_page(page, INMEM);
}
static int __revoke_inmem_pages(struct inode *inode,
struct list_head *head, bool drop, bool recover)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct inmem_pages *cur, *tmp;
int err = 0;
list_for_each_entry_safe(cur, tmp, head, list) {
struct page *page = cur->page;
if (drop)
trace_f2fs_commit_inmem_page(page, INMEM_DROP);
lock_page(page);
if (recover) {
struct dnode_of_data dn;
struct node_info ni;
trace_f2fs_commit_inmem_page(page, INMEM_REVOKE);
retry:
set_new_dnode(&dn, inode, NULL, NULL, 0);
err = get_dnode_of_data(&dn, page->index, LOOKUP_NODE);
if (err) {
if (err == -ENOMEM) {
congestion_wait(BLK_RW_ASYNC, HZ/50);
cond_resched();
goto retry;
}
err = -EAGAIN;
goto next;
}
get_node_info(sbi, dn.nid, &ni);
f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
cur->old_addr, ni.version, true, true);
f2fs_put_dnode(&dn);
}
next:
/* we don't need to invalidate this in the sccessful status */
if (drop || recover)
ClearPageUptodate(page);
set_page_private(page, 0);
ClearPagePrivate(page);
f2fs_put_page(page, 1);
list_del(&cur->list);
kmem_cache_free(inmem_entry_slab, cur);
dec_page_count(F2FS_I_SB(inode), F2FS_INMEM_PAGES);
}
return err;
}
void drop_inmem_pages(struct inode *inode)
{
struct f2fs_inode_info *fi = F2FS_I(inode);
mutex_lock(&fi->inmem_lock);
__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
mutex_unlock(&fi->inmem_lock);
clear_inode_flag(inode, FI_ATOMIC_FILE);
clear_inode_flag(inode, FI_HOT_DATA);
stat_dec_atomic_write(inode);
}
void drop_inmem_page(struct inode *inode, struct page *page)
{
struct f2fs_inode_info *fi = F2FS_I(inode);
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct list_head *head = &fi->inmem_pages;
struct inmem_pages *cur = NULL;
f2fs_bug_on(sbi, !IS_ATOMIC_WRITTEN_PAGE(page));
mutex_lock(&fi->inmem_lock);
list_for_each_entry(cur, head, list) {
if (cur->page == page)
break;
}
f2fs_bug_on(sbi, !cur || cur->page != page);
list_del(&cur->list);
mutex_unlock(&fi->inmem_lock);
dec_page_count(sbi, F2FS_INMEM_PAGES);
kmem_cache_free(inmem_entry_slab, cur);
ClearPageUptodate(page);
set_page_private(page, 0);
ClearPagePrivate(page);
f2fs_put_page(page, 0);
trace_f2fs_commit_inmem_page(page, INMEM_INVALIDATE);
}
static int __commit_inmem_pages(struct inode *inode,
struct list_head *revoke_list)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct f2fs_inode_info *fi = F2FS_I(inode);
struct inmem_pages *cur, *tmp;
struct f2fs_io_info fio = {
.sbi = sbi,
.type = DATA,
.op = REQ_OP_WRITE,
.op_flags = REQ_SYNC | REQ_PRIO,
.io_type = FS_DATA_IO,
};
pgoff_t last_idx = ULONG_MAX;
int err = 0;
list_for_each_entry_safe(cur, tmp, &fi->inmem_pages, list) {
struct page *page = cur->page;
lock_page(page);
if (page->mapping == inode->i_mapping) {
trace_f2fs_commit_inmem_page(page, INMEM);
set_page_dirty(page);
f2fs_wait_on_page_writeback(page, DATA, true);
if (clear_page_dirty_for_io(page)) {
inode_dec_dirty_pages(inode);
remove_dirty_inode(inode);
}
retry:
fio.page = page;
fio.old_blkaddr = NULL_ADDR;
fio.encrypted_page = NULL;
fio.need_lock = LOCK_DONE;
err = do_write_data_page(&fio);
if (err) {
if (err == -ENOMEM) {
congestion_wait(BLK_RW_ASYNC, HZ/50);
cond_resched();
goto retry;
}
unlock_page(page);
break;
}
/* record old blkaddr for revoking */
cur->old_addr = fio.old_blkaddr;
last_idx = page->index;
}
unlock_page(page);
list_move_tail(&cur->list, revoke_list);
}
if (last_idx != ULONG_MAX)
f2fs_submit_merged_write_cond(sbi, inode, 0, last_idx, DATA);
if (!err)
__revoke_inmem_pages(inode, revoke_list, false, false);
return err;
}
int commit_inmem_pages(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
struct f2fs_inode_info *fi = F2FS_I(inode);
struct list_head revoke_list;
int err;
INIT_LIST_HEAD(&revoke_list);
f2fs_balance_fs(sbi, true);
f2fs_lock_op(sbi);
set_inode_flag(inode, FI_ATOMIC_COMMIT);
mutex_lock(&fi->inmem_lock);
err = __commit_inmem_pages(inode, &revoke_list);
if (err) {
int ret;
/*
* try to revoke all committed pages, but still we could fail
* due to no memory or other reason, if that happened, EAGAIN
* will be returned, which means in such case, transaction is
* already not integrity, caller should use journal to do the
* recovery or rewrite & commit last transaction. For other
* error number, revoking was done by filesystem itself.
*/
ret = __revoke_inmem_pages(inode, &revoke_list, false, true);
if (ret)
err = ret;
/* drop all uncommitted pages */
__revoke_inmem_pages(inode, &fi->inmem_pages, true, false);
}
mutex_unlock(&fi->inmem_lock);
clear_inode_flag(inode, FI_ATOMIC_COMMIT);
f2fs_unlock_op(sbi);
return err;
}
/*
* This function balances dirty node and dentry pages.
* In addition, it controls garbage collection.
*/
void f2fs_balance_fs(struct f2fs_sb_info *sbi, bool need)
{
#ifdef CONFIG_F2FS_FAULT_INJECTION
if (time_to_inject(sbi, FAULT_CHECKPOINT)) {
f2fs_show_injection_info(FAULT_CHECKPOINT);
f2fs_stop_checkpoint(sbi, false);
}
#endif
/* balance_fs_bg is able to be pending */
if (need && excess_cached_nats(sbi))
f2fs_balance_fs_bg(sbi);
/*
* We should do GC or end up with checkpoint, if there are so many dirty
* dir/node pages without enough free segments.
*/
if (has_not_enough_free_secs(sbi, 0, 0)) {
mutex_lock(&sbi->gc_mutex);
f2fs_gc(sbi, false, false, NULL_SEGNO);
}
}
void f2fs_balance_fs_bg(struct f2fs_sb_info *sbi)
{
/* try to shrink extent cache when there is no enough memory */
if (!available_free_memory(sbi, EXTENT_CACHE))
f2fs_shrink_extent_tree(sbi, EXTENT_CACHE_SHRINK_NUMBER);
/* check the # of cached NAT entries */
if (!available_free_memory(sbi, NAT_ENTRIES))
try_to_free_nats(sbi, NAT_ENTRY_PER_BLOCK);
if (!available_free_memory(sbi, FREE_NIDS))
try_to_free_nids(sbi, MAX_FREE_NIDS);
else
build_free_nids(sbi, false, false);
if (!is_idle(sbi) && !excess_dirty_nats(sbi))
return;
/* checkpoint is the only way to shrink partial cached entries */
if (!available_free_memory(sbi, NAT_ENTRIES) ||
!available_free_memory(sbi, INO_ENTRIES) ||
excess_prefree_segs(sbi) ||
excess_dirty_nats(sbi) ||
f2fs_time_over(sbi, CP_TIME)) {
if (test_opt(sbi, DATA_FLUSH)) {
struct blk_plug plug;
blk_start_plug(&plug);
sync_dirty_inodes(sbi, FILE_INODE);
blk_finish_plug(&plug);
}
f2fs_sync_fs(sbi->sb, true);
stat_inc_bg_cp_count(sbi->stat_info);
}
}
static int __submit_flush_wait(struct f2fs_sb_info *sbi,
struct block_device *bdev)
{
struct bio *bio = f2fs_bio_alloc(0);
int ret;
bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
bio_set_dev(bio, bdev);
ret = submit_bio_wait(bio);
bio_put(bio);
trace_f2fs_issue_flush(bdev, test_opt(sbi, NOBARRIER),
test_opt(sbi, FLUSH_MERGE), ret);
return ret;
}
static int submit_flush_wait(struct f2fs_sb_info *sbi)
{
int ret = __submit_flush_wait(sbi, sbi->sb->s_bdev);
int i;
if (!sbi->s_ndevs || ret)
return ret;
for (i = 1; i < sbi->s_ndevs; i++) {
ret = __submit_flush_wait(sbi, FDEV(i).bdev);
if (ret)
break;
}
return ret;
}
static int issue_flush_thread(void *data)
{
struct f2fs_sb_info *sbi = data;
struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
wait_queue_head_t *q = &fcc->flush_wait_queue;
repeat:
if (kthread_should_stop())
return 0;
sb_start_intwrite(sbi->sb);
if (!llist_empty(&fcc->issue_list)) {
struct flush_cmd *cmd, *next;
int ret;
fcc->dispatch_list = llist_del_all(&fcc->issue_list);
fcc->dispatch_list = llist_reverse_order(fcc->dispatch_list);
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush);
llist_for_each_entry_safe(cmd, next,
fcc->dispatch_list, llnode) {
cmd->ret = ret;
complete(&cmd->wait);
}
fcc->dispatch_list = NULL;
}
sb_end_intwrite(sbi->sb);
wait_event_interruptible(*q,
kthread_should_stop() || !llist_empty(&fcc->issue_list));
goto repeat;
}
int f2fs_issue_flush(struct f2fs_sb_info *sbi)
{
struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
struct flush_cmd cmd;
int ret;
if (test_opt(sbi, NOBARRIER))
return 0;
if (!test_opt(sbi, FLUSH_MERGE)) {
ret = submit_flush_wait(sbi);
atomic_inc(&fcc->issued_flush);
return ret;
}
if (atomic_inc_return(&fcc->issing_flush) == 1) {
ret = submit_flush_wait(sbi);
atomic_dec(&fcc->issing_flush);
atomic_inc(&fcc->issued_flush);
return ret;
}
init_completion(&cmd.wait);
llist_add(&cmd.llnode, &fcc->issue_list);
/* update issue_list before we wake up issue_flush thread */
smp_mb();
if (waitqueue_active(&fcc->flush_wait_queue))
wake_up(&fcc->flush_wait_queue);
if (fcc->f2fs_issue_flush) {
wait_for_completion(&cmd.wait);
atomic_dec(&fcc->issing_flush);
} else {
struct llist_node *list;
list = llist_del_all(&fcc->issue_list);
if (!list) {
wait_for_completion(&cmd.wait);
atomic_dec(&fcc->issing_flush);
} else {
struct flush_cmd *tmp, *next;
ret = submit_flush_wait(sbi);
llist_for_each_entry_safe(tmp, next, list, llnode) {
if (tmp == &cmd) {
cmd.ret = ret;
atomic_dec(&fcc->issing_flush);
continue;
}
tmp->ret = ret;
complete(&tmp->wait);
}
}
}
return cmd.ret;
}
int create_flush_cmd_control(struct f2fs_sb_info *sbi)
{
dev_t dev = sbi->sb->s_bdev->bd_dev;
struct flush_cmd_control *fcc;
int err = 0;
if (SM_I(sbi)->fcc_info) {
fcc = SM_I(sbi)->fcc_info;
if (fcc->f2fs_issue_flush)
return err;
goto init_thread;
}
fcc = kzalloc(sizeof(struct flush_cmd_control), GFP_KERNEL);
if (!fcc)
return -ENOMEM;
atomic_set(&fcc->issued_flush, 0);
atomic_set(&fcc->issing_flush, 0);
init_waitqueue_head(&fcc->flush_wait_queue);
init_llist_head(&fcc->issue_list);
SM_I(sbi)->fcc_info = fcc;
if (!test_opt(sbi, FLUSH_MERGE))
return err;
init_thread:
fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi,
"f2fs_flush-%u:%u", MAJOR(dev), MINOR(dev));
if (IS_ERR(fcc->f2fs_issue_flush)) {
err = PTR_ERR(fcc->f2fs_issue_flush);
kfree(fcc);
SM_I(sbi)->fcc_info = NULL;
return err;
}
return err;
}
void destroy_flush_cmd_control(struct f2fs_sb_info *sbi, bool free)
{
struct flush_cmd_control *fcc = SM_I(sbi)->fcc_info;
if (fcc && fcc->f2fs_issue_flush) {
struct task_struct *flush_thread = fcc->f2fs_issue_flush;
fcc->f2fs_issue_flush = NULL;
kthread_stop(flush_thread);
}
if (free) {
kfree(fcc);
SM_I(sbi)->fcc_info = NULL;
}
}
static void __locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
enum dirty_type dirty_type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
/* need not be added */
if (IS_CURSEG(sbi, segno))
return;
if (!test_and_set_bit(segno, dirty_i->dirty_segmap[dirty_type]))
dirty_i->nr_dirty[dirty_type]++;
if (dirty_type == DIRTY) {
struct seg_entry *sentry = get_seg_entry(sbi, segno);
enum dirty_type t = sentry->type;
if (unlikely(t >= DIRTY)) {
f2fs_bug_on(sbi, 1);
return;
}
if (!test_and_set_bit(segno, dirty_i->dirty_segmap[t]))
dirty_i->nr_dirty[t]++;
}
}
static void __remove_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno,
enum dirty_type dirty_type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
if (test_and_clear_bit(segno, dirty_i->dirty_segmap[dirty_type]))
dirty_i->nr_dirty[dirty_type]--;
if (dirty_type == DIRTY) {
struct seg_entry *sentry = get_seg_entry(sbi, segno);
enum dirty_type t = sentry->type;
if (test_and_clear_bit(segno, dirty_i->dirty_segmap[t]))
dirty_i->nr_dirty[t]--;
if (get_valid_blocks(sbi, segno, true) == 0)
clear_bit(GET_SEC_FROM_SEG(sbi, segno),
dirty_i->victim_secmap);
}
}
/*
* Should not occur error such as -ENOMEM.
* Adding dirty entry into seglist is not critical operation.
* If a given segment is one of current working segments, it won't be added.
*/
static void locate_dirty_segment(struct f2fs_sb_info *sbi, unsigned int segno)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned short valid_blocks;
if (segno == NULL_SEGNO || IS_CURSEG(sbi, segno))
return;
mutex_lock(&dirty_i->seglist_lock);
valid_blocks = get_valid_blocks(sbi, segno, false);
if (valid_blocks == 0) {
__locate_dirty_segment(sbi, segno, PRE);
__remove_dirty_segment(sbi, segno, DIRTY);
} else if (valid_blocks < sbi->blocks_per_seg) {
__locate_dirty_segment(sbi, segno, DIRTY);
} else {
/* Recovery routine with SSR needs this */
__remove_dirty_segment(sbi, segno, DIRTY);
}
mutex_unlock(&dirty_i->seglist_lock);
}
static struct discard_cmd *__create_discard_cmd(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *pend_list;
struct discard_cmd *dc;
f2fs_bug_on(sbi, !len);
pend_list = &dcc->pend_list[plist_idx(len)];
dc = f2fs_kmem_cache_alloc(discard_cmd_slab, GFP_NOFS);
INIT_LIST_HEAD(&dc->list);
dc->bdev = bdev;
dc->lstart = lstart;
dc->start = start;
dc->len = len;
dc->ref = 0;
dc->state = D_PREP;
dc->error = 0;
init_completion(&dc->wait);
list_add_tail(&dc->list, pend_list);
atomic_inc(&dcc->discard_cmd_cnt);
dcc->undiscard_blks += len;
return dc;
}
static struct discard_cmd *__attach_discard_cmd(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len,
struct rb_node *parent, struct rb_node **p)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_cmd *dc;
dc = __create_discard_cmd(sbi, bdev, lstart, start, len);
rb_link_node(&dc->rb_node, parent, p);
rb_insert_color(&dc->rb_node, &dcc->root);
return dc;
}
static void __detach_discard_cmd(struct discard_cmd_control *dcc,
struct discard_cmd *dc)
{
if (dc->state == D_DONE)
atomic_dec(&dcc->issing_discard);
list_del(&dc->list);
rb_erase(&dc->rb_node, &dcc->root);
dcc->undiscard_blks -= dc->len;
kmem_cache_free(discard_cmd_slab, dc);
atomic_dec(&dcc->discard_cmd_cnt);
}
static void __remove_discard_cmd(struct f2fs_sb_info *sbi,
struct discard_cmd *dc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
f2fs_bug_on(sbi, dc->ref);
if (dc->error == -EOPNOTSUPP)
dc->error = 0;
if (dc->error)
f2fs_msg(sbi->sb, KERN_INFO,
"Issue discard(%u, %u, %u) failed, ret: %d",
dc->lstart, dc->start, dc->len, dc->error);
__detach_discard_cmd(dcc, dc);
}
static void f2fs_submit_discard_endio(struct bio *bio)
{
struct discard_cmd *dc = (struct discard_cmd *)bio->bi_private;
dc->error = blk_status_to_errno(bio->bi_status);
dc->state = D_DONE;
complete_all(&dc->wait);
bio_put(bio);
}
void __check_sit_bitmap(struct f2fs_sb_info *sbi,
block_t start, block_t end)
{
#ifdef CONFIG_F2FS_CHECK_FS
struct seg_entry *sentry;
unsigned int segno;
block_t blk = start;
unsigned long offset, size, max_blocks = sbi->blocks_per_seg;
unsigned long *map;
while (blk < end) {
segno = GET_SEGNO(sbi, blk);
sentry = get_seg_entry(sbi, segno);
offset = GET_BLKOFF_FROM_SEG0(sbi, blk);
if (end < START_BLOCK(sbi, segno + 1))
size = GET_BLKOFF_FROM_SEG0(sbi, end);
else
size = max_blocks;
map = (unsigned long *)(sentry->cur_valid_map);
offset = __find_rev_next_bit(map, size, offset);
f2fs_bug_on(sbi, offset != size);
blk = START_BLOCK(sbi, segno + 1);
}
#endif
}
/* this function is copied from blkdev_issue_discard from block/blk-lib.c */
static void __submit_discard_cmd(struct f2fs_sb_info *sbi,
struct discard_cmd *dc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct bio *bio = NULL;
if (dc->state != D_PREP)
return;
trace_f2fs_issue_discard(dc->bdev, dc->start, dc->len);
dc->error = __blkdev_issue_discard(dc->bdev,
SECTOR_FROM_BLOCK(dc->start),
SECTOR_FROM_BLOCK(dc->len),
GFP_NOFS, 0, &bio);
if (!dc->error) {
/* should keep before submission to avoid D_DONE right away */
dc->state = D_SUBMIT;
atomic_inc(&dcc->issued_discard);
atomic_inc(&dcc->issing_discard);
if (bio) {
bio->bi_private = dc;
bio->bi_end_io = f2fs_submit_discard_endio;
bio->bi_opf |= REQ_SYNC;
submit_bio(bio);
list_move_tail(&dc->list, &dcc->wait_list);
__check_sit_bitmap(sbi, dc->start, dc->start + dc->len);
f2fs_update_iostat(sbi, FS_DISCARD, 1);
}
} else {
__remove_discard_cmd(sbi, dc);
}
}
static struct discard_cmd *__insert_discard_tree(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len,
struct rb_node **insert_p,
struct rb_node *insert_parent)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct rb_node **p = &dcc->root.rb_node;
struct rb_node *parent = NULL;
struct discard_cmd *dc = NULL;
if (insert_p && insert_parent) {
parent = insert_parent;
p = insert_p;
goto do_insert;
}
p = __lookup_rb_tree_for_insert(sbi, &dcc->root, &parent, lstart);
do_insert:
dc = __attach_discard_cmd(sbi, bdev, lstart, start, len, parent, p);
if (!dc)
return NULL;
return dc;
}
static void __relocate_discard_cmd(struct discard_cmd_control *dcc,
struct discard_cmd *dc)
{
list_move_tail(&dc->list, &dcc->pend_list[plist_idx(dc->len)]);
}
static void __punch_discard_cmd(struct f2fs_sb_info *sbi,
struct discard_cmd *dc, block_t blkaddr)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_info di = dc->di;
bool modified = false;
if (dc->state == D_DONE || dc->len == 1) {
__remove_discard_cmd(sbi, dc);
return;
}
dcc->undiscard_blks -= di.len;
if (blkaddr > di.lstart) {
dc->len = blkaddr - dc->lstart;
dcc->undiscard_blks += dc->len;
__relocate_discard_cmd(dcc, dc);
modified = true;
}
if (blkaddr < di.lstart + di.len - 1) {
if (modified) {
__insert_discard_tree(sbi, dc->bdev, blkaddr + 1,
di.start + blkaddr + 1 - di.lstart,
di.lstart + di.len - 1 - blkaddr,
NULL, NULL);
} else {
dc->lstart++;
dc->len--;
dc->start++;
dcc->undiscard_blks += dc->len;
__relocate_discard_cmd(dcc, dc);
}
}
}
static void __update_discard_tree_range(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t lstart,
block_t start, block_t len)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_cmd *prev_dc = NULL, *next_dc = NULL;
struct discard_cmd *dc;
struct discard_info di = {0};
struct rb_node **insert_p = NULL, *insert_parent = NULL;
block_t end = lstart + len;
mutex_lock(&dcc->cmd_lock);
dc = (struct discard_cmd *)__lookup_rb_tree_ret(&dcc->root,
NULL, lstart,
(struct rb_entry **)&prev_dc,
(struct rb_entry **)&next_dc,
&insert_p, &insert_parent, true);
if (dc)
prev_dc = dc;
if (!prev_dc) {
di.lstart = lstart;
di.len = next_dc ? next_dc->lstart - lstart : len;
di.len = min(di.len, len);
di.start = start;
}
while (1) {
struct rb_node *node;
bool merged = false;
struct discard_cmd *tdc = NULL;
if (prev_dc) {
di.lstart = prev_dc->lstart + prev_dc->len;
if (di.lstart < lstart)
di.lstart = lstart;
if (di.lstart >= end)
break;
if (!next_dc || next_dc->lstart > end)
di.len = end - di.lstart;
else
di.len = next_dc->lstart - di.lstart;
di.start = start + di.lstart - lstart;
}
if (!di.len)
goto next;
if (prev_dc && prev_dc->state == D_PREP &&
prev_dc->bdev == bdev &&
__is_discard_back_mergeable(&di, &prev_dc->di)) {
prev_dc->di.len += di.len;
dcc->undiscard_blks += di.len;
__relocate_discard_cmd(dcc, prev_dc);
di = prev_dc->di;
tdc = prev_dc;
merged = true;
}
if (next_dc && next_dc->state == D_PREP &&
next_dc->bdev == bdev &&
__is_discard_front_mergeable(&di, &next_dc->di)) {
next_dc->di.lstart = di.lstart;
next_dc->di.len += di.len;
next_dc->di.start = di.start;
dcc->undiscard_blks += di.len;
__relocate_discard_cmd(dcc, next_dc);
if (tdc)
__remove_discard_cmd(sbi, tdc);
merged = true;
}
if (!merged) {
__insert_discard_tree(sbi, bdev, di.lstart, di.start,
di.len, NULL, NULL);
}
next:
prev_dc = next_dc;
if (!prev_dc)
break;
node = rb_next(&prev_dc->rb_node);
next_dc = rb_entry_safe(node, struct discard_cmd, rb_node);
}
mutex_unlock(&dcc->cmd_lock);
}
static int __queue_discard_cmd(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t blkstart, block_t blklen)
{
block_t lblkstart = blkstart;
trace_f2fs_queue_discard(bdev, blkstart, blklen);
if (sbi->s_ndevs) {
int devi = f2fs_target_device_index(sbi, blkstart);
blkstart -= FDEV(devi).start_blk;
}
__update_discard_tree_range(sbi, bdev, lblkstart, blkstart, blklen);
return 0;
}
static int __issue_discard_cmd(struct f2fs_sb_info *sbi, bool issue_cond)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *pend_list;
struct discard_cmd *dc, *tmp;
struct blk_plug plug;
int iter = 0, issued = 0;
int i;
bool io_interrupted = false;
mutex_lock(&dcc->cmd_lock);
f2fs_bug_on(sbi,
!__check_rb_tree_consistence(sbi, &dcc->root));
blk_start_plug(&plug);
for (i = MAX_PLIST_NUM - 1;
i >= 0 && plist_issue(dcc->pend_list_tag[i]); i--) {
pend_list = &dcc->pend_list[i];
list_for_each_entry_safe(dc, tmp, pend_list, list) {
f2fs_bug_on(sbi, dc->state != D_PREP);
/* Hurry up to finish fstrim */
if (dcc->pend_list_tag[i] & P_TRIM) {
__submit_discard_cmd(sbi, dc);
issued++;
if (fatal_signal_pending(current))
break;
continue;
}
if (!issue_cond) {
__submit_discard_cmd(sbi, dc);
issued++;
continue;
}
if (is_idle(sbi)) {
__submit_discard_cmd(sbi, dc);
issued++;
} else {
io_interrupted = true;
}
if (++iter >= DISCARD_ISSUE_RATE)
goto out;
}
if (list_empty(pend_list) && dcc->pend_list_tag[i] & P_TRIM)
dcc->pend_list_tag[i] &= (~P_TRIM);
}
out:
blk_finish_plug(&plug);
mutex_unlock(&dcc->cmd_lock);
if (!issued && io_interrupted)
issued = -1;
return issued;
}
static void __drop_discard_cmd(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *pend_list;
struct discard_cmd *dc, *tmp;
int i;
mutex_lock(&dcc->cmd_lock);
for (i = MAX_PLIST_NUM - 1; i >= 0; i--) {
pend_list = &dcc->pend_list[i];
list_for_each_entry_safe(dc, tmp, pend_list, list) {
f2fs_bug_on(sbi, dc->state != D_PREP);
__remove_discard_cmd(sbi, dc);
}
}
mutex_unlock(&dcc->cmd_lock);
}
static void __wait_one_discard_bio(struct f2fs_sb_info *sbi,
struct discard_cmd *dc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
wait_for_completion_io(&dc->wait);
mutex_lock(&dcc->cmd_lock);
f2fs_bug_on(sbi, dc->state != D_DONE);
dc->ref--;
if (!dc->ref)
__remove_discard_cmd(sbi, dc);
mutex_unlock(&dcc->cmd_lock);
}
static void __wait_discard_cmd(struct f2fs_sb_info *sbi, bool wait_cond)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *wait_list = &(dcc->wait_list);
struct discard_cmd *dc, *tmp;
bool need_wait;
next:
need_wait = false;
mutex_lock(&dcc->cmd_lock);
list_for_each_entry_safe(dc, tmp, wait_list, list) {
if (!wait_cond || (dc->state == D_DONE && !dc->ref)) {
wait_for_completion_io(&dc->wait);
__remove_discard_cmd(sbi, dc);
} else {
dc->ref++;
need_wait = true;
break;
}
}
mutex_unlock(&dcc->cmd_lock);
if (need_wait) {
__wait_one_discard_bio(sbi, dc);
goto next;
}
}
/* This should be covered by global mutex, &sit_i->sentry_lock */
void f2fs_wait_discard_bio(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct discard_cmd *dc;
bool need_wait = false;
mutex_lock(&dcc->cmd_lock);
dc = (struct discard_cmd *)__lookup_rb_tree(&dcc->root, NULL, blkaddr);
if (dc) {
if (dc->state == D_PREP) {
__punch_discard_cmd(sbi, dc, blkaddr);
} else {
dc->ref++;
need_wait = true;
}
}
mutex_unlock(&dcc->cmd_lock);
if (need_wait)
__wait_one_discard_bio(sbi, dc);
}
void stop_discard_thread(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
if (dcc && dcc->f2fs_issue_discard) {
struct task_struct *discard_thread = dcc->f2fs_issue_discard;
dcc->f2fs_issue_discard = NULL;
kthread_stop(discard_thread);
}
}
/* This comes from f2fs_put_super and f2fs_trim_fs */
void f2fs_wait_discard_bios(struct f2fs_sb_info *sbi, bool umount)
{
__issue_discard_cmd(sbi, false);
__drop_discard_cmd(sbi);
__wait_discard_cmd(sbi, !umount);
}
static void mark_discard_range_all(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
int i;
mutex_lock(&dcc->cmd_lock);
for (i = 0; i < MAX_PLIST_NUM; i++)
dcc->pend_list_tag[i] |= P_TRIM;
mutex_unlock(&dcc->cmd_lock);
}
static int issue_discard_thread(void *data)
{
struct f2fs_sb_info *sbi = data;
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
wait_queue_head_t *q = &dcc->discard_wait_queue;
unsigned int wait_ms = DEF_MIN_DISCARD_ISSUE_TIME;
int issued;
set_freezable();
do {
wait_event_interruptible_timeout(*q,
kthread_should_stop() || freezing(current) ||
dcc->discard_wake,
msecs_to_jiffies(wait_ms));
if (try_to_freeze())
continue;
if (kthread_should_stop())
return 0;
if (dcc->discard_wake) {
dcc->discard_wake = 0;
if (sbi->gc_thread && sbi->gc_thread->gc_urgent)
mark_discard_range_all(sbi);
}
sb_start_intwrite(sbi->sb);
issued = __issue_discard_cmd(sbi, true);
if (issued) {
__wait_discard_cmd(sbi, true);
wait_ms = DEF_MIN_DISCARD_ISSUE_TIME;
} else {
wait_ms = DEF_MAX_DISCARD_ISSUE_TIME;
}
sb_end_intwrite(sbi->sb);
} while (!kthread_should_stop());
return 0;
}
#ifdef CONFIG_BLK_DEV_ZONED
static int __f2fs_issue_discard_zone(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t blkstart, block_t blklen)
{
sector_t sector, nr_sects;
block_t lblkstart = blkstart;
int devi = 0;
if (sbi->s_ndevs) {
devi = f2fs_target_device_index(sbi, blkstart);
blkstart -= FDEV(devi).start_blk;
}
/*
* We need to know the type of the zone: for conventional zones,
* use regular discard if the drive supports it. For sequential
* zones, reset the zone write pointer.
*/
switch (get_blkz_type(sbi, bdev, blkstart)) {
case BLK_ZONE_TYPE_CONVENTIONAL:
if (!blk_queue_discard(bdev_get_queue(bdev)))
return 0;
return __queue_discard_cmd(sbi, bdev, lblkstart, blklen);
case BLK_ZONE_TYPE_SEQWRITE_REQ:
case BLK_ZONE_TYPE_SEQWRITE_PREF:
sector = SECTOR_FROM_BLOCK(blkstart);
nr_sects = SECTOR_FROM_BLOCK(blklen);
if (sector & (bdev_zone_sectors(bdev) - 1) ||
nr_sects != bdev_zone_sectors(bdev)) {
f2fs_msg(sbi->sb, KERN_INFO,
"(%d) %s: Unaligned discard attempted (block %x + %x)",
devi, sbi->s_ndevs ? FDEV(devi).path: "",
blkstart, blklen);
return -EIO;
}
trace_f2fs_issue_reset_zone(bdev, blkstart);
return blkdev_reset_zones(bdev, sector,
nr_sects, GFP_NOFS);
default:
/* Unknown zone type: broken device ? */
return -EIO;
}
}
#endif
static int __issue_discard_async(struct f2fs_sb_info *sbi,
struct block_device *bdev, block_t blkstart, block_t blklen)
{
#ifdef CONFIG_BLK_DEV_ZONED
if (f2fs_sb_mounted_blkzoned(sbi->sb) &&
bdev_zoned_model(bdev) != BLK_ZONED_NONE)
return __f2fs_issue_discard_zone(sbi, bdev, blkstart, blklen);
#endif
return __queue_discard_cmd(sbi, bdev, blkstart, blklen);
}
static int f2fs_issue_discard(struct f2fs_sb_info *sbi,
block_t blkstart, block_t blklen)
{
sector_t start = blkstart, len = 0;
struct block_device *bdev;
struct seg_entry *se;
unsigned int offset;
block_t i;
int err = 0;
bdev = f2fs_target_device(sbi, blkstart, NULL);
for (i = blkstart; i < blkstart + blklen; i++, len++) {
if (i != start) {
struct block_device *bdev2 =
f2fs_target_device(sbi, i, NULL);
if (bdev2 != bdev) {
err = __issue_discard_async(sbi, bdev,
start, len);
if (err)
return err;
bdev = bdev2;
start = i;
len = 0;
}
}
se = get_seg_entry(sbi, GET_SEGNO(sbi, i));
offset = GET_BLKOFF_FROM_SEG0(sbi, i);
if (!f2fs_test_and_set_bit(offset, se->discard_map))
sbi->discard_blks--;
}
if (len)
err = __issue_discard_async(sbi, bdev, start, len);
return err;
}
static bool add_discard_addrs(struct f2fs_sb_info *sbi, struct cp_control *cpc,
bool check_only)
{
int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
int max_blocks = sbi->blocks_per_seg;
struct seg_entry *se = get_seg_entry(sbi, cpc->trim_start);
unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
unsigned long *discard_map = (unsigned long *)se->discard_map;
unsigned long *dmap = SIT_I(sbi)->tmp_map;
unsigned int start = 0, end = -1;
bool force = (cpc->reason & CP_DISCARD);
struct discard_entry *de = NULL;
struct list_head *head = &SM_I(sbi)->dcc_info->entry_list;
int i;
if (se->valid_blocks == max_blocks || !f2fs_discard_en(sbi))
return false;
if (!force) {
if (!test_opt(sbi, DISCARD) || !se->valid_blocks ||
SM_I(sbi)->dcc_info->nr_discards >=
SM_I(sbi)->dcc_info->max_discards)
return false;
}
/* SIT_VBLOCK_MAP_SIZE should be multiple of sizeof(unsigned long) */
for (i = 0; i < entries; i++)
dmap[i] = force ? ~ckpt_map[i] & ~discard_map[i] :
(cur_map[i] ^ ckpt_map[i]) & ckpt_map[i];
while (force || SM_I(sbi)->dcc_info->nr_discards <=
SM_I(sbi)->dcc_info->max_discards) {
start = __find_rev_next_bit(dmap, max_blocks, end + 1);
if (start >= max_blocks)
break;
end = __find_rev_next_zero_bit(dmap, max_blocks, start + 1);
if (force && start && end != max_blocks
&& (end - start) < cpc->trim_minlen)
continue;
if (check_only)
return true;
if (!de) {
de = f2fs_kmem_cache_alloc(discard_entry_slab,
GFP_F2FS_ZERO);
de->start_blkaddr = START_BLOCK(sbi, cpc->trim_start);
list_add_tail(&de->list, head);
}
for (i = start; i < end; i++)
__set_bit_le(i, (void *)de->discard_map);
SM_I(sbi)->dcc_info->nr_discards += end - start;
}
return false;
}
void release_discard_addrs(struct f2fs_sb_info *sbi)
{
struct list_head *head = &(SM_I(sbi)->dcc_info->entry_list);
struct discard_entry *entry, *this;
/* drop caches */
list_for_each_entry_safe(entry, this, head, list) {
list_del(&entry->list);
kmem_cache_free(discard_entry_slab, entry);
}
}
/*
* Should call clear_prefree_segments after checkpoint is done.
*/
static void set_prefree_as_free_segments(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned int segno;
mutex_lock(&dirty_i->seglist_lock);
for_each_set_bit(segno, dirty_i->dirty_segmap[PRE], MAIN_SEGS(sbi))
__set_test_and_free(sbi, segno);
mutex_unlock(&dirty_i->seglist_lock);
}
void clear_prefree_segments(struct f2fs_sb_info *sbi, struct cp_control *cpc)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
struct list_head *head = &dcc->entry_list;
struct discard_entry *entry, *this;
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned long *prefree_map = dirty_i->dirty_segmap[PRE];
unsigned int start = 0, end = -1;
unsigned int secno, start_segno;
bool force = (cpc->reason & CP_DISCARD);
mutex_lock(&dirty_i->seglist_lock);
while (1) {
int i;
start = find_next_bit(prefree_map, MAIN_SEGS(sbi), end + 1);
if (start >= MAIN_SEGS(sbi))
break;
end = find_next_zero_bit(prefree_map, MAIN_SEGS(sbi),
start + 1);
for (i = start; i < end; i++)
clear_bit(i, prefree_map);
dirty_i->nr_dirty[PRE] -= end - start;
if (!test_opt(sbi, DISCARD))
continue;
if (force && start >= cpc->trim_start &&
(end - 1) <= cpc->trim_end)
continue;
if (!test_opt(sbi, LFS) || sbi->segs_per_sec == 1) {
f2fs_issue_discard(sbi, START_BLOCK(sbi, start),
(end - start) << sbi->log_blocks_per_seg);
continue;
}
next:
secno = GET_SEC_FROM_SEG(sbi, start);
start_segno = GET_SEG_FROM_SEC(sbi, secno);
if (!IS_CURSEC(sbi, secno) &&
!get_valid_blocks(sbi, start, true))
f2fs_issue_discard(sbi, START_BLOCK(sbi, start_segno),
sbi->segs_per_sec << sbi->log_blocks_per_seg);
start = start_segno + sbi->segs_per_sec;
if (start < end)
goto next;
else
end = start - 1;
}
mutex_unlock(&dirty_i->seglist_lock);
/* send small discards */
list_for_each_entry_safe(entry, this, head, list) {
unsigned int cur_pos = 0, next_pos, len, total_len = 0;
bool is_valid = test_bit_le(0, entry->discard_map);
find_next:
if (is_valid) {
next_pos = find_next_zero_bit_le(entry->discard_map,
sbi->blocks_per_seg, cur_pos);
len = next_pos - cur_pos;
if (f2fs_sb_mounted_blkzoned(sbi->sb) ||
(force && len < cpc->trim_minlen))
goto skip;
f2fs_issue_discard(sbi, entry->start_blkaddr + cur_pos,
len);
cpc->trimmed += len;
total_len += len;
} else {
next_pos = find_next_bit_le(entry->discard_map,
sbi->blocks_per_seg, cur_pos);
}
skip:
cur_pos = next_pos;
is_valid = !is_valid;
if (cur_pos < sbi->blocks_per_seg)
goto find_next;
list_del(&entry->list);
dcc->nr_discards -= total_len;
kmem_cache_free(discard_entry_slab, entry);
}
wake_up_discard_thread(sbi, false);
}
static int create_discard_cmd_control(struct f2fs_sb_info *sbi)
{
dev_t dev = sbi->sb->s_bdev->bd_dev;
struct discard_cmd_control *dcc;
int err = 0, i;
if (SM_I(sbi)->dcc_info) {
dcc = SM_I(sbi)->dcc_info;
goto init_thread;
}
dcc = kzalloc(sizeof(struct discard_cmd_control), GFP_KERNEL);
if (!dcc)
return -ENOMEM;
dcc->discard_granularity = DEFAULT_DISCARD_GRANULARITY;
INIT_LIST_HEAD(&dcc->entry_list);
for (i = 0; i < MAX_PLIST_NUM; i++) {
INIT_LIST_HEAD(&dcc->pend_list[i]);
if (i >= dcc->discard_granularity - 1)
dcc->pend_list_tag[i] |= P_ACTIVE;
}
INIT_LIST_HEAD(&dcc->wait_list);
mutex_init(&dcc->cmd_lock);
atomic_set(&dcc->issued_discard, 0);
atomic_set(&dcc->issing_discard, 0);
atomic_set(&dcc->discard_cmd_cnt, 0);
dcc->nr_discards = 0;
dcc->max_discards = MAIN_SEGS(sbi) << sbi->log_blocks_per_seg;
dcc->undiscard_blks = 0;
dcc->root = RB_ROOT;
init_waitqueue_head(&dcc->discard_wait_queue);
SM_I(sbi)->dcc_info = dcc;
init_thread:
dcc->f2fs_issue_discard = kthread_run(issue_discard_thread, sbi,
"f2fs_discard-%u:%u", MAJOR(dev), MINOR(dev));
if (IS_ERR(dcc->f2fs_issue_discard)) {
err = PTR_ERR(dcc->f2fs_issue_discard);
kfree(dcc);
SM_I(sbi)->dcc_info = NULL;
return err;
}
return err;
}
static void destroy_discard_cmd_control(struct f2fs_sb_info *sbi)
{
struct discard_cmd_control *dcc = SM_I(sbi)->dcc_info;
if (!dcc)
return;
stop_discard_thread(sbi);
kfree(dcc);
SM_I(sbi)->dcc_info = NULL;
}
static bool __mark_sit_entry_dirty(struct f2fs_sb_info *sbi, unsigned int segno)
{
struct sit_info *sit_i = SIT_I(sbi);
if (!__test_and_set_bit(segno, sit_i->dirty_sentries_bitmap)) {
sit_i->dirty_sentries++;
return false;
}
return true;
}
static void __set_sit_entry_type(struct f2fs_sb_info *sbi, int type,
unsigned int segno, int modified)
{
struct seg_entry *se = get_seg_entry(sbi, segno);
se->type = type;
if (modified)
__mark_sit_entry_dirty(sbi, segno);
}
static void update_sit_entry(struct f2fs_sb_info *sbi, block_t blkaddr, int del)
{
struct seg_entry *se;
unsigned int segno, offset;
long int new_vblocks;
bool exist;
#ifdef CONFIG_F2FS_CHECK_FS
bool mir_exist;
#endif
segno = GET_SEGNO(sbi, blkaddr);
se = get_seg_entry(sbi, segno);
new_vblocks = se->valid_blocks + del;
offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
f2fs_bug_on(sbi, (new_vblocks >> (sizeof(unsigned short) << 3) ||
(new_vblocks > sbi->blocks_per_seg)));
se->valid_blocks = new_vblocks;
se->mtime = get_mtime(sbi);
SIT_I(sbi)->max_mtime = se->mtime;
/* Update valid block bitmap */
if (del > 0) {
exist = f2fs_test_and_set_bit(offset, se->cur_valid_map);
#ifdef CONFIG_F2FS_CHECK_FS
mir_exist = f2fs_test_and_set_bit(offset,
se->cur_valid_map_mir);
if (unlikely(exist != mir_exist)) {
f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
"when setting bitmap, blk:%u, old bit:%d",
blkaddr, exist);
f2fs_bug_on(sbi, 1);
}
#endif
if (unlikely(exist)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Bitmap was wrongly set, blk:%u", blkaddr);
f2fs_bug_on(sbi, 1);
se->valid_blocks--;
del = 0;
}
if (f2fs_discard_en(sbi) &&
!f2fs_test_and_set_bit(offset, se->discard_map))
sbi->discard_blks--;
/* don't overwrite by SSR to keep node chain */
if (se->type == CURSEG_WARM_NODE) {
if (!f2fs_test_and_set_bit(offset, se->ckpt_valid_map))
se->ckpt_valid_blocks++;
}
} else {
exist = f2fs_test_and_clear_bit(offset, se->cur_valid_map);
#ifdef CONFIG_F2FS_CHECK_FS
mir_exist = f2fs_test_and_clear_bit(offset,
se->cur_valid_map_mir);
if (unlikely(exist != mir_exist)) {
f2fs_msg(sbi->sb, KERN_ERR, "Inconsistent error "
"when clearing bitmap, blk:%u, old bit:%d",
blkaddr, exist);
f2fs_bug_on(sbi, 1);
}
#endif
if (unlikely(!exist)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Bitmap was wrongly cleared, blk:%u", blkaddr);
f2fs_bug_on(sbi, 1);
se->valid_blocks++;
del = 0;
}
if (f2fs_discard_en(sbi) &&
f2fs_test_and_clear_bit(offset, se->discard_map))
sbi->discard_blks++;
}
if (!f2fs_test_bit(offset, se->ckpt_valid_map))
se->ckpt_valid_blocks += del;
__mark_sit_entry_dirty(sbi, segno);
/* update total number of valid blocks to be written in ckpt area */
SIT_I(sbi)->written_valid_blocks += del;
if (sbi->segs_per_sec > 1)
get_sec_entry(sbi, segno)->valid_blocks += del;
}
void refresh_sit_entry(struct f2fs_sb_info *sbi, block_t old, block_t new)
{
update_sit_entry(sbi, new, 1);
if (GET_SEGNO(sbi, old) != NULL_SEGNO)
update_sit_entry(sbi, old, -1);
locate_dirty_segment(sbi, GET_SEGNO(sbi, old));
locate_dirty_segment(sbi, GET_SEGNO(sbi, new));
}
void invalidate_blocks(struct f2fs_sb_info *sbi, block_t addr)
{
unsigned int segno = GET_SEGNO(sbi, addr);
struct sit_info *sit_i = SIT_I(sbi);
f2fs_bug_on(sbi, addr == NULL_ADDR);
if (addr == NEW_ADDR)
return;
/* add it into sit main buffer */
mutex_lock(&sit_i->sentry_lock);
update_sit_entry(sbi, addr, -1);
/* add it into dirty seglist */
locate_dirty_segment(sbi, segno);
mutex_unlock(&sit_i->sentry_lock);
}
bool is_checkpointed_data(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned int segno, offset;
struct seg_entry *se;
bool is_cp = false;
if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
return true;
mutex_lock(&sit_i->sentry_lock);
segno = GET_SEGNO(sbi, blkaddr);
se = get_seg_entry(sbi, segno);
offset = GET_BLKOFF_FROM_SEG0(sbi, blkaddr);
if (f2fs_test_bit(offset, se->ckpt_valid_map))
is_cp = true;
mutex_unlock(&sit_i->sentry_lock);
return is_cp;
}
/*
* This function should be resided under the curseg_mutex lock
*/
static void __add_sum_entry(struct f2fs_sb_info *sbi, int type,
struct f2fs_summary *sum)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
void *addr = curseg->sum_blk;
addr += curseg->next_blkoff * sizeof(struct f2fs_summary);
memcpy(addr, sum, sizeof(struct f2fs_summary));
}
/*
* Calculate the number of current summary pages for writing
*/
int npages_for_summary_flush(struct f2fs_sb_info *sbi, bool for_ra)
{
int valid_sum_count = 0;
int i, sum_in_page;
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
if (sbi->ckpt->alloc_type[i] == SSR)
valid_sum_count += sbi->blocks_per_seg;
else {
if (for_ra)
valid_sum_count += le16_to_cpu(
F2FS_CKPT(sbi)->cur_data_blkoff[i]);
else
valid_sum_count += curseg_blkoff(sbi, i);
}
}
sum_in_page = (PAGE_SIZE - 2 * SUM_JOURNAL_SIZE -
SUM_FOOTER_SIZE) / SUMMARY_SIZE;
if (valid_sum_count <= sum_in_page)
return 1;
else if ((valid_sum_count - sum_in_page) <=
(PAGE_SIZE - SUM_FOOTER_SIZE) / SUMMARY_SIZE)
return 2;
return 3;
}
/*
* Caller should put this summary page
*/
struct page *get_sum_page(struct f2fs_sb_info *sbi, unsigned int segno)
{
return get_meta_page(sbi, GET_SUM_BLOCK(sbi, segno));
}
void update_meta_page(struct f2fs_sb_info *sbi, void *src, block_t blk_addr)
{
struct page *page = grab_meta_page(sbi, blk_addr);
void *dst = page_address(page);
if (src)
memcpy(dst, src, PAGE_SIZE);
else
memset(dst, 0, PAGE_SIZE);
set_page_dirty(page);
f2fs_put_page(page, 1);
}
static void write_sum_page(struct f2fs_sb_info *sbi,
struct f2fs_summary_block *sum_blk, block_t blk_addr)
{
update_meta_page(sbi, (void *)sum_blk, blk_addr);
}
static void write_current_sum_page(struct f2fs_sb_info *sbi,
int type, block_t blk_addr)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
struct page *page = grab_meta_page(sbi, blk_addr);
struct f2fs_summary_block *src = curseg->sum_blk;
struct f2fs_summary_block *dst;
dst = (struct f2fs_summary_block *)page_address(page);
mutex_lock(&curseg->curseg_mutex);
down_read(&curseg->journal_rwsem);
memcpy(&dst->journal, curseg->journal, SUM_JOURNAL_SIZE);
up_read(&curseg->journal_rwsem);
memcpy(dst->entries, src->entries, SUM_ENTRY_SIZE);
memcpy(&dst->footer, &src->footer, SUM_FOOTER_SIZE);
mutex_unlock(&curseg->curseg_mutex);
set_page_dirty(page);
f2fs_put_page(page, 1);
}
static int is_next_segment_free(struct f2fs_sb_info *sbi, int type)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int segno = curseg->segno + 1;
struct free_segmap_info *free_i = FREE_I(sbi);
if (segno < MAIN_SEGS(sbi) && segno % sbi->segs_per_sec)
return !test_bit(segno, free_i->free_segmap);
return 0;
}
/*
* Find a new segment from the free segments bitmap to right order
* This function should be returned with success, otherwise BUG
*/
static void get_new_segment(struct f2fs_sb_info *sbi,
unsigned int *newseg, bool new_sec, int dir)
{
struct free_segmap_info *free_i = FREE_I(sbi);
unsigned int segno, secno, zoneno;
unsigned int total_zones = MAIN_SECS(sbi) / sbi->secs_per_zone;
unsigned int hint = GET_SEC_FROM_SEG(sbi, *newseg);
unsigned int old_zoneno = GET_ZONE_FROM_SEG(sbi, *newseg);
unsigned int left_start = hint;
bool init = true;
int go_left = 0;
int i;
spin_lock(&free_i->segmap_lock);
if (!new_sec && ((*newseg + 1) % sbi->segs_per_sec)) {
segno = find_next_zero_bit(free_i->free_segmap,
GET_SEG_FROM_SEC(sbi, hint + 1), *newseg + 1);
if (segno < GET_SEG_FROM_SEC(sbi, hint + 1))
goto got_it;
}
find_other_zone:
secno = find_next_zero_bit(free_i->free_secmap, MAIN_SECS(sbi), hint);
if (secno >= MAIN_SECS(sbi)) {
if (dir == ALLOC_RIGHT) {
secno = find_next_zero_bit(free_i->free_secmap,
MAIN_SECS(sbi), 0);
f2fs_bug_on(sbi, secno >= MAIN_SECS(sbi));
} else {
go_left = 1;
left_start = hint - 1;
}
}
if (go_left == 0)
goto skip_left;
while (test_bit(left_start, free_i->free_secmap)) {
if (left_start > 0) {
left_start--;
continue;
}
left_start = find_next_zero_bit(free_i->free_secmap,
MAIN_SECS(sbi), 0);
f2fs_bug_on(sbi, left_start >= MAIN_SECS(sbi));
break;
}
secno = left_start;
skip_left:
hint = secno;
segno = GET_SEG_FROM_SEC(sbi, secno);
zoneno = GET_ZONE_FROM_SEC(sbi, secno);
/* give up on finding another zone */
if (!init)
goto got_it;
if (sbi->secs_per_zone == 1)
goto got_it;
if (zoneno == old_zoneno)
goto got_it;
if (dir == ALLOC_LEFT) {
if (!go_left && zoneno + 1 >= total_zones)
goto got_it;
if (go_left && zoneno == 0)
goto got_it;
}
for (i = 0; i < NR_CURSEG_TYPE; i++)
if (CURSEG_I(sbi, i)->zone == zoneno)
break;
if (i < NR_CURSEG_TYPE) {
/* zone is in user, try another */
if (go_left)
hint = zoneno * sbi->secs_per_zone - 1;
else if (zoneno + 1 >= total_zones)
hint = 0;
else
hint = (zoneno + 1) * sbi->secs_per_zone;
init = false;
goto find_other_zone;
}
got_it:
/* set it as dirty segment in free segmap */
f2fs_bug_on(sbi, test_bit(segno, free_i->free_segmap));
__set_inuse(sbi, segno);
*newseg = segno;
spin_unlock(&free_i->segmap_lock);
}
static void reset_curseg(struct f2fs_sb_info *sbi, int type, int modified)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
struct summary_footer *sum_footer;
curseg->segno = curseg->next_segno;
curseg->zone = GET_ZONE_FROM_SEG(sbi, curseg->segno);
curseg->next_blkoff = 0;
curseg->next_segno = NULL_SEGNO;
sum_footer = &(curseg->sum_blk->footer);
memset(sum_footer, 0, sizeof(struct summary_footer));
if (IS_DATASEG(type))
SET_SUM_TYPE(sum_footer, SUM_TYPE_DATA);
if (IS_NODESEG(type))
SET_SUM_TYPE(sum_footer, SUM_TYPE_NODE);
__set_sit_entry_type(sbi, type, curseg->segno, modified);
}
static unsigned int __get_next_segno(struct f2fs_sb_info *sbi, int type)
{
/* if segs_per_sec is large than 1, we need to keep original policy. */
if (sbi->segs_per_sec != 1)
return CURSEG_I(sbi, type)->segno;
if (type == CURSEG_HOT_DATA || IS_NODESEG(type))
return 0;
if (SIT_I(sbi)->last_victim[ALLOC_NEXT])
return SIT_I(sbi)->last_victim[ALLOC_NEXT];
return CURSEG_I(sbi, type)->segno;
}
/*
* Allocate a current working segment.
* This function always allocates a free segment in LFS manner.
*/
static void new_curseg(struct f2fs_sb_info *sbi, int type, bool new_sec)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int segno = curseg->segno;
int dir = ALLOC_LEFT;
write_sum_page(sbi, curseg->sum_blk,
GET_SUM_BLOCK(sbi, segno));
if (type == CURSEG_WARM_DATA || type == CURSEG_COLD_DATA)
dir = ALLOC_RIGHT;
if (test_opt(sbi, NOHEAP))
dir = ALLOC_RIGHT;
segno = __get_next_segno(sbi, type);
get_new_segment(sbi, &segno, new_sec, dir);
curseg->next_segno = segno;
reset_curseg(sbi, type, 1);
curseg->alloc_type = LFS;
}
static void __next_free_blkoff(struct f2fs_sb_info *sbi,
struct curseg_info *seg, block_t start)
{
struct seg_entry *se = get_seg_entry(sbi, seg->segno);
int entries = SIT_VBLOCK_MAP_SIZE / sizeof(unsigned long);
unsigned long *target_map = SIT_I(sbi)->tmp_map;
unsigned long *ckpt_map = (unsigned long *)se->ckpt_valid_map;
unsigned long *cur_map = (unsigned long *)se->cur_valid_map;
int i, pos;
for (i = 0; i < entries; i++)
target_map[i] = ckpt_map[i] | cur_map[i];
pos = __find_rev_next_zero_bit(target_map, sbi->blocks_per_seg, start);
seg->next_blkoff = pos;
}
/*
* If a segment is written by LFS manner, next block offset is just obtained
* by increasing the current block offset. However, if a segment is written by
* SSR manner, next block offset obtained by calling __next_free_blkoff
*/
static void __refresh_next_blkoff(struct f2fs_sb_info *sbi,
struct curseg_info *seg)
{
if (seg->alloc_type == SSR)
__next_free_blkoff(sbi, seg, seg->next_blkoff + 1);
else
seg->next_blkoff++;
}
/*
* This function always allocates a used segment(from dirty seglist) by SSR
* manner, so it should recover the existing segment information of valid blocks
*/
static void change_curseg(struct f2fs_sb_info *sbi, int type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
struct curseg_info *curseg = CURSEG_I(sbi, type);
unsigned int new_segno = curseg->next_segno;
struct f2fs_summary_block *sum_node;
struct page *sum_page;
write_sum_page(sbi, curseg->sum_blk,
GET_SUM_BLOCK(sbi, curseg->segno));
__set_test_and_inuse(sbi, new_segno);
mutex_lock(&dirty_i->seglist_lock);
__remove_dirty_segment(sbi, new_segno, PRE);
__remove_dirty_segment(sbi, new_segno, DIRTY);
mutex_unlock(&dirty_i->seglist_lock);
reset_curseg(sbi, type, 1);
curseg->alloc_type = SSR;
__next_free_blkoff(sbi, curseg, 0);
sum_page = get_sum_page(sbi, new_segno);
sum_node = (struct f2fs_summary_block *)page_address(sum_page);
memcpy(curseg->sum_blk, sum_node, SUM_ENTRY_SIZE);
f2fs_put_page(sum_page, 1);
}
static int get_ssr_segment(struct f2fs_sb_info *sbi, int type)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
const struct victim_selection *v_ops = DIRTY_I(sbi)->v_ops;
unsigned segno = NULL_SEGNO;
int i, cnt;
bool reversed = false;
/* need_SSR() already forces to do this */
if (v_ops->get_victim(sbi, &segno, BG_GC, type, SSR)) {
curseg->next_segno = segno;
return 1;
}
/* For node segments, let's do SSR more intensively */
if (IS_NODESEG(type)) {
if (type >= CURSEG_WARM_NODE) {
reversed = true;
i = CURSEG_COLD_NODE;
} else {
i = CURSEG_HOT_NODE;
}
cnt = NR_CURSEG_NODE_TYPE;
} else {
if (type >= CURSEG_WARM_DATA) {
reversed = true;
i = CURSEG_COLD_DATA;
} else {
i = CURSEG_HOT_DATA;
}
cnt = NR_CURSEG_DATA_TYPE;
}
for (; cnt-- > 0; reversed ? i-- : i++) {
if (i == type)
continue;
if (v_ops->get_victim(sbi, &segno, BG_GC, i, SSR)) {
curseg->next_segno = segno;
return 1;
}
}
return 0;
}
/*
* flush out current segment and replace it with new segment
* This function should be returned with success, otherwise BUG
*/
static void allocate_segment_by_default(struct f2fs_sb_info *sbi,
int type, bool force)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
if (force)
new_curseg(sbi, type, true);
else if (!is_set_ckpt_flags(sbi, CP_CRC_RECOVERY_FLAG) &&
type == CURSEG_WARM_NODE)
new_curseg(sbi, type, false);
else if (curseg->alloc_type == LFS && is_next_segment_free(sbi, type))
new_curseg(sbi, type, false);
else if (need_SSR(sbi) && get_ssr_segment(sbi, type))
change_curseg(sbi, type);
else
new_curseg(sbi, type, false);
stat_inc_seg_type(sbi, curseg);
}
void allocate_new_segments(struct f2fs_sb_info *sbi)
{
struct curseg_info *curseg;
unsigned int old_segno;
int i;
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
curseg = CURSEG_I(sbi, i);
old_segno = curseg->segno;
SIT_I(sbi)->s_ops->allocate_segment(sbi, i, true);
locate_dirty_segment(sbi, old_segno);
}
}
static const struct segment_allocation default_salloc_ops = {
.allocate_segment = allocate_segment_by_default,
};
bool exist_trim_candidates(struct f2fs_sb_info *sbi, struct cp_control *cpc)
{
__u64 trim_start = cpc->trim_start;
bool has_candidate = false;
mutex_lock(&SIT_I(sbi)->sentry_lock);
for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++) {
if (add_discard_addrs(sbi, cpc, true)) {
has_candidate = true;
break;
}
}
mutex_unlock(&SIT_I(sbi)->sentry_lock);
cpc->trim_start = trim_start;
return has_candidate;
}
int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range)
{
__u64 start = F2FS_BYTES_TO_BLK(range->start);
__u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1;
unsigned int start_segno, end_segno;
struct cp_control cpc;
int err = 0;
if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize)
return -EINVAL;
cpc.trimmed = 0;
if (end <= MAIN_BLKADDR(sbi))
goto out;
if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) {
f2fs_msg(sbi->sb, KERN_WARNING,
"Found FS corruption, run fsck to fix.");
goto out;
}
/* start/end segment number in main_area */
start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start);
end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 :
GET_SEGNO(sbi, end);
cpc.reason = CP_DISCARD;
cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen));
/* do checkpoint to issue discard commands safely */
for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) {
cpc.trim_start = start_segno;
if (sbi->discard_blks == 0)
break;
else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi))
cpc.trim_end = end_segno;
else
cpc.trim_end = min_t(unsigned int,
rounddown(start_segno +
BATCHED_TRIM_SEGMENTS(sbi),
sbi->segs_per_sec) - 1, end_segno);
mutex_lock(&sbi->gc_mutex);
err = write_checkpoint(sbi, &cpc);
mutex_unlock(&sbi->gc_mutex);
if (err)
break;
schedule();
}
/* It's time to issue all the filed discards */
mark_discard_range_all(sbi);
f2fs_wait_discard_bios(sbi, false);
out:
range->len = F2FS_BLK_TO_BYTES(cpc.trimmed);
return err;
}
static bool __has_curseg_space(struct f2fs_sb_info *sbi, int type)
{
struct curseg_info *curseg = CURSEG_I(sbi, type);
if (curseg->next_blkoff < sbi->blocks_per_seg)
return true;
return false;
}
static int __get_segment_type_2(struct f2fs_io_info *fio)
{
if (fio->type == DATA)
return CURSEG_HOT_DATA;
else
return CURSEG_HOT_NODE;
}
static int __get_segment_type_4(struct f2fs_io_info *fio)
{
if (fio->type == DATA) {
struct inode *inode = fio->page->mapping->host;
if (S_ISDIR(inode->i_mode))
return CURSEG_HOT_DATA;
else
return CURSEG_COLD_DATA;
} else {
if (IS_DNODE(fio->page) && is_cold_node(fio->page))
return CURSEG_WARM_NODE;
else
return CURSEG_COLD_NODE;
}
}
static int __get_segment_type_6(struct f2fs_io_info *fio)
{
if (fio->type == DATA) {
struct inode *inode = fio->page->mapping->host;
if (is_cold_data(fio->page) || file_is_cold(inode))
return CURSEG_COLD_DATA;
if (is_inode_flag_set(inode, FI_HOT_DATA))
return CURSEG_HOT_DATA;
return CURSEG_WARM_DATA;
} else {
if (IS_DNODE(fio->page))
return is_cold_node(fio->page) ? CURSEG_WARM_NODE :
CURSEG_HOT_NODE;
return CURSEG_COLD_NODE;
}
}
static int __get_segment_type(struct f2fs_io_info *fio)
{
int type = 0;
switch (fio->sbi->active_logs) {
case 2:
type = __get_segment_type_2(fio);
break;
case 4:
type = __get_segment_type_4(fio);
break;
case 6:
type = __get_segment_type_6(fio);
break;
default:
f2fs_bug_on(fio->sbi, true);
}
if (IS_HOT(type))
fio->temp = HOT;
else if (IS_WARM(type))
fio->temp = WARM;
else
fio->temp = COLD;
return type;
}
void allocate_data_block(struct f2fs_sb_info *sbi, struct page *page,
block_t old_blkaddr, block_t *new_blkaddr,
struct f2fs_summary *sum, int type,
struct f2fs_io_info *fio, bool add_list)
{
struct sit_info *sit_i = SIT_I(sbi);
struct curseg_info *curseg = CURSEG_I(sbi, type);
mutex_lock(&curseg->curseg_mutex);
mutex_lock(&sit_i->sentry_lock);
*new_blkaddr = NEXT_FREE_BLKADDR(sbi, curseg);
f2fs_wait_discard_bio(sbi, *new_blkaddr);
/*
* __add_sum_entry should be resided under the curseg_mutex
* because, this function updates a summary entry in the
* current summary block.
*/
__add_sum_entry(sbi, type, sum);
__refresh_next_blkoff(sbi, curseg);
stat_inc_block_count(sbi, curseg);
if (!__has_curseg_space(sbi, type))
sit_i->s_ops->allocate_segment(sbi, type, false);
/*
* SIT information should be updated after segment allocation,
* since we need to keep dirty segments precisely under SSR.
*/
refresh_sit_entry(sbi, old_blkaddr, *new_blkaddr);
mutex_unlock(&sit_i->sentry_lock);
if (page && IS_NODESEG(type)) {
fill_node_footer_blkaddr(page, NEXT_FREE_BLKADDR(sbi, curseg));
f2fs_inode_chksum_set(sbi, page);
}
if (add_list) {
struct f2fs_bio_info *io;
INIT_LIST_HEAD(&fio->list);
fio->in_list = true;
io = sbi->write_io[fio->type] + fio->temp;
spin_lock(&io->io_lock);
list_add_tail(&fio->list, &io->io_list);
spin_unlock(&io->io_lock);
}
mutex_unlock(&curseg->curseg_mutex);
}
static void do_write_page(struct f2fs_summary *sum, struct f2fs_io_info *fio)
{
int type = __get_segment_type(fio);
int err;
reallocate:
allocate_data_block(fio->sbi, fio->page, fio->old_blkaddr,
&fio->new_blkaddr, sum, type, fio, true);
/* writeout dirty page into bdev */
err = f2fs_submit_page_write(fio);
if (err == -EAGAIN) {
fio->old_blkaddr = fio->new_blkaddr;
goto reallocate;
}
}
void write_meta_page(struct f2fs_sb_info *sbi, struct page *page,
enum iostat_type io_type)
{
struct f2fs_io_info fio = {
.sbi = sbi,
.type = META,
.op = REQ_OP_WRITE,
.op_flags = REQ_SYNC | REQ_META | REQ_PRIO,
.old_blkaddr = page->index,
.new_blkaddr = page->index,
.page = page,
.encrypted_page = NULL,
.in_list = false,
};
if (unlikely(page->index >= MAIN_BLKADDR(sbi)))
fio.op_flags &= ~REQ_META;
set_page_writeback(page);
f2fs_submit_page_write(&fio);
f2fs_update_iostat(sbi, io_type, F2FS_BLKSIZE);
}
void write_node_page(unsigned int nid, struct f2fs_io_info *fio)
{
struct f2fs_summary sum;
set_summary(&sum, nid, 0, 0);
do_write_page(&sum, fio);
f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
}
void write_data_page(struct dnode_of_data *dn, struct f2fs_io_info *fio)
{
struct f2fs_sb_info *sbi = fio->sbi;
struct f2fs_summary sum;
struct node_info ni;
f2fs_bug_on(sbi, dn->data_blkaddr == NULL_ADDR);
get_node_info(sbi, dn->nid, &ni);
set_summary(&sum, dn->nid, dn->ofs_in_node, ni.version);
do_write_page(&sum, fio);
f2fs_update_data_blkaddr(dn, fio->new_blkaddr);
f2fs_update_iostat(sbi, fio->io_type, F2FS_BLKSIZE);
}
int rewrite_data_page(struct f2fs_io_info *fio)
{
int err;
fio->new_blkaddr = fio->old_blkaddr;
stat_inc_inplace_blocks(fio->sbi);
err = f2fs_submit_page_bio(fio);
f2fs_update_iostat(fio->sbi, fio->io_type, F2FS_BLKSIZE);
return err;
}
void __f2fs_replace_block(struct f2fs_sb_info *sbi, struct f2fs_summary *sum,
block_t old_blkaddr, block_t new_blkaddr,
bool recover_curseg, bool recover_newaddr)
{
struct sit_info *sit_i = SIT_I(sbi);
struct curseg_info *curseg;
unsigned int segno, old_cursegno;
struct seg_entry *se;
int type;
unsigned short old_blkoff;
segno = GET_SEGNO(sbi, new_blkaddr);
se = get_seg_entry(sbi, segno);
type = se->type;
if (!recover_curseg) {
/* for recovery flow */
if (se->valid_blocks == 0 && !IS_CURSEG(sbi, segno)) {
if (old_blkaddr == NULL_ADDR)
type = CURSEG_COLD_DATA;
else
type = CURSEG_WARM_DATA;
}
} else {
if (!IS_CURSEG(sbi, segno))
type = CURSEG_WARM_DATA;
}
curseg = CURSEG_I(sbi, type);
mutex_lock(&curseg->curseg_mutex);
mutex_lock(&sit_i->sentry_lock);
old_cursegno = curseg->segno;
old_blkoff = curseg->next_blkoff;
/* change the current segment */
if (segno != curseg->segno) {
curseg->next_segno = segno;
change_curseg(sbi, type);
}
curseg->next_blkoff = GET_BLKOFF_FROM_SEG0(sbi, new_blkaddr);
__add_sum_entry(sbi, type, sum);
if (!recover_curseg || recover_newaddr)
update_sit_entry(sbi, new_blkaddr, 1);
if (GET_SEGNO(sbi, old_blkaddr) != NULL_SEGNO)
update_sit_entry(sbi, old_blkaddr, -1);
locate_dirty_segment(sbi, GET_SEGNO(sbi, old_blkaddr));
locate_dirty_segment(sbi, GET_SEGNO(sbi, new_blkaddr));
locate_dirty_segment(sbi, old_cursegno);
if (recover_curseg) {
if (old_cursegno != curseg->segno) {
curseg->next_segno = old_cursegno;
change_curseg(sbi, type);
}
curseg->next_blkoff = old_blkoff;
}
mutex_unlock(&sit_i->sentry_lock);
mutex_unlock(&curseg->curseg_mutex);
}
void f2fs_replace_block(struct f2fs_sb_info *sbi, struct dnode_of_data *dn,
block_t old_addr, block_t new_addr,
unsigned char version, bool recover_curseg,
bool recover_newaddr)
{
struct f2fs_summary sum;
set_summary(&sum, dn->nid, dn->ofs_in_node, version);
__f2fs_replace_block(sbi, &sum, old_addr, new_addr,
recover_curseg, recover_newaddr);
f2fs_update_data_blkaddr(dn, new_addr);
}
void f2fs_wait_on_page_writeback(struct page *page,
enum page_type type, bool ordered)
{
if (PageWriteback(page)) {
struct f2fs_sb_info *sbi = F2FS_P_SB(page);
f2fs_submit_merged_write_cond(sbi, page->mapping->host,
0, page->index, type);
if (ordered)
wait_on_page_writeback(page);
else
wait_for_stable_page(page);
}
}
void f2fs_wait_on_block_writeback(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct page *cpage;
if (blkaddr == NEW_ADDR || blkaddr == NULL_ADDR)
return;
cpage = find_lock_page(META_MAPPING(sbi), blkaddr);
if (cpage) {
f2fs_wait_on_page_writeback(cpage, DATA, true);
f2fs_put_page(cpage, 1);
}
}
static int read_compacted_summaries(struct f2fs_sb_info *sbi)
{
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct curseg_info *seg_i;
unsigned char *kaddr;
struct page *page;
block_t start;
int i, j, offset;
start = start_sum_block(sbi);
page = get_meta_page(sbi, start++);
kaddr = (unsigned char *)page_address(page);
/* Step 1: restore nat cache */
seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
memcpy(seg_i->journal, kaddr, SUM_JOURNAL_SIZE);
/* Step 2: restore sit cache */
seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
memcpy(seg_i->journal, kaddr + SUM_JOURNAL_SIZE, SUM_JOURNAL_SIZE);
offset = 2 * SUM_JOURNAL_SIZE;
/* Step 3: restore summary entries */
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
unsigned short blk_off;
unsigned int segno;
seg_i = CURSEG_I(sbi, i);
segno = le32_to_cpu(ckpt->cur_data_segno[i]);
blk_off = le16_to_cpu(ckpt->cur_data_blkoff[i]);
seg_i->next_segno = segno;
reset_curseg(sbi, i, 0);
seg_i->alloc_type = ckpt->alloc_type[i];
seg_i->next_blkoff = blk_off;
if (seg_i->alloc_type == SSR)
blk_off = sbi->blocks_per_seg;
for (j = 0; j < blk_off; j++) {
struct f2fs_summary *s;
s = (struct f2fs_summary *)(kaddr + offset);
seg_i->sum_blk->entries[j] = *s;
offset += SUMMARY_SIZE;
if (offset + SUMMARY_SIZE <= PAGE_SIZE -
SUM_FOOTER_SIZE)
continue;
f2fs_put_page(page, 1);
page = NULL;
page = get_meta_page(sbi, start++);
kaddr = (unsigned char *)page_address(page);
offset = 0;
}
}
f2fs_put_page(page, 1);
return 0;
}
static int read_normal_summaries(struct f2fs_sb_info *sbi, int type)
{
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_summary_block *sum;
struct curseg_info *curseg;
struct page *new;
unsigned short blk_off;
unsigned int segno = 0;
block_t blk_addr = 0;
/* get segment number and block addr */
if (IS_DATASEG(type)) {
segno = le32_to_cpu(ckpt->cur_data_segno[type]);
blk_off = le16_to_cpu(ckpt->cur_data_blkoff[type -
CURSEG_HOT_DATA]);
if (__exist_node_summaries(sbi))
blk_addr = sum_blk_addr(sbi, NR_CURSEG_TYPE, type);
else
blk_addr = sum_blk_addr(sbi, NR_CURSEG_DATA_TYPE, type);
} else {
segno = le32_to_cpu(ckpt->cur_node_segno[type -
CURSEG_HOT_NODE]);
blk_off = le16_to_cpu(ckpt->cur_node_blkoff[type -
CURSEG_HOT_NODE]);
if (__exist_node_summaries(sbi))
blk_addr = sum_blk_addr(sbi, NR_CURSEG_NODE_TYPE,
type - CURSEG_HOT_NODE);
else
blk_addr = GET_SUM_BLOCK(sbi, segno);
}
new = get_meta_page(sbi, blk_addr);
sum = (struct f2fs_summary_block *)page_address(new);
if (IS_NODESEG(type)) {
if (__exist_node_summaries(sbi)) {
struct f2fs_summary *ns = &sum->entries[0];
int i;
for (i = 0; i < sbi->blocks_per_seg; i++, ns++) {
ns->version = 0;
ns->ofs_in_node = 0;
}
} else {
int err;
err = restore_node_summary(sbi, segno, sum);
if (err) {
f2fs_put_page(new, 1);
return err;
}
}
}
/* set uncompleted segment to curseg */
curseg = CURSEG_I(sbi, type);
mutex_lock(&curseg->curseg_mutex);
/* update journal info */
down_write(&curseg->journal_rwsem);
memcpy(curseg->journal, &sum->journal, SUM_JOURNAL_SIZE);
up_write(&curseg->journal_rwsem);
memcpy(curseg->sum_blk->entries, sum->entries, SUM_ENTRY_SIZE);
memcpy(&curseg->sum_blk->footer, &sum->footer, SUM_FOOTER_SIZE);
curseg->next_segno = segno;
reset_curseg(sbi, type, 0);
curseg->alloc_type = ckpt->alloc_type[type];
curseg->next_blkoff = blk_off;
mutex_unlock(&curseg->curseg_mutex);
f2fs_put_page(new, 1);
return 0;
}
static int restore_curseg_summaries(struct f2fs_sb_info *sbi)
{
struct f2fs_journal *sit_j = CURSEG_I(sbi, CURSEG_COLD_DATA)->journal;
struct f2fs_journal *nat_j = CURSEG_I(sbi, CURSEG_HOT_DATA)->journal;
int type = CURSEG_HOT_DATA;
int err;
if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG)) {
int npages = npages_for_summary_flush(sbi, true);
if (npages >= 2)
ra_meta_pages(sbi, start_sum_block(sbi), npages,
META_CP, true);
/* restore for compacted data summary */
if (read_compacted_summaries(sbi))
return -EINVAL;
type = CURSEG_HOT_NODE;
}
if (__exist_node_summaries(sbi))
ra_meta_pages(sbi, sum_blk_addr(sbi, NR_CURSEG_TYPE, type),
NR_CURSEG_TYPE - type, META_CP, true);
for (; type <= CURSEG_COLD_NODE; type++) {
err = read_normal_summaries(sbi, type);
if (err)
return err;
}
/* sanity check for summary blocks */
if (nats_in_cursum(nat_j) > NAT_JOURNAL_ENTRIES ||
sits_in_cursum(sit_j) > SIT_JOURNAL_ENTRIES)
return -EINVAL;
return 0;
}
static void write_compacted_summaries(struct f2fs_sb_info *sbi, block_t blkaddr)
{
struct page *page;
unsigned char *kaddr;
struct f2fs_summary *summary;
struct curseg_info *seg_i;
int written_size = 0;
int i, j;
page = grab_meta_page(sbi, blkaddr++);
kaddr = (unsigned char *)page_address(page);
/* Step 1: write nat cache */
seg_i = CURSEG_I(sbi, CURSEG_HOT_DATA);
memcpy(kaddr, seg_i->journal, SUM_JOURNAL_SIZE);
written_size += SUM_JOURNAL_SIZE;
/* Step 2: write sit cache */
seg_i = CURSEG_I(sbi, CURSEG_COLD_DATA);
memcpy(kaddr + written_size, seg_i->journal, SUM_JOURNAL_SIZE);
written_size += SUM_JOURNAL_SIZE;
/* Step 3: write summary entries */
for (i = CURSEG_HOT_DATA; i <= CURSEG_COLD_DATA; i++) {
unsigned short blkoff;
seg_i = CURSEG_I(sbi, i);
if (sbi->ckpt->alloc_type[i] == SSR)
blkoff = sbi->blocks_per_seg;
else
blkoff = curseg_blkoff(sbi, i);
for (j = 0; j < blkoff; j++) {
if (!page) {
page = grab_meta_page(sbi, blkaddr++);
kaddr = (unsigned char *)page_address(page);
written_size = 0;
}
summary = (struct f2fs_summary *)(kaddr + written_size);
*summary = seg_i->sum_blk->entries[j];
written_size += SUMMARY_SIZE;
if (written_size + SUMMARY_SIZE <= PAGE_SIZE -
SUM_FOOTER_SIZE)
continue;
set_page_dirty(page);
f2fs_put_page(page, 1);
page = NULL;
}
}
if (page) {
set_page_dirty(page);
f2fs_put_page(page, 1);
}
}
static void write_normal_summaries(struct f2fs_sb_info *sbi,
block_t blkaddr, int type)
{
int i, end;
if (IS_DATASEG(type))
end = type + NR_CURSEG_DATA_TYPE;
else
end = type + NR_CURSEG_NODE_TYPE;
for (i = type; i < end; i++)
write_current_sum_page(sbi, i, blkaddr + (i - type));
}
void write_data_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
{
if (is_set_ckpt_flags(sbi, CP_COMPACT_SUM_FLAG))
write_compacted_summaries(sbi, start_blk);
else
write_normal_summaries(sbi, start_blk, CURSEG_HOT_DATA);
}
void write_node_summaries(struct f2fs_sb_info *sbi, block_t start_blk)
{
write_normal_summaries(sbi, start_blk, CURSEG_HOT_NODE);
}
int lookup_journal_in_cursum(struct f2fs_journal *journal, int type,
unsigned int val, int alloc)
{
int i;
if (type == NAT_JOURNAL) {
for (i = 0; i < nats_in_cursum(journal); i++) {
if (le32_to_cpu(nid_in_journal(journal, i)) == val)
return i;
}
if (alloc && __has_cursum_space(journal, 1, NAT_JOURNAL))
return update_nats_in_cursum(journal, 1);
} else if (type == SIT_JOURNAL) {
for (i = 0; i < sits_in_cursum(journal); i++)
if (le32_to_cpu(segno_in_journal(journal, i)) == val)
return i;
if (alloc && __has_cursum_space(journal, 1, SIT_JOURNAL))
return update_sits_in_cursum(journal, 1);
}
return -1;
}
static struct page *get_current_sit_page(struct f2fs_sb_info *sbi,
unsigned int segno)
{
return get_meta_page(sbi, current_sit_addr(sbi, segno));
}
static struct page *get_next_sit_page(struct f2fs_sb_info *sbi,
unsigned int start)
{
struct sit_info *sit_i = SIT_I(sbi);
struct page *src_page, *dst_page;
pgoff_t src_off, dst_off;
void *src_addr, *dst_addr;
src_off = current_sit_addr(sbi, start);
dst_off = next_sit_addr(sbi, src_off);
/* get current sit block page without lock */
src_page = get_meta_page(sbi, src_off);
dst_page = grab_meta_page(sbi, dst_off);
f2fs_bug_on(sbi, PageDirty(src_page));
src_addr = page_address(src_page);
dst_addr = page_address(dst_page);
memcpy(dst_addr, src_addr, PAGE_SIZE);
set_page_dirty(dst_page);
f2fs_put_page(src_page, 1);
set_to_next_sit(sit_i, start);
return dst_page;
}
static struct sit_entry_set *grab_sit_entry_set(void)
{
struct sit_entry_set *ses =
f2fs_kmem_cache_alloc(sit_entry_set_slab, GFP_NOFS);
ses->entry_cnt = 0;
INIT_LIST_HEAD(&ses->set_list);
return ses;
}
static void release_sit_entry_set(struct sit_entry_set *ses)
{
list_del(&ses->set_list);
kmem_cache_free(sit_entry_set_slab, ses);
}
static void adjust_sit_entry_set(struct sit_entry_set *ses,
struct list_head *head)
{
struct sit_entry_set *next = ses;
if (list_is_last(&ses->set_list, head))
return;
list_for_each_entry_continue(next, head, set_list)
if (ses->entry_cnt <= next->entry_cnt)
break;
list_move_tail(&ses->set_list, &next->set_list);
}
static void add_sit_entry(unsigned int segno, struct list_head *head)
{
struct sit_entry_set *ses;
unsigned int start_segno = START_SEGNO(segno);
list_for_each_entry(ses, head, set_list) {
if (ses->start_segno == start_segno) {
ses->entry_cnt++;
adjust_sit_entry_set(ses, head);
return;
}
}
ses = grab_sit_entry_set();
ses->start_segno = start_segno;
ses->entry_cnt++;
list_add(&ses->set_list, head);
}
static void add_sits_in_set(struct f2fs_sb_info *sbi)
{
struct f2fs_sm_info *sm_info = SM_I(sbi);
struct list_head *set_list = &sm_info->sit_entry_set;
unsigned long *bitmap = SIT_I(sbi)->dirty_sentries_bitmap;
unsigned int segno;
for_each_set_bit(segno, bitmap, MAIN_SEGS(sbi))
add_sit_entry(segno, set_list);
}
static void remove_sits_in_journal(struct f2fs_sb_info *sbi)
{
struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
struct f2fs_journal *journal = curseg->journal;
int i;
down_write(&curseg->journal_rwsem);
for (i = 0; i < sits_in_cursum(journal); i++) {
unsigned int segno;
bool dirtied;
segno = le32_to_cpu(segno_in_journal(journal, i));
dirtied = __mark_sit_entry_dirty(sbi, segno);
if (!dirtied)
add_sit_entry(segno, &SM_I(sbi)->sit_entry_set);
}
update_sits_in_cursum(journal, -i);
up_write(&curseg->journal_rwsem);
}
/*
* CP calls this function, which flushes SIT entries including sit_journal,
* and moves prefree segs to free segs.
*/
void flush_sit_entries(struct f2fs_sb_info *sbi, struct cp_control *cpc)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned long *bitmap = sit_i->dirty_sentries_bitmap;
struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
struct f2fs_journal *journal = curseg->journal;
struct sit_entry_set *ses, *tmp;
struct list_head *head = &SM_I(sbi)->sit_entry_set;
bool to_journal = true;
struct seg_entry *se;
mutex_lock(&sit_i->sentry_lock);
if (!sit_i->dirty_sentries)
goto out;
/*
* add and account sit entries of dirty bitmap in sit entry
* set temporarily
*/
add_sits_in_set(sbi);
/*
* if there are no enough space in journal to store dirty sit
* entries, remove all entries from journal and add and account
* them in sit entry set.
*/
if (!__has_cursum_space(journal, sit_i->dirty_sentries, SIT_JOURNAL))
remove_sits_in_journal(sbi);
/*
* there are two steps to flush sit entries:
* #1, flush sit entries to journal in current cold data summary block.
* #2, flush sit entries to sit page.
*/
list_for_each_entry_safe(ses, tmp, head, set_list) {
struct page *page = NULL;
struct f2fs_sit_block *raw_sit = NULL;
unsigned int start_segno = ses->start_segno;
unsigned int end = min(start_segno + SIT_ENTRY_PER_BLOCK,
(unsigned long)MAIN_SEGS(sbi));
unsigned int segno = start_segno;
if (to_journal &&
!__has_cursum_space(journal, ses->entry_cnt, SIT_JOURNAL))
to_journal = false;
if (to_journal) {
down_write(&curseg->journal_rwsem);
} else {
page = get_next_sit_page(sbi, start_segno);
raw_sit = page_address(page);
}
/* flush dirty sit entries in region of current sit set */
for_each_set_bit_from(segno, bitmap, end) {
int offset, sit_offset;
se = get_seg_entry(sbi, segno);
/* add discard candidates */
if (!(cpc->reason & CP_DISCARD)) {
cpc->trim_start = segno;
add_discard_addrs(sbi, cpc, false);
}
if (to_journal) {
offset = lookup_journal_in_cursum(journal,
SIT_JOURNAL, segno, 1);
f2fs_bug_on(sbi, offset < 0);
segno_in_journal(journal, offset) =
cpu_to_le32(segno);
seg_info_to_raw_sit(se,
&sit_in_journal(journal, offset));
} else {
sit_offset = SIT_ENTRY_OFFSET(sit_i, segno);
seg_info_to_raw_sit(se,
&raw_sit->entries[sit_offset]);
}
__clear_bit(segno, bitmap);
sit_i->dirty_sentries--;
ses->entry_cnt--;
}
if (to_journal)
up_write(&curseg->journal_rwsem);
else
f2fs_put_page(page, 1);
f2fs_bug_on(sbi, ses->entry_cnt);
release_sit_entry_set(ses);
}
f2fs_bug_on(sbi, !list_empty(head));
f2fs_bug_on(sbi, sit_i->dirty_sentries);
out:
if (cpc->reason & CP_DISCARD) {
__u64 trim_start = cpc->trim_start;
for (; cpc->trim_start <= cpc->trim_end; cpc->trim_start++)
add_discard_addrs(sbi, cpc, false);
cpc->trim_start = trim_start;
}
mutex_unlock(&sit_i->sentry_lock);
set_prefree_as_free_segments(sbi);
}
static int build_sit_info(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct sit_info *sit_i;
unsigned int sit_segs, start;
char *src_bitmap;
unsigned int bitmap_size;
/* allocate memory for SIT information */
sit_i = kzalloc(sizeof(struct sit_info), GFP_KERNEL);
if (!sit_i)
return -ENOMEM;
SM_I(sbi)->sit_info = sit_i;
sit_i->sentries = kvzalloc(MAIN_SEGS(sbi) *
sizeof(struct seg_entry), GFP_KERNEL);
if (!sit_i->sentries)
return -ENOMEM;
bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
sit_i->dirty_sentries_bitmap = kvzalloc(bitmap_size, GFP_KERNEL);
if (!sit_i->dirty_sentries_bitmap)
return -ENOMEM;
for (start = 0; start < MAIN_SEGS(sbi); start++) {
sit_i->sentries[start].cur_valid_map
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
sit_i->sentries[start].ckpt_valid_map
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->sentries[start].cur_valid_map ||
!sit_i->sentries[start].ckpt_valid_map)
return -ENOMEM;
#ifdef CONFIG_F2FS_CHECK_FS
sit_i->sentries[start].cur_valid_map_mir
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->sentries[start].cur_valid_map_mir)
return -ENOMEM;
#endif
if (f2fs_discard_en(sbi)) {
sit_i->sentries[start].discard_map
= kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->sentries[start].discard_map)
return -ENOMEM;
}
}
sit_i->tmp_map = kzalloc(SIT_VBLOCK_MAP_SIZE, GFP_KERNEL);
if (!sit_i->tmp_map)
return -ENOMEM;
if (sbi->segs_per_sec > 1) {
sit_i->sec_entries = kvzalloc(MAIN_SECS(sbi) *
sizeof(struct sec_entry), GFP_KERNEL);
if (!sit_i->sec_entries)
return -ENOMEM;
}
/* get information related with SIT */
sit_segs = le32_to_cpu(raw_super->segment_count_sit) >> 1;
/* setup SIT bitmap from ckeckpoint pack */
bitmap_size = __bitmap_size(sbi, SIT_BITMAP);
src_bitmap = __bitmap_ptr(sbi, SIT_BITMAP);
sit_i->sit_bitmap = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
if (!sit_i->sit_bitmap)
return -ENOMEM;
#ifdef CONFIG_F2FS_CHECK_FS
sit_i->sit_bitmap_mir = kmemdup(src_bitmap, bitmap_size, GFP_KERNEL);
if (!sit_i->sit_bitmap_mir)
return -ENOMEM;
#endif
/* init SIT information */
sit_i->s_ops = &default_salloc_ops;
sit_i->sit_base_addr = le32_to_cpu(raw_super->sit_blkaddr);
sit_i->sit_blocks = sit_segs << sbi->log_blocks_per_seg;
sit_i->written_valid_blocks = 0;
sit_i->bitmap_size = bitmap_size;
sit_i->dirty_sentries = 0;
sit_i->sents_per_block = SIT_ENTRY_PER_BLOCK;
sit_i->elapsed_time = le64_to_cpu(sbi->ckpt->elapsed_time);
sit_i->mounted_time = ktime_get_real_seconds();
mutex_init(&sit_i->sentry_lock);
return 0;
}
static int build_free_segmap(struct f2fs_sb_info *sbi)
{
struct free_segmap_info *free_i;
unsigned int bitmap_size, sec_bitmap_size;
/* allocate memory for free segmap information */
free_i = kzalloc(sizeof(struct free_segmap_info), GFP_KERNEL);
if (!free_i)
return -ENOMEM;
SM_I(sbi)->free_info = free_i;
bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
free_i->free_segmap = kvmalloc(bitmap_size, GFP_KERNEL);
if (!free_i->free_segmap)
return -ENOMEM;
sec_bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
free_i->free_secmap = kvmalloc(sec_bitmap_size, GFP_KERNEL);
if (!free_i->free_secmap)
return -ENOMEM;
/* set all segments as dirty temporarily */
memset(free_i->free_segmap, 0xff, bitmap_size);
memset(free_i->free_secmap, 0xff, sec_bitmap_size);
/* init free segmap information */
free_i->start_segno = GET_SEGNO_FROM_SEG0(sbi, MAIN_BLKADDR(sbi));
free_i->free_segments = 0;
free_i->free_sections = 0;
spin_lock_init(&free_i->segmap_lock);
return 0;
}
static int build_curseg(struct f2fs_sb_info *sbi)
{
struct curseg_info *array;
int i;
array = kcalloc(NR_CURSEG_TYPE, sizeof(*array), GFP_KERNEL);
if (!array)
return -ENOMEM;
SM_I(sbi)->curseg_array = array;
for (i = 0; i < NR_CURSEG_TYPE; i++) {
mutex_init(&array[i].curseg_mutex);
array[i].sum_blk = kzalloc(PAGE_SIZE, GFP_KERNEL);
if (!array[i].sum_blk)
return -ENOMEM;
init_rwsem(&array[i].journal_rwsem);
array[i].journal = kzalloc(sizeof(struct f2fs_journal),
GFP_KERNEL);
if (!array[i].journal)
return -ENOMEM;
array[i].segno = NULL_SEGNO;
array[i].next_blkoff = 0;
}
return restore_curseg_summaries(sbi);
}
static void build_sit_entries(struct f2fs_sb_info *sbi)
{
struct sit_info *sit_i = SIT_I(sbi);
struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA);
struct f2fs_journal *journal = curseg->journal;
struct seg_entry *se;
struct f2fs_sit_entry sit;
int sit_blk_cnt = SIT_BLK_CNT(sbi);
unsigned int i, start, end;
unsigned int readed, start_blk = 0;
do {
readed = ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES,
META_SIT, true);
start = start_blk * sit_i->sents_per_block;
end = (start_blk + readed) * sit_i->sents_per_block;
for (; start < end && start < MAIN_SEGS(sbi); start++) {
struct f2fs_sit_block *sit_blk;
struct page *page;
se = &sit_i->sentries[start];
page = get_current_sit_page(sbi, start);
sit_blk = (struct f2fs_sit_block *)page_address(page);
sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)];
f2fs_put_page(page, 1);
check_block_count(sbi, start, &sit);
seg_info_from_raw_sit(se, &sit);
/* build discard map only one time */
if (f2fs_discard_en(sbi)) {
if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
memset(se->discard_map, 0xff,
SIT_VBLOCK_MAP_SIZE);
} else {
memcpy(se->discard_map,
se->cur_valid_map,
SIT_VBLOCK_MAP_SIZE);
sbi->discard_blks +=
sbi->blocks_per_seg -
se->valid_blocks;
}
}
if (sbi->segs_per_sec > 1)
get_sec_entry(sbi, start)->valid_blocks +=
se->valid_blocks;
}
start_blk += readed;
} while (start_blk < sit_blk_cnt);
down_read(&curseg->journal_rwsem);
for (i = 0; i < sits_in_cursum(journal); i++) {
unsigned int old_valid_blocks;
start = le32_to_cpu(segno_in_journal(journal, i));
se = &sit_i->sentries[start];
sit = sit_in_journal(journal, i);
old_valid_blocks = se->valid_blocks;
check_block_count(sbi, start, &sit);
seg_info_from_raw_sit(se, &sit);
if (f2fs_discard_en(sbi)) {
if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) {
memset(se->discard_map, 0xff,
SIT_VBLOCK_MAP_SIZE);
} else {
memcpy(se->discard_map, se->cur_valid_map,
SIT_VBLOCK_MAP_SIZE);
sbi->discard_blks += old_valid_blocks -
se->valid_blocks;
}
}
if (sbi->segs_per_sec > 1)
get_sec_entry(sbi, start)->valid_blocks +=
se->valid_blocks - old_valid_blocks;
}
up_read(&curseg->journal_rwsem);
}
static void init_free_segmap(struct f2fs_sb_info *sbi)
{
unsigned int start;
int type;
for (start = 0; start < MAIN_SEGS(sbi); start++) {
struct seg_entry *sentry = get_seg_entry(sbi, start);
if (!sentry->valid_blocks)
__set_free(sbi, start);
else
SIT_I(sbi)->written_valid_blocks +=
sentry->valid_blocks;
}
/* set use the current segments */
for (type = CURSEG_HOT_DATA; type <= CURSEG_COLD_NODE; type++) {
struct curseg_info *curseg_t = CURSEG_I(sbi, type);
__set_test_and_inuse(sbi, curseg_t->segno);
}
}
static void init_dirty_segmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
struct free_segmap_info *free_i = FREE_I(sbi);
unsigned int segno = 0, offset = 0;
unsigned short valid_blocks;
while (1) {
/* find dirty segment based on free segmap */
segno = find_next_inuse(free_i, MAIN_SEGS(sbi), offset);
if (segno >= MAIN_SEGS(sbi))
break;
offset = segno + 1;
valid_blocks = get_valid_blocks(sbi, segno, false);
if (valid_blocks == sbi->blocks_per_seg || !valid_blocks)
continue;
if (valid_blocks > sbi->blocks_per_seg) {
f2fs_bug_on(sbi, 1);
continue;
}
mutex_lock(&dirty_i->seglist_lock);
__locate_dirty_segment(sbi, segno, DIRTY);
mutex_unlock(&dirty_i->seglist_lock);
}
}
static int init_victim_secmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
unsigned int bitmap_size = f2fs_bitmap_size(MAIN_SECS(sbi));
dirty_i->victim_secmap = kvzalloc(bitmap_size, GFP_KERNEL);
if (!dirty_i->victim_secmap)
return -ENOMEM;
return 0;
}
static int build_dirty_segmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i;
unsigned int bitmap_size, i;
/* allocate memory for dirty segments list information */
dirty_i = kzalloc(sizeof(struct dirty_seglist_info), GFP_KERNEL);
if (!dirty_i)
return -ENOMEM;
SM_I(sbi)->dirty_info = dirty_i;
mutex_init(&dirty_i->seglist_lock);
bitmap_size = f2fs_bitmap_size(MAIN_SEGS(sbi));
for (i = 0; i < NR_DIRTY_TYPE; i++) {
dirty_i->dirty_segmap[i] = kvzalloc(bitmap_size, GFP_KERNEL);
if (!dirty_i->dirty_segmap[i])
return -ENOMEM;
}
init_dirty_segmap(sbi);
return init_victim_secmap(sbi);
}
/*
* Update min, max modified time for cost-benefit GC algorithm
*/
static void init_min_max_mtime(struct f2fs_sb_info *sbi)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned int segno;
mutex_lock(&sit_i->sentry_lock);
sit_i->min_mtime = LLONG_MAX;
for (segno = 0; segno < MAIN_SEGS(sbi); segno += sbi->segs_per_sec) {
unsigned int i;
unsigned long long mtime = 0;
for (i = 0; i < sbi->segs_per_sec; i++)
mtime += get_seg_entry(sbi, segno + i)->mtime;
mtime = div_u64(mtime, sbi->segs_per_sec);
if (sit_i->min_mtime > mtime)
sit_i->min_mtime = mtime;
}
sit_i->max_mtime = get_mtime(sbi);
mutex_unlock(&sit_i->sentry_lock);
}
int build_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
struct f2fs_sm_info *sm_info;
int err;
sm_info = kzalloc(sizeof(struct f2fs_sm_info), GFP_KERNEL);
if (!sm_info)
return -ENOMEM;
/* init sm info */
sbi->sm_info = sm_info;
sm_info->seg0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
sm_info->main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
sm_info->segment_count = le32_to_cpu(raw_super->segment_count);
sm_info->reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
sm_info->ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
sm_info->main_segments = le32_to_cpu(raw_super->segment_count_main);
sm_info->ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
sm_info->rec_prefree_segments = sm_info->main_segments *
DEF_RECLAIM_PREFREE_SEGMENTS / 100;
if (sm_info->rec_prefree_segments > DEF_MAX_RECLAIM_PREFREE_SEGMENTS)
sm_info->rec_prefree_segments = DEF_MAX_RECLAIM_PREFREE_SEGMENTS;
if (!test_opt(sbi, LFS))
sm_info->ipu_policy = 1 << F2FS_IPU_FSYNC;
sm_info->min_ipu_util = DEF_MIN_IPU_UTIL;
sm_info->min_fsync_blocks = DEF_MIN_FSYNC_BLOCKS;
sm_info->min_hot_blocks = DEF_MIN_HOT_BLOCKS;
sm_info->trim_sections = DEF_BATCHED_TRIM_SECTIONS;
INIT_LIST_HEAD(&sm_info->sit_entry_set);
if (!f2fs_readonly(sbi->sb)) {
err = create_flush_cmd_control(sbi);
if (err)
return err;
}
err = create_discard_cmd_control(sbi);
if (err)
return err;
err = build_sit_info(sbi);
if (err)
return err;
err = build_free_segmap(sbi);
if (err)
return err;
err = build_curseg(sbi);
if (err)
return err;
/* reinit free segmap based on SIT */
build_sit_entries(sbi);
init_free_segmap(sbi);
err = build_dirty_segmap(sbi);
if (err)
return err;
init_min_max_mtime(sbi);
return 0;
}
static void discard_dirty_segmap(struct f2fs_sb_info *sbi,
enum dirty_type dirty_type)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
mutex_lock(&dirty_i->seglist_lock);
kvfree(dirty_i->dirty_segmap[dirty_type]);
dirty_i->nr_dirty[dirty_type] = 0;
mutex_unlock(&dirty_i->seglist_lock);
}
static void destroy_victim_secmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
kvfree(dirty_i->victim_secmap);
}
static void destroy_dirty_segmap(struct f2fs_sb_info *sbi)
{
struct dirty_seglist_info *dirty_i = DIRTY_I(sbi);
int i;
if (!dirty_i)
return;
/* discard pre-free/dirty segments list */
for (i = 0; i < NR_DIRTY_TYPE; i++)
discard_dirty_segmap(sbi, i);
destroy_victim_secmap(sbi);
SM_I(sbi)->dirty_info = NULL;
kfree(dirty_i);
}
static void destroy_curseg(struct f2fs_sb_info *sbi)
{
struct curseg_info *array = SM_I(sbi)->curseg_array;
int i;
if (!array)
return;
SM_I(sbi)->curseg_array = NULL;
for (i = 0; i < NR_CURSEG_TYPE; i++) {
kfree(array[i].sum_blk);
kfree(array[i].journal);
}
kfree(array);
}
static void destroy_free_segmap(struct f2fs_sb_info *sbi)
{
struct free_segmap_info *free_i = SM_I(sbi)->free_info;
if (!free_i)
return;
SM_I(sbi)->free_info = NULL;
kvfree(free_i->free_segmap);
kvfree(free_i->free_secmap);
kfree(free_i);
}
static void destroy_sit_info(struct f2fs_sb_info *sbi)
{
struct sit_info *sit_i = SIT_I(sbi);
unsigned int start;
if (!sit_i)
return;
if (sit_i->sentries) {
for (start = 0; start < MAIN_SEGS(sbi); start++) {
kfree(sit_i->sentries[start].cur_valid_map);
#ifdef CONFIG_F2FS_CHECK_FS
kfree(sit_i->sentries[start].cur_valid_map_mir);
#endif
kfree(sit_i->sentries[start].ckpt_valid_map);
kfree(sit_i->sentries[start].discard_map);
}
}
kfree(sit_i->tmp_map);
kvfree(sit_i->sentries);
kvfree(sit_i->sec_entries);
kvfree(sit_i->dirty_sentries_bitmap);
SM_I(sbi)->sit_info = NULL;
kfree(sit_i->sit_bitmap);
#ifdef CONFIG_F2FS_CHECK_FS
kfree(sit_i->sit_bitmap_mir);
#endif
kfree(sit_i);
}
void destroy_segment_manager(struct f2fs_sb_info *sbi)
{
struct f2fs_sm_info *sm_info = SM_I(sbi);
if (!sm_info)
return;
destroy_flush_cmd_control(sbi, true);
destroy_discard_cmd_control(sbi);
destroy_dirty_segmap(sbi);
destroy_curseg(sbi);
destroy_free_segmap(sbi);
destroy_sit_info(sbi);
sbi->sm_info = NULL;
kfree(sm_info);
}
int __init create_segment_manager_caches(void)
{
discard_entry_slab = f2fs_kmem_cache_create("discard_entry",
sizeof(struct discard_entry));
if (!discard_entry_slab)
goto fail;
discard_cmd_slab = f2fs_kmem_cache_create("discard_cmd",
sizeof(struct discard_cmd));
if (!discard_cmd_slab)
goto destroy_discard_entry;
sit_entry_set_slab = f2fs_kmem_cache_create("sit_entry_set",
sizeof(struct sit_entry_set));
if (!sit_entry_set_slab)
goto destroy_discard_cmd;
inmem_entry_slab = f2fs_kmem_cache_create("inmem_page_entry",
sizeof(struct inmem_pages));
if (!inmem_entry_slab)
goto destroy_sit_entry_set;
return 0;
destroy_sit_entry_set:
kmem_cache_destroy(sit_entry_set_slab);
destroy_discard_cmd:
kmem_cache_destroy(discard_cmd_slab);
destroy_discard_entry:
kmem_cache_destroy(discard_entry_slab);
fail:
return -ENOMEM;
}
void destroy_segment_manager_caches(void)
{
kmem_cache_destroy(sit_entry_set_slab);
kmem_cache_destroy(discard_cmd_slab);
kmem_cache_destroy(discard_entry_slab);
kmem_cache_destroy(inmem_entry_slab);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3012_1 |
crossvul-cpp_data_bad_3641_0 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* Generic socket support routines. Memory allocators, socket lock/release
* handler for protocols to use and generic option handler.
*
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Florian La Roche, <flla@stud.uni-sb.de>
* Alan Cox, <A.Cox@swansea.ac.uk>
*
* Fixes:
* Alan Cox : Numerous verify_area() problems
* Alan Cox : Connecting on a connecting socket
* now returns an error for tcp.
* Alan Cox : sock->protocol is set correctly.
* and is not sometimes left as 0.
* Alan Cox : connect handles icmp errors on a
* connect properly. Unfortunately there
* is a restart syscall nasty there. I
* can't match BSD without hacking the C
* library. Ideas urgently sought!
* Alan Cox : Disallow bind() to addresses that are
* not ours - especially broadcast ones!!
* Alan Cox : Socket 1024 _IS_ ok for users. (fencepost)
* Alan Cox : sock_wfree/sock_rfree don't destroy sockets,
* instead they leave that for the DESTROY timer.
* Alan Cox : Clean up error flag in accept
* Alan Cox : TCP ack handling is buggy, the DESTROY timer
* was buggy. Put a remove_sock() in the handler
* for memory when we hit 0. Also altered the timer
* code. The ACK stuff can wait and needs major
* TCP layer surgery.
* Alan Cox : Fixed TCP ack bug, removed remove sock
* and fixed timer/inet_bh race.
* Alan Cox : Added zapped flag for TCP
* Alan Cox : Move kfree_skb into skbuff.c and tidied up surplus code
* Alan Cox : for new sk_buff allocations wmalloc/rmalloc now call alloc_skb
* Alan Cox : kfree_s calls now are kfree_skbmem so we can track skb resources
* Alan Cox : Supports socket option broadcast now as does udp. Packet and raw need fixing.
* Alan Cox : Added RCVBUF,SNDBUF size setting. It suddenly occurred to me how easy it was so...
* Rick Sladkey : Relaxed UDP rules for matching packets.
* C.E.Hawkins : IFF_PROMISC/SIOCGHWADDR support
* Pauline Middelink : identd support
* Alan Cox : Fixed connect() taking signals I think.
* Alan Cox : SO_LINGER supported
* Alan Cox : Error reporting fixes
* Anonymous : inet_create tidied up (sk->reuse setting)
* Alan Cox : inet sockets don't set sk->type!
* Alan Cox : Split socket option code
* Alan Cox : Callbacks
* Alan Cox : Nagle flag for Charles & Johannes stuff
* Alex : Removed restriction on inet fioctl
* Alan Cox : Splitting INET from NET core
* Alan Cox : Fixed bogus SO_TYPE handling in getsockopt()
* Adam Caldwell : Missing return in SO_DONTROUTE/SO_DEBUG code
* Alan Cox : Split IP from generic code
* Alan Cox : New kfree_skbmem()
* Alan Cox : Make SO_DEBUG superuser only.
* Alan Cox : Allow anyone to clear SO_DEBUG
* (compatibility fix)
* Alan Cox : Added optimistic memory grabbing for AF_UNIX throughput.
* Alan Cox : Allocator for a socket is settable.
* Alan Cox : SO_ERROR includes soft errors.
* Alan Cox : Allow NULL arguments on some SO_ opts
* Alan Cox : Generic socket allocation to make hooks
* easier (suggested by Craig Metz).
* Michael Pall : SO_ERROR returns positive errno again
* Steve Whitehouse: Added default destructor to free
* protocol private data.
* Steve Whitehouse: Added various other default routines
* common to several socket families.
* Chris Evans : Call suser() check last on F_SETOWN
* Jay Schulist : Added SO_ATTACH_FILTER and SO_DETACH_FILTER.
* Andi Kleen : Add sock_kmalloc()/sock_kfree_s()
* Andi Kleen : Fix write_space callback
* Chris Evans : Security fixes - signedness again
* Arnaldo C. Melo : cleanups, use skb_queue_purge
*
* To Fix:
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sched.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/poll.h>
#include <linux/tcp.h>
#include <linux/init.h>
#include <linux/highmem.h>
#include <linux/user_namespace.h>
#include <linux/static_key.h>
#include <linux/memcontrol.h>
#include <linux/prefetch.h>
#include <asm/uaccess.h>
#include <linux/netdevice.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/request_sock.h>
#include <net/sock.h>
#include <linux/net_tstamp.h>
#include <net/xfrm.h>
#include <linux/ipsec.h>
#include <net/cls_cgroup.h>
#include <net/netprio_cgroup.h>
#include <linux/filter.h>
#include <trace/events/sock.h>
#ifdef CONFIG_INET
#include <net/tcp.h>
#endif
static DEFINE_MUTEX(proto_list_mutex);
static LIST_HEAD(proto_list);
#ifdef CONFIG_CGROUP_MEM_RES_CTLR_KMEM
int mem_cgroup_sockets_init(struct mem_cgroup *memcg, struct cgroup_subsys *ss)
{
struct proto *proto;
int ret = 0;
mutex_lock(&proto_list_mutex);
list_for_each_entry(proto, &proto_list, node) {
if (proto->init_cgroup) {
ret = proto->init_cgroup(memcg, ss);
if (ret)
goto out;
}
}
mutex_unlock(&proto_list_mutex);
return ret;
out:
list_for_each_entry_continue_reverse(proto, &proto_list, node)
if (proto->destroy_cgroup)
proto->destroy_cgroup(memcg);
mutex_unlock(&proto_list_mutex);
return ret;
}
void mem_cgroup_sockets_destroy(struct mem_cgroup *memcg)
{
struct proto *proto;
mutex_lock(&proto_list_mutex);
list_for_each_entry_reverse(proto, &proto_list, node)
if (proto->destroy_cgroup)
proto->destroy_cgroup(memcg);
mutex_unlock(&proto_list_mutex);
}
#endif
/*
* Each address family might have different locking rules, so we have
* one slock key per address family:
*/
static struct lock_class_key af_family_keys[AF_MAX];
static struct lock_class_key af_family_slock_keys[AF_MAX];
struct static_key memcg_socket_limit_enabled;
EXPORT_SYMBOL(memcg_socket_limit_enabled);
/*
* Make lock validator output more readable. (we pre-construct these
* strings build-time, so that runtime initialization of socket
* locks is fast):
*/
static const char *const af_family_key_strings[AF_MAX+1] = {
"sk_lock-AF_UNSPEC", "sk_lock-AF_UNIX" , "sk_lock-AF_INET" ,
"sk_lock-AF_AX25" , "sk_lock-AF_IPX" , "sk_lock-AF_APPLETALK",
"sk_lock-AF_NETROM", "sk_lock-AF_BRIDGE" , "sk_lock-AF_ATMPVC" ,
"sk_lock-AF_X25" , "sk_lock-AF_INET6" , "sk_lock-AF_ROSE" ,
"sk_lock-AF_DECnet", "sk_lock-AF_NETBEUI" , "sk_lock-AF_SECURITY" ,
"sk_lock-AF_KEY" , "sk_lock-AF_NETLINK" , "sk_lock-AF_PACKET" ,
"sk_lock-AF_ASH" , "sk_lock-AF_ECONET" , "sk_lock-AF_ATMSVC" ,
"sk_lock-AF_RDS" , "sk_lock-AF_SNA" , "sk_lock-AF_IRDA" ,
"sk_lock-AF_PPPOX" , "sk_lock-AF_WANPIPE" , "sk_lock-AF_LLC" ,
"sk_lock-27" , "sk_lock-28" , "sk_lock-AF_CAN" ,
"sk_lock-AF_TIPC" , "sk_lock-AF_BLUETOOTH", "sk_lock-IUCV" ,
"sk_lock-AF_RXRPC" , "sk_lock-AF_ISDN" , "sk_lock-AF_PHONET" ,
"sk_lock-AF_IEEE802154", "sk_lock-AF_CAIF" , "sk_lock-AF_ALG" ,
"sk_lock-AF_NFC" , "sk_lock-AF_MAX"
};
static const char *const af_family_slock_key_strings[AF_MAX+1] = {
"slock-AF_UNSPEC", "slock-AF_UNIX" , "slock-AF_INET" ,
"slock-AF_AX25" , "slock-AF_IPX" , "slock-AF_APPLETALK",
"slock-AF_NETROM", "slock-AF_BRIDGE" , "slock-AF_ATMPVC" ,
"slock-AF_X25" , "slock-AF_INET6" , "slock-AF_ROSE" ,
"slock-AF_DECnet", "slock-AF_NETBEUI" , "slock-AF_SECURITY" ,
"slock-AF_KEY" , "slock-AF_NETLINK" , "slock-AF_PACKET" ,
"slock-AF_ASH" , "slock-AF_ECONET" , "slock-AF_ATMSVC" ,
"slock-AF_RDS" , "slock-AF_SNA" , "slock-AF_IRDA" ,
"slock-AF_PPPOX" , "slock-AF_WANPIPE" , "slock-AF_LLC" ,
"slock-27" , "slock-28" , "slock-AF_CAN" ,
"slock-AF_TIPC" , "slock-AF_BLUETOOTH", "slock-AF_IUCV" ,
"slock-AF_RXRPC" , "slock-AF_ISDN" , "slock-AF_PHONET" ,
"slock-AF_IEEE802154", "slock-AF_CAIF" , "slock-AF_ALG" ,
"slock-AF_NFC" , "slock-AF_MAX"
};
static const char *const af_family_clock_key_strings[AF_MAX+1] = {
"clock-AF_UNSPEC", "clock-AF_UNIX" , "clock-AF_INET" ,
"clock-AF_AX25" , "clock-AF_IPX" , "clock-AF_APPLETALK",
"clock-AF_NETROM", "clock-AF_BRIDGE" , "clock-AF_ATMPVC" ,
"clock-AF_X25" , "clock-AF_INET6" , "clock-AF_ROSE" ,
"clock-AF_DECnet", "clock-AF_NETBEUI" , "clock-AF_SECURITY" ,
"clock-AF_KEY" , "clock-AF_NETLINK" , "clock-AF_PACKET" ,
"clock-AF_ASH" , "clock-AF_ECONET" , "clock-AF_ATMSVC" ,
"clock-AF_RDS" , "clock-AF_SNA" , "clock-AF_IRDA" ,
"clock-AF_PPPOX" , "clock-AF_WANPIPE" , "clock-AF_LLC" ,
"clock-27" , "clock-28" , "clock-AF_CAN" ,
"clock-AF_TIPC" , "clock-AF_BLUETOOTH", "clock-AF_IUCV" ,
"clock-AF_RXRPC" , "clock-AF_ISDN" , "clock-AF_PHONET" ,
"clock-AF_IEEE802154", "clock-AF_CAIF" , "clock-AF_ALG" ,
"clock-AF_NFC" , "clock-AF_MAX"
};
/*
* sk_callback_lock locking rules are per-address-family,
* so split the lock classes by using a per-AF key:
*/
static struct lock_class_key af_callback_keys[AF_MAX];
/* Take into consideration the size of the struct sk_buff overhead in the
* determination of these values, since that is non-constant across
* platforms. This makes socket queueing behavior and performance
* not depend upon such differences.
*/
#define _SK_MEM_PACKETS 256
#define _SK_MEM_OVERHEAD SKB_TRUESIZE(256)
#define SK_WMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
#define SK_RMEM_MAX (_SK_MEM_OVERHEAD * _SK_MEM_PACKETS)
/* Run time adjustable parameters. */
__u32 sysctl_wmem_max __read_mostly = SK_WMEM_MAX;
EXPORT_SYMBOL(sysctl_wmem_max);
__u32 sysctl_rmem_max __read_mostly = SK_RMEM_MAX;
EXPORT_SYMBOL(sysctl_rmem_max);
__u32 sysctl_wmem_default __read_mostly = SK_WMEM_MAX;
__u32 sysctl_rmem_default __read_mostly = SK_RMEM_MAX;
/* Maximal space eaten by iovec or ancillary data plus some space */
int sysctl_optmem_max __read_mostly = sizeof(unsigned long)*(2*UIO_MAXIOV+512);
EXPORT_SYMBOL(sysctl_optmem_max);
#if defined(CONFIG_CGROUPS)
#if !defined(CONFIG_NET_CLS_CGROUP)
int net_cls_subsys_id = -1;
EXPORT_SYMBOL_GPL(net_cls_subsys_id);
#endif
#if !defined(CONFIG_NETPRIO_CGROUP)
int net_prio_subsys_id = -1;
EXPORT_SYMBOL_GPL(net_prio_subsys_id);
#endif
#endif
static int sock_set_timeout(long *timeo_p, char __user *optval, int optlen)
{
struct timeval tv;
if (optlen < sizeof(tv))
return -EINVAL;
if (copy_from_user(&tv, optval, sizeof(tv)))
return -EFAULT;
if (tv.tv_usec < 0 || tv.tv_usec >= USEC_PER_SEC)
return -EDOM;
if (tv.tv_sec < 0) {
static int warned __read_mostly;
*timeo_p = 0;
if (warned < 10 && net_ratelimit()) {
warned++;
pr_info("%s: `%s' (pid %d) tries to set negative timeout\n",
__func__, current->comm, task_pid_nr(current));
}
return 0;
}
*timeo_p = MAX_SCHEDULE_TIMEOUT;
if (tv.tv_sec == 0 && tv.tv_usec == 0)
return 0;
if (tv.tv_sec < (MAX_SCHEDULE_TIMEOUT/HZ - 1))
*timeo_p = tv.tv_sec*HZ + (tv.tv_usec+(1000000/HZ-1))/(1000000/HZ);
return 0;
}
static void sock_warn_obsolete_bsdism(const char *name)
{
static int warned;
static char warncomm[TASK_COMM_LEN];
if (strcmp(warncomm, current->comm) && warned < 5) {
strcpy(warncomm, current->comm);
pr_warn("process `%s' is using obsolete %s SO_BSDCOMPAT\n",
warncomm, name);
warned++;
}
}
#define SK_FLAGS_TIMESTAMP ((1UL << SOCK_TIMESTAMP) | (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE))
static void sock_disable_timestamp(struct sock *sk, unsigned long flags)
{
if (sk->sk_flags & flags) {
sk->sk_flags &= ~flags;
if (!(sk->sk_flags & SK_FLAGS_TIMESTAMP))
net_disable_timestamp();
}
}
int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
int err;
int skb_len;
unsigned long flags;
struct sk_buff_head *list = &sk->sk_receive_queue;
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) {
atomic_inc(&sk->sk_drops);
trace_sock_rcvqueue_full(sk, skb);
return -ENOMEM;
}
err = sk_filter(sk, skb);
if (err)
return err;
if (!sk_rmem_schedule(sk, skb->truesize)) {
atomic_inc(&sk->sk_drops);
return -ENOBUFS;
}
skb->dev = NULL;
skb_set_owner_r(skb, sk);
/* Cache the SKB length before we tack it onto the receive
* queue. Once it is added it no longer belongs to us and
* may be freed by other threads of control pulling packets
* from the queue.
*/
skb_len = skb->len;
/* we escape from rcu protected region, make sure we dont leak
* a norefcounted dst
*/
skb_dst_force(skb);
spin_lock_irqsave(&list->lock, flags);
skb->dropcount = atomic_read(&sk->sk_drops);
__skb_queue_tail(list, skb);
spin_unlock_irqrestore(&list->lock, flags);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, skb_len);
return 0;
}
EXPORT_SYMBOL(sock_queue_rcv_skb);
int sk_receive_skb(struct sock *sk, struct sk_buff *skb, const int nested)
{
int rc = NET_RX_SUCCESS;
if (sk_filter(sk, skb))
goto discard_and_relse;
skb->dev = NULL;
if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf)) {
atomic_inc(&sk->sk_drops);
goto discard_and_relse;
}
if (nested)
bh_lock_sock_nested(sk);
else
bh_lock_sock(sk);
if (!sock_owned_by_user(sk)) {
/*
* trylock + unlock semantics:
*/
mutex_acquire(&sk->sk_lock.dep_map, 0, 1, _RET_IP_);
rc = sk_backlog_rcv(sk, skb);
mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);
} else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) {
bh_unlock_sock(sk);
atomic_inc(&sk->sk_drops);
goto discard_and_relse;
}
bh_unlock_sock(sk);
out:
sock_put(sk);
return rc;
discard_and_relse:
kfree_skb(skb);
goto out;
}
EXPORT_SYMBOL(sk_receive_skb);
void sk_reset_txq(struct sock *sk)
{
sk_tx_queue_clear(sk);
}
EXPORT_SYMBOL(sk_reset_txq);
struct dst_entry *__sk_dst_check(struct sock *sk, u32 cookie)
{
struct dst_entry *dst = __sk_dst_get(sk);
if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk_tx_queue_clear(sk);
RCU_INIT_POINTER(sk->sk_dst_cache, NULL);
dst_release(dst);
return NULL;
}
return dst;
}
EXPORT_SYMBOL(__sk_dst_check);
struct dst_entry *sk_dst_check(struct sock *sk, u32 cookie)
{
struct dst_entry *dst = sk_dst_get(sk);
if (dst && dst->obsolete && dst->ops->check(dst, cookie) == NULL) {
sk_dst_reset(sk);
dst_release(dst);
return NULL;
}
return dst;
}
EXPORT_SYMBOL(sk_dst_check);
static int sock_bindtodevice(struct sock *sk, char __user *optval, int optlen)
{
int ret = -ENOPROTOOPT;
#ifdef CONFIG_NETDEVICES
struct net *net = sock_net(sk);
char devname[IFNAMSIZ];
int index;
/* Sorry... */
ret = -EPERM;
if (!capable(CAP_NET_RAW))
goto out;
ret = -EINVAL;
if (optlen < 0)
goto out;
/* Bind this socket to a particular device like "eth0",
* as specified in the passed interface name. If the
* name is "" or the option length is zero the socket
* is not bound.
*/
if (optlen > IFNAMSIZ - 1)
optlen = IFNAMSIZ - 1;
memset(devname, 0, sizeof(devname));
ret = -EFAULT;
if (copy_from_user(devname, optval, optlen))
goto out;
index = 0;
if (devname[0] != '\0') {
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, devname);
if (dev)
index = dev->ifindex;
rcu_read_unlock();
ret = -ENODEV;
if (!dev)
goto out;
}
lock_sock(sk);
sk->sk_bound_dev_if = index;
sk_dst_reset(sk);
release_sock(sk);
ret = 0;
out:
#endif
return ret;
}
static inline void sock_valbool_flag(struct sock *sk, int bit, int valbool)
{
if (valbool)
sock_set_flag(sk, bit);
else
sock_reset_flag(sk, bit);
}
/*
* This is meant for all protocols to use and covers goings on
* at the socket level. Everything here is generic.
*/
int sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int val;
int valbool;
struct linger ling;
int ret = 0;
/*
* Options without arguments
*/
if (optname == SO_BINDTODEVICE)
return sock_bindtodevice(sk, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
valbool = val ? 1 : 0;
lock_sock(sk);
switch (optname) {
case SO_DEBUG:
if (val && !capable(CAP_NET_ADMIN))
ret = -EACCES;
else
sock_valbool_flag(sk, SOCK_DBG, valbool);
break;
case SO_REUSEADDR:
sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE);
break;
case SO_TYPE:
case SO_PROTOCOL:
case SO_DOMAIN:
case SO_ERROR:
ret = -ENOPROTOOPT;
break;
case SO_DONTROUTE:
sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool);
break;
case SO_BROADCAST:
sock_valbool_flag(sk, SOCK_BROADCAST, valbool);
break;
case SO_SNDBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_wmem_max);
set_sndbuf:
sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF);
/* Wake up sending tasks if we upped the value. */
sk->sk_write_space(sk);
break;
case SO_SNDBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_sndbuf;
case SO_RCVBUF:
/* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/
val = min_t(u32, val, sysctl_rmem_max);
set_rcvbuf:
sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
/*
* We double it on the way in to account for
* "struct sk_buff" etc. overhead. Applications
* assume that the SO_RCVBUF setting they make will
* allow that much actual data to be received on that
* socket.
*
* Applications are unaware that "struct sk_buff" and
* other overheads allocate from the receive buffer
* during socket buffer allocation.
*
* And after considering the possible alternatives,
* returning the value we actually used in getsockopt
* is the most desirable behavior.
*/
sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF);
break;
case SO_RCVBUFFORCE:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
goto set_rcvbuf;
case SO_KEEPALIVE:
#ifdef CONFIG_INET
if (sk->sk_protocol == IPPROTO_TCP)
tcp_set_keepalive(sk, valbool);
#endif
sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool);
break;
case SO_OOBINLINE:
sock_valbool_flag(sk, SOCK_URGINLINE, valbool);
break;
case SO_NO_CHECK:
sk->sk_no_check = valbool;
break;
case SO_PRIORITY:
if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN))
sk->sk_priority = val;
else
ret = -EPERM;
break;
case SO_LINGER:
if (optlen < sizeof(ling)) {
ret = -EINVAL; /* 1003.1g */
break;
}
if (copy_from_user(&ling, optval, sizeof(ling))) {
ret = -EFAULT;
break;
}
if (!ling.l_onoff)
sock_reset_flag(sk, SOCK_LINGER);
else {
#if (BITS_PER_LONG == 32)
if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ)
sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT;
else
#endif
sk->sk_lingertime = (unsigned int)ling.l_linger * HZ;
sock_set_flag(sk, SOCK_LINGER);
}
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("setsockopt");
break;
case SO_PASSCRED:
if (valbool)
set_bit(SOCK_PASSCRED, &sock->flags);
else
clear_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_TIMESTAMP:
case SO_TIMESTAMPNS:
if (valbool) {
if (optname == SO_TIMESTAMP)
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
else
sock_set_flag(sk, SOCK_RCVTSTAMPNS);
sock_set_flag(sk, SOCK_RCVTSTAMP);
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
} else {
sock_reset_flag(sk, SOCK_RCVTSTAMP);
sock_reset_flag(sk, SOCK_RCVTSTAMPNS);
}
break;
case SO_TIMESTAMPING:
if (val & ~SOF_TIMESTAMPING_MASK) {
ret = -EINVAL;
break;
}
sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE,
val & SOF_TIMESTAMPING_TX_HARDWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE,
val & SOF_TIMESTAMPING_TX_SOFTWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE,
val & SOF_TIMESTAMPING_RX_HARDWARE);
if (val & SOF_TIMESTAMPING_RX_SOFTWARE)
sock_enable_timestamp(sk,
SOCK_TIMESTAMPING_RX_SOFTWARE);
else
sock_disable_timestamp(sk,
(1UL << SOCK_TIMESTAMPING_RX_SOFTWARE));
sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE,
val & SOF_TIMESTAMPING_SOFTWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE,
val & SOF_TIMESTAMPING_SYS_HARDWARE);
sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE,
val & SOF_TIMESTAMPING_RAW_HARDWARE);
break;
case SO_RCVLOWAT:
if (val < 0)
val = INT_MAX;
sk->sk_rcvlowat = val ? : 1;
break;
case SO_RCVTIMEO:
ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen);
break;
case SO_SNDTIMEO:
ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen);
break;
case SO_ATTACH_FILTER:
ret = -EINVAL;
if (optlen == sizeof(struct sock_fprog)) {
struct sock_fprog fprog;
ret = -EFAULT;
if (copy_from_user(&fprog, optval, sizeof(fprog)))
break;
ret = sk_attach_filter(&fprog, sk);
}
break;
case SO_DETACH_FILTER:
ret = sk_detach_filter(sk);
break;
case SO_PASSSEC:
if (valbool)
set_bit(SOCK_PASSSEC, &sock->flags);
else
clear_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_MARK:
if (!capable(CAP_NET_ADMIN))
ret = -EPERM;
else
sk->sk_mark = val;
break;
/* We implement the SO_SNDLOWAT etc to
not be settable (1003.1g 5.3) */
case SO_RXQ_OVFL:
sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool);
break;
case SO_WIFI_STATUS:
sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool);
break;
case SO_PEEK_OFF:
if (sock->ops->set_peek_off)
sock->ops->set_peek_off(sk, val);
else
ret = -EOPNOTSUPP;
break;
case SO_NOFCS:
sock_valbool_flag(sk, SOCK_NOFCS, valbool);
break;
default:
ret = -ENOPROTOOPT;
break;
}
release_sock(sk);
return ret;
}
EXPORT_SYMBOL(sock_setsockopt);
void cred_to_ucred(struct pid *pid, const struct cred *cred,
struct ucred *ucred)
{
ucred->pid = pid_vnr(pid);
ucred->uid = ucred->gid = -1;
if (cred) {
struct user_namespace *current_ns = current_user_ns();
ucred->uid = from_kuid(current_ns, cred->euid);
ucred->gid = from_kgid(current_ns, cred->egid);
}
}
EXPORT_SYMBOL_GPL(cred_to_ucred);
int sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
union {
int val;
struct linger ling;
struct timeval tm;
} v;
int lv = sizeof(int);
int len;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
memset(&v, 0, sizeof(v));
switch (optname) {
case SO_DEBUG:
v.val = sock_flag(sk, SOCK_DBG);
break;
case SO_DONTROUTE:
v.val = sock_flag(sk, SOCK_LOCALROUTE);
break;
case SO_BROADCAST:
v.val = sock_flag(sk, SOCK_BROADCAST);
break;
case SO_SNDBUF:
v.val = sk->sk_sndbuf;
break;
case SO_RCVBUF:
v.val = sk->sk_rcvbuf;
break;
case SO_REUSEADDR:
v.val = sk->sk_reuse;
break;
case SO_KEEPALIVE:
v.val = sock_flag(sk, SOCK_KEEPOPEN);
break;
case SO_TYPE:
v.val = sk->sk_type;
break;
case SO_PROTOCOL:
v.val = sk->sk_protocol;
break;
case SO_DOMAIN:
v.val = sk->sk_family;
break;
case SO_ERROR:
v.val = -sock_error(sk);
if (v.val == 0)
v.val = xchg(&sk->sk_err_soft, 0);
break;
case SO_OOBINLINE:
v.val = sock_flag(sk, SOCK_URGINLINE);
break;
case SO_NO_CHECK:
v.val = sk->sk_no_check;
break;
case SO_PRIORITY:
v.val = sk->sk_priority;
break;
case SO_LINGER:
lv = sizeof(v.ling);
v.ling.l_onoff = sock_flag(sk, SOCK_LINGER);
v.ling.l_linger = sk->sk_lingertime / HZ;
break;
case SO_BSDCOMPAT:
sock_warn_obsolete_bsdism("getsockopt");
break;
case SO_TIMESTAMP:
v.val = sock_flag(sk, SOCK_RCVTSTAMP) &&
!sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPNS:
v.val = sock_flag(sk, SOCK_RCVTSTAMPNS);
break;
case SO_TIMESTAMPING:
v.val = 0;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE))
v.val |= SOF_TIMESTAMPING_TX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_TX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE))
v.val |= SOF_TIMESTAMPING_RX_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RX_SOFTWARE))
v.val |= SOF_TIMESTAMPING_RX_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE))
v.val |= SOF_TIMESTAMPING_SOFTWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE))
v.val |= SOF_TIMESTAMPING_SYS_HARDWARE;
if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE))
v.val |= SOF_TIMESTAMPING_RAW_HARDWARE;
break;
case SO_RCVTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_rcvtimeo / HZ;
v.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_SNDTIMEO:
lv = sizeof(struct timeval);
if (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {
v.tm.tv_sec = 0;
v.tm.tv_usec = 0;
} else {
v.tm.tv_sec = sk->sk_sndtimeo / HZ;
v.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) / HZ;
}
break;
case SO_RCVLOWAT:
v.val = sk->sk_rcvlowat;
break;
case SO_SNDLOWAT:
v.val = 1;
break;
case SO_PASSCRED:
v.val = !!test_bit(SOCK_PASSCRED, &sock->flags);
break;
case SO_PEERCRED:
{
struct ucred peercred;
if (len > sizeof(peercred))
len = sizeof(peercred);
cred_to_ucred(sk->sk_peer_pid, sk->sk_peer_cred, &peercred);
if (copy_to_user(optval, &peercred, len))
return -EFAULT;
goto lenout;
}
case SO_PEERNAME:
{
char address[128];
if (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2))
return -ENOTCONN;
if (lv < len)
return -EINVAL;
if (copy_to_user(optval, address, len))
return -EFAULT;
goto lenout;
}
/* Dubious BSD thing... Probably nobody even uses it, but
* the UNIX standard wants it for whatever reason... -DaveM
*/
case SO_ACCEPTCONN:
v.val = sk->sk_state == TCP_LISTEN;
break;
case SO_PASSSEC:
v.val = !!test_bit(SOCK_PASSSEC, &sock->flags);
break;
case SO_PEERSEC:
return security_socket_getpeersec_stream(sock, optval, optlen, len);
case SO_MARK:
v.val = sk->sk_mark;
break;
case SO_RXQ_OVFL:
v.val = sock_flag(sk, SOCK_RXQ_OVFL);
break;
case SO_WIFI_STATUS:
v.val = sock_flag(sk, SOCK_WIFI_STATUS);
break;
case SO_PEEK_OFF:
if (!sock->ops->set_peek_off)
return -EOPNOTSUPP;
v.val = sk->sk_peek_off;
break;
case SO_NOFCS:
v.val = sock_flag(sk, SOCK_NOFCS);
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (copy_to_user(optval, &v, len))
return -EFAULT;
lenout:
if (put_user(len, optlen))
return -EFAULT;
return 0;
}
/*
* Initialize an sk_lock.
*
* (We also register the sk_lock with the lock validator.)
*/
static inline void sock_lock_init(struct sock *sk)
{
sock_lock_init_class_and_name(sk,
af_family_slock_key_strings[sk->sk_family],
af_family_slock_keys + sk->sk_family,
af_family_key_strings[sk->sk_family],
af_family_keys + sk->sk_family);
}
/*
* Copy all fields from osk to nsk but nsk->sk_refcnt must not change yet,
* even temporarly, because of RCU lookups. sk_node should also be left as is.
* We must not copy fields between sk_dontcopy_begin and sk_dontcopy_end
*/
static void sock_copy(struct sock *nsk, const struct sock *osk)
{
#ifdef CONFIG_SECURITY_NETWORK
void *sptr = nsk->sk_security;
#endif
memcpy(nsk, osk, offsetof(struct sock, sk_dontcopy_begin));
memcpy(&nsk->sk_dontcopy_end, &osk->sk_dontcopy_end,
osk->sk_prot->obj_size - offsetof(struct sock, sk_dontcopy_end));
#ifdef CONFIG_SECURITY_NETWORK
nsk->sk_security = sptr;
security_sk_clone(osk, nsk);
#endif
}
/*
* caches using SLAB_DESTROY_BY_RCU should let .next pointer from nulls nodes
* un-modified. Special care is taken when initializing object to zero.
*/
static inline void sk_prot_clear_nulls(struct sock *sk, int size)
{
if (offsetof(struct sock, sk_node.next) != 0)
memset(sk, 0, offsetof(struct sock, sk_node.next));
memset(&sk->sk_node.pprev, 0,
size - offsetof(struct sock, sk_node.pprev));
}
void sk_prot_clear_portaddr_nulls(struct sock *sk, int size)
{
unsigned long nulls1, nulls2;
nulls1 = offsetof(struct sock, __sk_common.skc_node.next);
nulls2 = offsetof(struct sock, __sk_common.skc_portaddr_node.next);
if (nulls1 > nulls2)
swap(nulls1, nulls2);
if (nulls1 != 0)
memset((char *)sk, 0, nulls1);
memset((char *)sk + nulls1 + sizeof(void *), 0,
nulls2 - nulls1 - sizeof(void *));
memset((char *)sk + nulls2 + sizeof(void *), 0,
size - nulls2 - sizeof(void *));
}
EXPORT_SYMBOL(sk_prot_clear_portaddr_nulls);
static struct sock *sk_prot_alloc(struct proto *prot, gfp_t priority,
int family)
{
struct sock *sk;
struct kmem_cache *slab;
slab = prot->slab;
if (slab != NULL) {
sk = kmem_cache_alloc(slab, priority & ~__GFP_ZERO);
if (!sk)
return sk;
if (priority & __GFP_ZERO) {
if (prot->clear_sk)
prot->clear_sk(sk, prot->obj_size);
else
sk_prot_clear_nulls(sk, prot->obj_size);
}
} else
sk = kmalloc(prot->obj_size, priority);
if (sk != NULL) {
kmemcheck_annotate_bitfield(sk, flags);
if (security_sk_alloc(sk, family, priority))
goto out_free;
if (!try_module_get(prot->owner))
goto out_free_sec;
sk_tx_queue_clear(sk);
}
return sk;
out_free_sec:
security_sk_free(sk);
out_free:
if (slab != NULL)
kmem_cache_free(slab, sk);
else
kfree(sk);
return NULL;
}
static void sk_prot_free(struct proto *prot, struct sock *sk)
{
struct kmem_cache *slab;
struct module *owner;
owner = prot->owner;
slab = prot->slab;
security_sk_free(sk);
if (slab != NULL)
kmem_cache_free(slab, sk);
else
kfree(sk);
module_put(owner);
}
#ifdef CONFIG_CGROUPS
void sock_update_classid(struct sock *sk)
{
u32 classid;
rcu_read_lock(); /* doing current task, which cannot vanish. */
classid = task_cls_classid(current);
rcu_read_unlock();
if (classid && classid != sk->sk_classid)
sk->sk_classid = classid;
}
EXPORT_SYMBOL(sock_update_classid);
void sock_update_netprioidx(struct sock *sk)
{
if (in_interrupt())
return;
sk->sk_cgrp_prioidx = task_netprioidx(current);
}
EXPORT_SYMBOL_GPL(sock_update_netprioidx);
#endif
/**
* sk_alloc - All socket objects are allocated here
* @net: the applicable net namespace
* @family: protocol family
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
* @prot: struct proto associated with this new sock instance
*/
struct sock *sk_alloc(struct net *net, int family, gfp_t priority,
struct proto *prot)
{
struct sock *sk;
sk = sk_prot_alloc(prot, priority | __GFP_ZERO, family);
if (sk) {
sk->sk_family = family;
/*
* See comment in struct sock definition to understand
* why we need sk_prot_creator -acme
*/
sk->sk_prot = sk->sk_prot_creator = prot;
sock_lock_init(sk);
sock_net_set(sk, get_net(net));
atomic_set(&sk->sk_wmem_alloc, 1);
sock_update_classid(sk);
sock_update_netprioidx(sk);
}
return sk;
}
EXPORT_SYMBOL(sk_alloc);
static void __sk_free(struct sock *sk)
{
struct sk_filter *filter;
if (sk->sk_destruct)
sk->sk_destruct(sk);
filter = rcu_dereference_check(sk->sk_filter,
atomic_read(&sk->sk_wmem_alloc) == 0);
if (filter) {
sk_filter_uncharge(sk, filter);
RCU_INIT_POINTER(sk->sk_filter, NULL);
}
sock_disable_timestamp(sk, SK_FLAGS_TIMESTAMP);
if (atomic_read(&sk->sk_omem_alloc))
pr_debug("%s: optmem leakage (%d bytes) detected\n",
__func__, atomic_read(&sk->sk_omem_alloc));
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
put_pid(sk->sk_peer_pid);
put_net(sock_net(sk));
sk_prot_free(sk->sk_prot_creator, sk);
}
void sk_free(struct sock *sk)
{
/*
* We subtract one from sk_wmem_alloc and can know if
* some packets are still in some tx queue.
* If not null, sock_wfree() will call __sk_free(sk) later
*/
if (atomic_dec_and_test(&sk->sk_wmem_alloc))
__sk_free(sk);
}
EXPORT_SYMBOL(sk_free);
/*
* Last sock_put should drop reference to sk->sk_net. It has already
* been dropped in sk_change_net. Taking reference to stopping namespace
* is not an option.
* Take reference to a socket to remove it from hash _alive_ and after that
* destroy it in the context of init_net.
*/
void sk_release_kernel(struct sock *sk)
{
if (sk == NULL || sk->sk_socket == NULL)
return;
sock_hold(sk);
sock_release(sk->sk_socket);
release_net(sock_net(sk));
sock_net_set(sk, get_net(&init_net));
sock_put(sk);
}
EXPORT_SYMBOL(sk_release_kernel);
static void sk_update_clone(const struct sock *sk, struct sock *newsk)
{
if (mem_cgroup_sockets_enabled && sk->sk_cgrp)
sock_update_memcg(newsk);
}
/**
* sk_clone_lock - clone a socket, and lock its clone
* @sk: the socket to clone
* @priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
*
* Caller must unlock socket even in error path (bh_unlock_sock(newsk))
*/
struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)
{
struct sock *newsk;
newsk = sk_prot_alloc(sk->sk_prot, priority, sk->sk_family);
if (newsk != NULL) {
struct sk_filter *filter;
sock_copy(newsk, sk);
/* SANITY */
get_net(sock_net(newsk));
sk_node_init(&newsk->sk_node);
sock_lock_init(newsk);
bh_lock_sock(newsk);
newsk->sk_backlog.head = newsk->sk_backlog.tail = NULL;
newsk->sk_backlog.len = 0;
atomic_set(&newsk->sk_rmem_alloc, 0);
/*
* sk_wmem_alloc set to one (see sk_free() and sock_wfree())
*/
atomic_set(&newsk->sk_wmem_alloc, 1);
atomic_set(&newsk->sk_omem_alloc, 0);
skb_queue_head_init(&newsk->sk_receive_queue);
skb_queue_head_init(&newsk->sk_write_queue);
#ifdef CONFIG_NET_DMA
skb_queue_head_init(&newsk->sk_async_wait_queue);
#endif
spin_lock_init(&newsk->sk_dst_lock);
rwlock_init(&newsk->sk_callback_lock);
lockdep_set_class_and_name(&newsk->sk_callback_lock,
af_callback_keys + newsk->sk_family,
af_family_clock_key_strings[newsk->sk_family]);
newsk->sk_dst_cache = NULL;
newsk->sk_wmem_queued = 0;
newsk->sk_forward_alloc = 0;
newsk->sk_send_head = NULL;
newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK;
sock_reset_flag(newsk, SOCK_DONE);
skb_queue_head_init(&newsk->sk_error_queue);
filter = rcu_dereference_protected(newsk->sk_filter, 1);
if (filter != NULL)
sk_filter_charge(newsk, filter);
if (unlikely(xfrm_sk_clone_policy(newsk))) {
/* It is still raw copy of parent, so invalidate
* destructor and make plain sk_free() */
newsk->sk_destruct = NULL;
bh_unlock_sock(newsk);
sk_free(newsk);
newsk = NULL;
goto out;
}
newsk->sk_err = 0;
newsk->sk_priority = 0;
/*
* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
atomic_set(&newsk->sk_refcnt, 2);
/*
* Increment the counter in the same struct proto as the master
* sock (sk_refcnt_debug_inc uses newsk->sk_prot->socks, that
* is the same as sk->sk_prot->socks, as this field was copied
* with memcpy).
*
* This _changes_ the previous behaviour, where
* tcp_create_openreq_child always was incrementing the
* equivalent to tcp_prot->socks (inet_sock_nr), so this have
* to be taken into account in all callers. -acme
*/
sk_refcnt_debug_inc(newsk);
sk_set_socket(newsk, NULL);
newsk->sk_wq = NULL;
sk_update_clone(sk, newsk);
if (newsk->sk_prot->sockets_allocated)
sk_sockets_allocated_inc(newsk);
if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
net_enable_timestamp();
}
out:
return newsk;
}
EXPORT_SYMBOL_GPL(sk_clone_lock);
void sk_setup_caps(struct sock *sk, struct dst_entry *dst)
{
__sk_dst_set(sk, dst);
sk->sk_route_caps = dst->dev->features;
if (sk->sk_route_caps & NETIF_F_GSO)
sk->sk_route_caps |= NETIF_F_GSO_SOFTWARE;
sk->sk_route_caps &= ~sk->sk_route_nocaps;
if (sk_can_gso(sk)) {
if (dst->header_len) {
sk->sk_route_caps &= ~NETIF_F_GSO_MASK;
} else {
sk->sk_route_caps |= NETIF_F_SG | NETIF_F_HW_CSUM;
sk->sk_gso_max_size = dst->dev->gso_max_size;
}
}
}
EXPORT_SYMBOL_GPL(sk_setup_caps);
void __init sk_init(void)
{
if (totalram_pages <= 4096) {
sysctl_wmem_max = 32767;
sysctl_rmem_max = 32767;
sysctl_wmem_default = 32767;
sysctl_rmem_default = 32767;
} else if (totalram_pages >= 131072) {
sysctl_wmem_max = 131071;
sysctl_rmem_max = 131071;
}
}
/*
* Simple resource managers for sockets.
*/
/*
* Write buffer destructor automatically called from kfree_skb.
*/
void sock_wfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
unsigned int len = skb->truesize;
if (!sock_flag(sk, SOCK_USE_WRITE_QUEUE)) {
/*
* Keep a reference on sk_wmem_alloc, this will be released
* after sk_write_space() call
*/
atomic_sub(len - 1, &sk->sk_wmem_alloc);
sk->sk_write_space(sk);
len = 1;
}
/*
* if sk_wmem_alloc reaches 0, we must finish what sk_free()
* could not do because of in-flight packets
*/
if (atomic_sub_and_test(len, &sk->sk_wmem_alloc))
__sk_free(sk);
}
EXPORT_SYMBOL(sock_wfree);
/*
* Read buffer destructor automatically called from kfree_skb.
*/
void sock_rfree(struct sk_buff *skb)
{
struct sock *sk = skb->sk;
unsigned int len = skb->truesize;
atomic_sub(len, &sk->sk_rmem_alloc);
sk_mem_uncharge(sk, len);
}
EXPORT_SYMBOL(sock_rfree);
int sock_i_uid(struct sock *sk)
{
int uid;
read_lock_bh(&sk->sk_callback_lock);
uid = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_uid : 0;
read_unlock_bh(&sk->sk_callback_lock);
return uid;
}
EXPORT_SYMBOL(sock_i_uid);
unsigned long sock_i_ino(struct sock *sk)
{
unsigned long ino;
read_lock_bh(&sk->sk_callback_lock);
ino = sk->sk_socket ? SOCK_INODE(sk->sk_socket)->i_ino : 0;
read_unlock_bh(&sk->sk_callback_lock);
return ino;
}
EXPORT_SYMBOL(sock_i_ino);
/*
* Allocate a skb from the socket's send buffer.
*/
struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force,
gfp_t priority)
{
if (force || atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
struct sk_buff *skb = alloc_skb(size, priority);
if (skb) {
skb_set_owner_w(skb, sk);
return skb;
}
}
return NULL;
}
EXPORT_SYMBOL(sock_wmalloc);
/*
* Allocate a skb from the socket's receive buffer.
*/
struct sk_buff *sock_rmalloc(struct sock *sk, unsigned long size, int force,
gfp_t priority)
{
if (force || atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
struct sk_buff *skb = alloc_skb(size, priority);
if (skb) {
skb_set_owner_r(skb, sk);
return skb;
}
}
return NULL;
}
/*
* Allocate a memory block from the socket's option memory buffer.
*/
void *sock_kmalloc(struct sock *sk, int size, gfp_t priority)
{
if ((unsigned int)size <= sysctl_optmem_max &&
atomic_read(&sk->sk_omem_alloc) + size < sysctl_optmem_max) {
void *mem;
/* First do the add, to avoid the race if kmalloc
* might sleep.
*/
atomic_add(size, &sk->sk_omem_alloc);
mem = kmalloc(size, priority);
if (mem)
return mem;
atomic_sub(size, &sk->sk_omem_alloc);
}
return NULL;
}
EXPORT_SYMBOL(sock_kmalloc);
/*
* Free an option memory block.
*/
void sock_kfree_s(struct sock *sk, void *mem, int size)
{
kfree(mem);
atomic_sub(size, &sk->sk_omem_alloc);
}
EXPORT_SYMBOL(sock_kfree_s);
/* It is almost wait_for_tcp_memory minus release_sock/lock_sock.
I think, these locks should be removed for datagram sockets.
*/
static long sock_wait_for_wmem(struct sock *sk, long timeo)
{
DEFINE_WAIT(wait);
clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
for (;;) {
if (!timeo)
break;
if (signal_pending(current))
break;
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf)
break;
if (sk->sk_shutdown & SEND_SHUTDOWN)
break;
if (sk->sk_err)
break;
timeo = schedule_timeout(timeo);
}
finish_wait(sk_sleep(sk), &wait);
return timeo;
}
/*
* Generic send/receive buffer handlers
*/
struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
unsigned long data_len, int noblock,
int *errcode)
{
struct sk_buff *skb;
gfp_t gfp_mask;
long timeo;
int err;
gfp_mask = sk->sk_allocation;
if (gfp_mask & __GFP_WAIT)
gfp_mask |= __GFP_REPEAT;
timeo = sock_sndtimeo(sk, noblock);
while (1) {
err = sock_error(sk);
if (err != 0)
goto failure;
err = -EPIPE;
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto failure;
if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
skb = alloc_skb(header_len, gfp_mask);
if (skb) {
int npages;
int i;
/* No pages, we're done... */
if (!data_len)
break;
npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
skb->truesize += data_len;
skb_shinfo(skb)->nr_frags = npages;
for (i = 0; i < npages; i++) {
struct page *page;
page = alloc_pages(sk->sk_allocation, 0);
if (!page) {
err = -ENOBUFS;
skb_shinfo(skb)->nr_frags = i;
kfree_skb(skb);
goto failure;
}
__skb_fill_page_desc(skb, i,
page, 0,
(data_len >= PAGE_SIZE ?
PAGE_SIZE :
data_len));
data_len -= PAGE_SIZE;
}
/* Full success... */
break;
}
err = -ENOBUFS;
goto failure;
}
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
err = -EAGAIN;
if (!timeo)
goto failure;
if (signal_pending(current))
goto interrupted;
timeo = sock_wait_for_wmem(sk, timeo);
}
skb_set_owner_w(skb, sk);
return skb;
interrupted:
err = sock_intr_errno(timeo);
failure:
*errcode = err;
return NULL;
}
EXPORT_SYMBOL(sock_alloc_send_pskb);
struct sk_buff *sock_alloc_send_skb(struct sock *sk, unsigned long size,
int noblock, int *errcode)
{
return sock_alloc_send_pskb(sk, size, 0, noblock, errcode);
}
EXPORT_SYMBOL(sock_alloc_send_skb);
static void __lock_sock(struct sock *sk)
__releases(&sk->sk_lock.slock)
__acquires(&sk->sk_lock.slock)
{
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait_exclusive(&sk->sk_lock.wq, &wait,
TASK_UNINTERRUPTIBLE);
spin_unlock_bh(&sk->sk_lock.slock);
schedule();
spin_lock_bh(&sk->sk_lock.slock);
if (!sock_owned_by_user(sk))
break;
}
finish_wait(&sk->sk_lock.wq, &wait);
}
static void __release_sock(struct sock *sk)
__releases(&sk->sk_lock.slock)
__acquires(&sk->sk_lock.slock)
{
struct sk_buff *skb = sk->sk_backlog.head;
do {
sk->sk_backlog.head = sk->sk_backlog.tail = NULL;
bh_unlock_sock(sk);
do {
struct sk_buff *next = skb->next;
prefetch(next);
WARN_ON_ONCE(skb_dst_is_noref(skb));
skb->next = NULL;
sk_backlog_rcv(sk, skb);
/*
* We are in process context here with softirqs
* disabled, use cond_resched_softirq() to preempt.
* This is safe to do because we've taken the backlog
* queue private:
*/
cond_resched_softirq();
skb = next;
} while (skb != NULL);
bh_lock_sock(sk);
} while ((skb = sk->sk_backlog.head) != NULL);
/*
* Doing the zeroing here guarantee we can not loop forever
* while a wild producer attempts to flood us.
*/
sk->sk_backlog.len = 0;
}
/**
* sk_wait_data - wait for data to arrive at sk_receive_queue
* @sk: sock to wait on
* @timeo: for how long
*
* Now socket state including sk->sk_err is changed only under lock,
* hence we may omit checks after joining wait queue.
* We check receive queue before schedule() only as optimization;
* it is very likely that release_sock() added new data.
*/
int sk_wait_data(struct sock *sk, long *timeo)
{
int rc;
DEFINE_WAIT(wait);
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
rc = sk_wait_event(sk, timeo, !skb_queue_empty(&sk->sk_receive_queue));
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
finish_wait(sk_sleep(sk), &wait);
return rc;
}
EXPORT_SYMBOL(sk_wait_data);
/**
* __sk_mem_schedule - increase sk_forward_alloc and memory_allocated
* @sk: socket
* @size: memory size to allocate
* @kind: allocation type
*
* If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means
* rmem allocation. This function assumes that protocols which have
* memory_pressure use sk_wmem_queued as write buffer accounting.
*/
int __sk_mem_schedule(struct sock *sk, int size, int kind)
{
struct proto *prot = sk->sk_prot;
int amt = sk_mem_pages(size);
long allocated;
int parent_status = UNDER_LIMIT;
sk->sk_forward_alloc += amt * SK_MEM_QUANTUM;
allocated = sk_memory_allocated_add(sk, amt, &parent_status);
/* Under limit. */
if (parent_status == UNDER_LIMIT &&
allocated <= sk_prot_mem_limits(sk, 0)) {
sk_leave_memory_pressure(sk);
return 1;
}
/* Under pressure. (we or our parents) */
if ((parent_status > SOFT_LIMIT) ||
allocated > sk_prot_mem_limits(sk, 1))
sk_enter_memory_pressure(sk);
/* Over hard limit (we or our parents) */
if ((parent_status == OVER_LIMIT) ||
(allocated > sk_prot_mem_limits(sk, 2)))
goto suppress_allocation;
/* guarantee minimum buffer size under pressure */
if (kind == SK_MEM_RECV) {
if (atomic_read(&sk->sk_rmem_alloc) < prot->sysctl_rmem[0])
return 1;
} else { /* SK_MEM_SEND */
if (sk->sk_type == SOCK_STREAM) {
if (sk->sk_wmem_queued < prot->sysctl_wmem[0])
return 1;
} else if (atomic_read(&sk->sk_wmem_alloc) <
prot->sysctl_wmem[0])
return 1;
}
if (sk_has_memory_pressure(sk)) {
int alloc;
if (!sk_under_memory_pressure(sk))
return 1;
alloc = sk_sockets_allocated_read_positive(sk);
if (sk_prot_mem_limits(sk, 2) > alloc *
sk_mem_pages(sk->sk_wmem_queued +
atomic_read(&sk->sk_rmem_alloc) +
sk->sk_forward_alloc))
return 1;
}
suppress_allocation:
if (kind == SK_MEM_SEND && sk->sk_type == SOCK_STREAM) {
sk_stream_moderate_sndbuf(sk);
/* Fail only if socket is _under_ its sndbuf.
* In this case we cannot block, so that we have to fail.
*/
if (sk->sk_wmem_queued + size >= sk->sk_sndbuf)
return 1;
}
trace_sock_exceed_buf_limit(sk, prot, allocated);
/* Alas. Undo changes. */
sk->sk_forward_alloc -= amt * SK_MEM_QUANTUM;
sk_memory_allocated_sub(sk, amt);
return 0;
}
EXPORT_SYMBOL(__sk_mem_schedule);
/**
* __sk_reclaim - reclaim memory_allocated
* @sk: socket
*/
void __sk_mem_reclaim(struct sock *sk)
{
sk_memory_allocated_sub(sk,
sk->sk_forward_alloc >> SK_MEM_QUANTUM_SHIFT);
sk->sk_forward_alloc &= SK_MEM_QUANTUM - 1;
if (sk_under_memory_pressure(sk) &&
(sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)))
sk_leave_memory_pressure(sk);
}
EXPORT_SYMBOL(__sk_mem_reclaim);
/*
* Set of default routines for initialising struct proto_ops when
* the protocol does not support a particular function. In certain
* cases where it makes no sense for a protocol to have a "do nothing"
* function, some default processing is provided.
*/
int sock_no_bind(struct socket *sock, struct sockaddr *saddr, int len)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_bind);
int sock_no_connect(struct socket *sock, struct sockaddr *saddr,
int len, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_connect);
int sock_no_socketpair(struct socket *sock1, struct socket *sock2)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_socketpair);
int sock_no_accept(struct socket *sock, struct socket *newsock, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_accept);
int sock_no_getname(struct socket *sock, struct sockaddr *saddr,
int *len, int peer)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_getname);
unsigned int sock_no_poll(struct file *file, struct socket *sock, poll_table *pt)
{
return 0;
}
EXPORT_SYMBOL(sock_no_poll);
int sock_no_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_ioctl);
int sock_no_listen(struct socket *sock, int backlog)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_listen);
int sock_no_shutdown(struct socket *sock, int how)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_shutdown);
int sock_no_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_setsockopt);
int sock_no_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_getsockopt);
int sock_no_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t len)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_sendmsg);
int sock_no_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t len, int flags)
{
return -EOPNOTSUPP;
}
EXPORT_SYMBOL(sock_no_recvmsg);
int sock_no_mmap(struct file *file, struct socket *sock, struct vm_area_struct *vma)
{
/* Mirror missing mmap method error code */
return -ENODEV;
}
EXPORT_SYMBOL(sock_no_mmap);
ssize_t sock_no_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags)
{
ssize_t res;
struct msghdr msg = {.msg_flags = flags};
struct kvec iov;
char *kaddr = kmap(page);
iov.iov_base = kaddr + offset;
iov.iov_len = size;
res = kernel_sendmsg(sock, &msg, &iov, 1, size);
kunmap(page);
return res;
}
EXPORT_SYMBOL(sock_no_sendpage);
/*
* Default Socket Callbacks
*/
static void sock_def_wakeup(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_all(&wq->wait);
rcu_read_unlock();
}
static void sock_def_error_report(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_poll(&wq->wait, POLLERR);
sk_wake_async(sk, SOCK_WAKE_IO, POLL_ERR);
rcu_read_unlock();
}
static void sock_def_readable(struct sock *sk, int len)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLIN | POLLPRI |
POLLRDNORM | POLLRDBAND);
sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
rcu_read_unlock();
}
static void sock_def_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
/* Do not wake up a writer until he can make "significant"
* progress. --DaveM
*/
if ((atomic_read(&sk->sk_wmem_alloc) << 1) <= sk->sk_sndbuf) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
POLLWRNORM | POLLWRBAND);
/* Should agree with poll, otherwise some programs break */
if (sock_writeable(sk))
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
static void sock_def_destruct(struct sock *sk)
{
kfree(sk->sk_protinfo);
}
void sk_send_sigurg(struct sock *sk)
{
if (sk->sk_socket && sk->sk_socket->file)
if (send_sigurg(&sk->sk_socket->file->f_owner))
sk_wake_async(sk, SOCK_WAKE_URG, POLL_PRI);
}
EXPORT_SYMBOL(sk_send_sigurg);
void sk_reset_timer(struct sock *sk, struct timer_list* timer,
unsigned long expires)
{
if (!mod_timer(timer, expires))
sock_hold(sk);
}
EXPORT_SYMBOL(sk_reset_timer);
void sk_stop_timer(struct sock *sk, struct timer_list* timer)
{
if (timer_pending(timer) && del_timer(timer))
__sock_put(sk);
}
EXPORT_SYMBOL(sk_stop_timer);
void sock_init_data(struct socket *sock, struct sock *sk)
{
skb_queue_head_init(&sk->sk_receive_queue);
skb_queue_head_init(&sk->sk_write_queue);
skb_queue_head_init(&sk->sk_error_queue);
#ifdef CONFIG_NET_DMA
skb_queue_head_init(&sk->sk_async_wait_queue);
#endif
sk->sk_send_head = NULL;
init_timer(&sk->sk_timer);
sk->sk_allocation = GFP_KERNEL;
sk->sk_rcvbuf = sysctl_rmem_default;
sk->sk_sndbuf = sysctl_wmem_default;
sk->sk_state = TCP_CLOSE;
sk_set_socket(sk, sock);
sock_set_flag(sk, SOCK_ZAPPED);
if (sock) {
sk->sk_type = sock->type;
sk->sk_wq = sock->wq;
sock->sk = sk;
} else
sk->sk_wq = NULL;
spin_lock_init(&sk->sk_dst_lock);
rwlock_init(&sk->sk_callback_lock);
lockdep_set_class_and_name(&sk->sk_callback_lock,
af_callback_keys + sk->sk_family,
af_family_clock_key_strings[sk->sk_family]);
sk->sk_state_change = sock_def_wakeup;
sk->sk_data_ready = sock_def_readable;
sk->sk_write_space = sock_def_write_space;
sk->sk_error_report = sock_def_error_report;
sk->sk_destruct = sock_def_destruct;
sk->sk_sndmsg_page = NULL;
sk->sk_sndmsg_off = 0;
sk->sk_peek_off = -1;
sk->sk_peer_pid = NULL;
sk->sk_peer_cred = NULL;
sk->sk_write_pending = 0;
sk->sk_rcvlowat = 1;
sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
sk->sk_stamp = ktime_set(-1L, 0);
/*
* Before updating sk_refcnt, we must commit prior changes to memory
* (Documentation/RCU/rculist_nulls.txt for details)
*/
smp_wmb();
atomic_set(&sk->sk_refcnt, 1);
atomic_set(&sk->sk_drops, 0);
}
EXPORT_SYMBOL(sock_init_data);
void lock_sock_nested(struct sock *sk, int subclass)
{
might_sleep();
spin_lock_bh(&sk->sk_lock.slock);
if (sk->sk_lock.owned)
__lock_sock(sk);
sk->sk_lock.owned = 1;
spin_unlock(&sk->sk_lock.slock);
/*
* The sk_lock has mutex_lock() semantics here:
*/
mutex_acquire(&sk->sk_lock.dep_map, subclass, 0, _RET_IP_);
local_bh_enable();
}
EXPORT_SYMBOL(lock_sock_nested);
void release_sock(struct sock *sk)
{
/*
* The sk_lock has mutex_unlock() semantics:
*/
mutex_release(&sk->sk_lock.dep_map, 1, _RET_IP_);
spin_lock_bh(&sk->sk_lock.slock);
if (sk->sk_backlog.tail)
__release_sock(sk);
sk->sk_lock.owned = 0;
if (waitqueue_active(&sk->sk_lock.wq))
wake_up(&sk->sk_lock.wq);
spin_unlock_bh(&sk->sk_lock.slock);
}
EXPORT_SYMBOL(release_sock);
/**
* lock_sock_fast - fast version of lock_sock
* @sk: socket
*
* This version should be used for very small section, where process wont block
* return false if fast path is taken
* sk_lock.slock locked, owned = 0, BH disabled
* return true if slow path is taken
* sk_lock.slock unlocked, owned = 1, BH enabled
*/
bool lock_sock_fast(struct sock *sk)
{
might_sleep();
spin_lock_bh(&sk->sk_lock.slock);
if (!sk->sk_lock.owned)
/*
* Note : We must disable BH
*/
return false;
__lock_sock(sk);
sk->sk_lock.owned = 1;
spin_unlock(&sk->sk_lock.slock);
/*
* The sk_lock has mutex_lock() semantics here:
*/
mutex_acquire(&sk->sk_lock.dep_map, 0, 0, _RET_IP_);
local_bh_enable();
return true;
}
EXPORT_SYMBOL(lock_sock_fast);
int sock_get_timestamp(struct sock *sk, struct timeval __user *userstamp)
{
struct timeval tv;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
tv = ktime_to_timeval(sk->sk_stamp);
if (tv.tv_sec == -1)
return -ENOENT;
if (tv.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
tv = ktime_to_timeval(sk->sk_stamp);
}
return copy_to_user(userstamp, &tv, sizeof(tv)) ? -EFAULT : 0;
}
EXPORT_SYMBOL(sock_get_timestamp);
int sock_get_timestampns(struct sock *sk, struct timespec __user *userstamp)
{
struct timespec ts;
if (!sock_flag(sk, SOCK_TIMESTAMP))
sock_enable_timestamp(sk, SOCK_TIMESTAMP);
ts = ktime_to_timespec(sk->sk_stamp);
if (ts.tv_sec == -1)
return -ENOENT;
if (ts.tv_sec == 0) {
sk->sk_stamp = ktime_get_real();
ts = ktime_to_timespec(sk->sk_stamp);
}
return copy_to_user(userstamp, &ts, sizeof(ts)) ? -EFAULT : 0;
}
EXPORT_SYMBOL(sock_get_timestampns);
void sock_enable_timestamp(struct sock *sk, int flag)
{
if (!sock_flag(sk, flag)) {
unsigned long previous_flags = sk->sk_flags;
sock_set_flag(sk, flag);
/*
* we just set one of the two flags which require net
* time stamping, but time stamping might have been on
* already because of the other one
*/
if (!(previous_flags & SK_FLAGS_TIMESTAMP))
net_enable_timestamp();
}
}
/*
* Get a socket option on an socket.
*
* FIX: POSIX 1003.1g is very ambiguous here. It states that
* asynchronous errors should be reported by getsockopt. We assume
* this means if you specify SO_ERROR (otherwise whats the point of it).
*/
int sock_common_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(sock_common_getsockopt);
#ifdef CONFIG_COMPAT
int compat_sock_common_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
if (sk->sk_prot->compat_getsockopt != NULL)
return sk->sk_prot->compat_getsockopt(sk, level, optname,
optval, optlen);
return sk->sk_prot->getsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_sock_common_getsockopt);
#endif
int sock_common_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
int addr_len = 0;
int err;
err = sk->sk_prot->recvmsg(iocb, sk, msg, size, flags & MSG_DONTWAIT,
flags & ~MSG_DONTWAIT, &addr_len);
if (err >= 0)
msg->msg_namelen = addr_len;
return err;
}
EXPORT_SYMBOL(sock_common_recvmsg);
/*
* Set socket options on an inet socket.
*/
int sock_common_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(sock_common_setsockopt);
#ifdef CONFIG_COMPAT
int compat_sock_common_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
if (sk->sk_prot->compat_setsockopt != NULL)
return sk->sk_prot->compat_setsockopt(sk, level, optname,
optval, optlen);
return sk->sk_prot->setsockopt(sk, level, optname, optval, optlen);
}
EXPORT_SYMBOL(compat_sock_common_setsockopt);
#endif
void sk_common_release(struct sock *sk)
{
if (sk->sk_prot->destroy)
sk->sk_prot->destroy(sk);
/*
* Observation: when sock_common_release is called, processes have
* no access to socket. But net still has.
* Step one, detach it from networking:
*
* A. Remove from hash tables.
*/
sk->sk_prot->unhash(sk);
/*
* In this point socket cannot receive new packets, but it is possible
* that some packets are in flight because some CPU runs receiver and
* did hash table lookup before we unhashed socket. They will achieve
* receive queue and will be purged by socket destructor.
*
* Also we still have packets pending on receive queue and probably,
* our own packets waiting in device queues. sock_destroy will drain
* receive queue, but transmitted packets will delay socket destruction
* until the last reference will be released.
*/
sock_orphan(sk);
xfrm_sk_free_policy(sk);
sk_refcnt_debug_release(sk);
sock_put(sk);
}
EXPORT_SYMBOL(sk_common_release);
#ifdef CONFIG_PROC_FS
#define PROTO_INUSE_NR 64 /* should be enough for the first time */
struct prot_inuse {
int val[PROTO_INUSE_NR];
};
static DECLARE_BITMAP(proto_inuse_idx, PROTO_INUSE_NR);
#ifdef CONFIG_NET_NS
void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
{
__this_cpu_add(net->core.inuse->val[prot->inuse_idx], val);
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
int sock_prot_inuse_get(struct net *net, struct proto *prot)
{
int cpu, idx = prot->inuse_idx;
int res = 0;
for_each_possible_cpu(cpu)
res += per_cpu_ptr(net->core.inuse, cpu)->val[idx];
return res >= 0 ? res : 0;
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
static int __net_init sock_inuse_init_net(struct net *net)
{
net->core.inuse = alloc_percpu(struct prot_inuse);
return net->core.inuse ? 0 : -ENOMEM;
}
static void __net_exit sock_inuse_exit_net(struct net *net)
{
free_percpu(net->core.inuse);
}
static struct pernet_operations net_inuse_ops = {
.init = sock_inuse_init_net,
.exit = sock_inuse_exit_net,
};
static __init int net_inuse_init(void)
{
if (register_pernet_subsys(&net_inuse_ops))
panic("Cannot initialize net inuse counters");
return 0;
}
core_initcall(net_inuse_init);
#else
static DEFINE_PER_CPU(struct prot_inuse, prot_inuse);
void sock_prot_inuse_add(struct net *net, struct proto *prot, int val)
{
__this_cpu_add(prot_inuse.val[prot->inuse_idx], val);
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_add);
int sock_prot_inuse_get(struct net *net, struct proto *prot)
{
int cpu, idx = prot->inuse_idx;
int res = 0;
for_each_possible_cpu(cpu)
res += per_cpu(prot_inuse, cpu).val[idx];
return res >= 0 ? res : 0;
}
EXPORT_SYMBOL_GPL(sock_prot_inuse_get);
#endif
static void assign_proto_idx(struct proto *prot)
{
prot->inuse_idx = find_first_zero_bit(proto_inuse_idx, PROTO_INUSE_NR);
if (unlikely(prot->inuse_idx == PROTO_INUSE_NR - 1)) {
pr_err("PROTO_INUSE_NR exhausted\n");
return;
}
set_bit(prot->inuse_idx, proto_inuse_idx);
}
static void release_proto_idx(struct proto *prot)
{
if (prot->inuse_idx != PROTO_INUSE_NR - 1)
clear_bit(prot->inuse_idx, proto_inuse_idx);
}
#else
static inline void assign_proto_idx(struct proto *prot)
{
}
static inline void release_proto_idx(struct proto *prot)
{
}
#endif
int proto_register(struct proto *prot, int alloc_slab)
{
if (alloc_slab) {
prot->slab = kmem_cache_create(prot->name, prot->obj_size, 0,
SLAB_HWCACHE_ALIGN | prot->slab_flags,
NULL);
if (prot->slab == NULL) {
pr_crit("%s: Can't create sock SLAB cache!\n",
prot->name);
goto out;
}
if (prot->rsk_prot != NULL) {
prot->rsk_prot->slab_name = kasprintf(GFP_KERNEL, "request_sock_%s", prot->name);
if (prot->rsk_prot->slab_name == NULL)
goto out_free_sock_slab;
prot->rsk_prot->slab = kmem_cache_create(prot->rsk_prot->slab_name,
prot->rsk_prot->obj_size, 0,
SLAB_HWCACHE_ALIGN, NULL);
if (prot->rsk_prot->slab == NULL) {
pr_crit("%s: Can't create request sock SLAB cache!\n",
prot->name);
goto out_free_request_sock_slab_name;
}
}
if (prot->twsk_prot != NULL) {
prot->twsk_prot->twsk_slab_name = kasprintf(GFP_KERNEL, "tw_sock_%s", prot->name);
if (prot->twsk_prot->twsk_slab_name == NULL)
goto out_free_request_sock_slab;
prot->twsk_prot->twsk_slab =
kmem_cache_create(prot->twsk_prot->twsk_slab_name,
prot->twsk_prot->twsk_obj_size,
0,
SLAB_HWCACHE_ALIGN |
prot->slab_flags,
NULL);
if (prot->twsk_prot->twsk_slab == NULL)
goto out_free_timewait_sock_slab_name;
}
}
mutex_lock(&proto_list_mutex);
list_add(&prot->node, &proto_list);
assign_proto_idx(prot);
mutex_unlock(&proto_list_mutex);
return 0;
out_free_timewait_sock_slab_name:
kfree(prot->twsk_prot->twsk_slab_name);
out_free_request_sock_slab:
if (prot->rsk_prot && prot->rsk_prot->slab) {
kmem_cache_destroy(prot->rsk_prot->slab);
prot->rsk_prot->slab = NULL;
}
out_free_request_sock_slab_name:
if (prot->rsk_prot)
kfree(prot->rsk_prot->slab_name);
out_free_sock_slab:
kmem_cache_destroy(prot->slab);
prot->slab = NULL;
out:
return -ENOBUFS;
}
EXPORT_SYMBOL(proto_register);
void proto_unregister(struct proto *prot)
{
mutex_lock(&proto_list_mutex);
release_proto_idx(prot);
list_del(&prot->node);
mutex_unlock(&proto_list_mutex);
if (prot->slab != NULL) {
kmem_cache_destroy(prot->slab);
prot->slab = NULL;
}
if (prot->rsk_prot != NULL && prot->rsk_prot->slab != NULL) {
kmem_cache_destroy(prot->rsk_prot->slab);
kfree(prot->rsk_prot->slab_name);
prot->rsk_prot->slab = NULL;
}
if (prot->twsk_prot != NULL && prot->twsk_prot->twsk_slab != NULL) {
kmem_cache_destroy(prot->twsk_prot->twsk_slab);
kfree(prot->twsk_prot->twsk_slab_name);
prot->twsk_prot->twsk_slab = NULL;
}
}
EXPORT_SYMBOL(proto_unregister);
#ifdef CONFIG_PROC_FS
static void *proto_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(proto_list_mutex)
{
mutex_lock(&proto_list_mutex);
return seq_list_start_head(&proto_list, *pos);
}
static void *proto_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_list_next(v, &proto_list, pos);
}
static void proto_seq_stop(struct seq_file *seq, void *v)
__releases(proto_list_mutex)
{
mutex_unlock(&proto_list_mutex);
}
static char proto_method_implemented(const void *method)
{
return method == NULL ? 'n' : 'y';
}
static long sock_prot_memory_allocated(struct proto *proto)
{
return proto->memory_allocated != NULL ? proto_memory_allocated(proto) : -1L;
}
static char *sock_prot_memory_pressure(struct proto *proto)
{
return proto->memory_pressure != NULL ?
proto_memory_pressure(proto) ? "yes" : "no" : "NI";
}
static void proto_seq_printf(struct seq_file *seq, struct proto *proto)
{
seq_printf(seq, "%-9s %4u %6d %6ld %-3s %6u %-3s %-10s "
"%2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c %2c\n",
proto->name,
proto->obj_size,
sock_prot_inuse_get(seq_file_net(seq), proto),
sock_prot_memory_allocated(proto),
sock_prot_memory_pressure(proto),
proto->max_header,
proto->slab == NULL ? "no" : "yes",
module_name(proto->owner),
proto_method_implemented(proto->close),
proto_method_implemented(proto->connect),
proto_method_implemented(proto->disconnect),
proto_method_implemented(proto->accept),
proto_method_implemented(proto->ioctl),
proto_method_implemented(proto->init),
proto_method_implemented(proto->destroy),
proto_method_implemented(proto->shutdown),
proto_method_implemented(proto->setsockopt),
proto_method_implemented(proto->getsockopt),
proto_method_implemented(proto->sendmsg),
proto_method_implemented(proto->recvmsg),
proto_method_implemented(proto->sendpage),
proto_method_implemented(proto->bind),
proto_method_implemented(proto->backlog_rcv),
proto_method_implemented(proto->hash),
proto_method_implemented(proto->unhash),
proto_method_implemented(proto->get_port),
proto_method_implemented(proto->enter_memory_pressure));
}
static int proto_seq_show(struct seq_file *seq, void *v)
{
if (v == &proto_list)
seq_printf(seq, "%-9s %-4s %-8s %-6s %-5s %-7s %-4s %-10s %s",
"protocol",
"size",
"sockets",
"memory",
"press",
"maxhdr",
"slab",
"module",
"cl co di ac io in de sh ss gs se re sp bi br ha uh gp em\n");
else
proto_seq_printf(seq, list_entry(v, struct proto, node));
return 0;
}
static const struct seq_operations proto_seq_ops = {
.start = proto_seq_start,
.next = proto_seq_next,
.stop = proto_seq_stop,
.show = proto_seq_show,
};
static int proto_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &proto_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations proto_seq_fops = {
.owner = THIS_MODULE,
.open = proto_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static __net_init int proto_init_net(struct net *net)
{
if (!proc_net_fops_create(net, "protocols", S_IRUGO, &proto_seq_fops))
return -ENOMEM;
return 0;
}
static __net_exit void proto_exit_net(struct net *net)
{
proc_net_remove(net, "protocols");
}
static __net_initdata struct pernet_operations proto_net_ops = {
.init = proto_init_net,
.exit = proto_exit_net,
};
static int __init proto_init(void)
{
return register_pernet_subsys(&proto_net_ops);
}
subsys_initcall(proto_init);
#endif /* PROC_FS */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3641_0 |
crossvul-cpp_data_bad_5718_0 | #include <linux/err.h>
#include <linux/igmp.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/rculist.h>
#include <linux/skbuff.h>
#include <linux/if_ether.h>
#include <net/ip.h>
#include <net/netlink.h>
#if IS_ENABLED(CONFIG_IPV6)
#include <net/ipv6.h>
#endif
#include "br_private.h"
static int br_rports_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_port *p;
struct nlattr *nest;
if (!br->multicast_router || hlist_empty(&br->router_list))
return 0;
nest = nla_nest_start(skb, MDBA_ROUTER);
if (nest == NULL)
return -EMSGSIZE;
hlist_for_each_entry_rcu(p, &br->router_list, rlist) {
if (p && nla_put_u32(skb, MDBA_ROUTER_PORT, p->dev->ifindex))
goto fail;
}
nla_nest_end(skb, nest);
return 0;
fail:
nla_nest_cancel(skb, nest);
return -EMSGSIZE;
}
static int br_mdb_fill_info(struct sk_buff *skb, struct netlink_callback *cb,
struct net_device *dev)
{
struct net_bridge *br = netdev_priv(dev);
struct net_bridge_mdb_htable *mdb;
struct nlattr *nest, *nest2;
int i, err = 0;
int idx = 0, s_idx = cb->args[1];
if (br->multicast_disabled)
return 0;
mdb = rcu_dereference(br->mdb);
if (!mdb)
return 0;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
return -EMSGSIZE;
for (i = 0; i < mdb->max; i++) {
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p, **pp;
struct net_bridge_port *port;
hlist_for_each_entry_rcu(mp, &mdb->mhash[i], hlist[mdb->ver]) {
if (idx < s_idx)
goto skip;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL) {
err = -EMSGSIZE;
goto out;
}
for (pp = &mp->ports;
(p = rcu_dereference(*pp)) != NULL;
pp = &p->next) {
port = p->port;
if (port) {
struct br_mdb_entry e;
memset(&e, 0, sizeof(e));
e.ifindex = port->dev->ifindex;
e.state = p->state;
if (p->addr.proto == htons(ETH_P_IP))
e.addr.u.ip4 = p->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
if (p->addr.proto == htons(ETH_P_IPV6))
e.addr.u.ip6 = p->addr.u.ip6;
#endif
e.addr.proto = p->addr.proto;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(e), &e)) {
nla_nest_cancel(skb, nest2);
err = -EMSGSIZE;
goto out;
}
}
}
nla_nest_end(skb, nest2);
skip:
idx++;
}
}
out:
cb->args[1] = idx;
nla_nest_end(skb, nest);
return err;
}
static int br_mdb_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net_device *dev;
struct net *net = sock_net(skb->sk);
struct nlmsghdr *nlh = NULL;
int idx = 0, s_idx;
s_idx = cb->args[0];
rcu_read_lock();
/* In theory this could be wrapped to 0... */
cb->seq = net->dev_base_seq + br_mdb_rehash_seq;
for_each_netdev_rcu(net, dev) {
if (dev->priv_flags & IFF_EBRIDGE) {
struct br_port_msg *bpm;
if (idx < s_idx)
goto skip;
nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, RTM_GETMDB,
sizeof(*bpm), NLM_F_MULTI);
if (nlh == NULL)
break;
bpm = nlmsg_data(nlh);
memset(bpm, 0, sizeof(*bpm));
bpm->ifindex = dev->ifindex;
if (br_mdb_fill_info(skb, cb, dev) < 0)
goto out;
if (br_rports_fill_info(skb, cb, dev) < 0)
goto out;
cb->args[1] = 0;
nlmsg_end(skb, nlh);
skip:
idx++;
}
}
out:
if (nlh)
nlmsg_end(skb, nlh);
rcu_read_unlock();
cb->args[0] = idx;
return skb->len;
}
static int nlmsg_populate_mdb_fill(struct sk_buff *skb,
struct net_device *dev,
struct br_mdb_entry *entry, u32 pid,
u32 seq, int type, unsigned int flags)
{
struct nlmsghdr *nlh;
struct br_port_msg *bpm;
struct nlattr *nest, *nest2;
nlh = nlmsg_put(skb, pid, seq, type, sizeof(*bpm), NLM_F_MULTI);
if (!nlh)
return -EMSGSIZE;
bpm = nlmsg_data(nlh);
memset(bpm, 0, sizeof(*bpm));
bpm->family = AF_BRIDGE;
bpm->ifindex = dev->ifindex;
nest = nla_nest_start(skb, MDBA_MDB);
if (nest == NULL)
goto cancel;
nest2 = nla_nest_start(skb, MDBA_MDB_ENTRY);
if (nest2 == NULL)
goto end;
if (nla_put(skb, MDBA_MDB_ENTRY_INFO, sizeof(*entry), entry))
goto end;
nla_nest_end(skb, nest2);
nla_nest_end(skb, nest);
return nlmsg_end(skb, nlh);
end:
nla_nest_end(skb, nest);
cancel:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
static inline size_t rtnl_mdb_nlmsg_size(void)
{
return NLMSG_ALIGN(sizeof(struct br_port_msg))
+ nla_total_size(sizeof(struct br_mdb_entry));
}
static void __br_mdb_notify(struct net_device *dev, struct br_mdb_entry *entry,
int type)
{
struct net *net = dev_net(dev);
struct sk_buff *skb;
int err = -ENOBUFS;
skb = nlmsg_new(rtnl_mdb_nlmsg_size(), GFP_ATOMIC);
if (!skb)
goto errout;
err = nlmsg_populate_mdb_fill(skb, dev, entry, 0, 0, type, NTF_SELF);
if (err < 0) {
kfree_skb(skb);
goto errout;
}
rtnl_notify(skb, net, 0, RTNLGRP_MDB, NULL, GFP_ATOMIC);
return;
errout:
rtnl_set_sk_err(net, RTNLGRP_MDB, err);
}
void br_mdb_notify(struct net_device *dev, struct net_bridge_port *port,
struct br_ip *group, int type)
{
struct br_mdb_entry entry;
memset(&entry, 0, sizeof(entry));
entry.ifindex = port->dev->ifindex;
entry.addr.proto = group->proto;
entry.addr.u.ip4 = group->u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
entry.addr.u.ip6 = group->u.ip6;
#endif
__br_mdb_notify(dev, &entry, type);
}
static bool is_valid_mdb_entry(struct br_mdb_entry *entry)
{
if (entry->ifindex == 0)
return false;
if (entry->addr.proto == htons(ETH_P_IP)) {
if (!ipv4_is_multicast(entry->addr.u.ip4))
return false;
if (ipv4_is_local_multicast(entry->addr.u.ip4))
return false;
#if IS_ENABLED(CONFIG_IPV6)
} else if (entry->addr.proto == htons(ETH_P_IPV6)) {
if (!ipv6_is_transient_multicast(&entry->addr.u.ip6))
return false;
#endif
} else
return false;
if (entry->state != MDB_PERMANENT && entry->state != MDB_TEMPORARY)
return false;
return true;
}
static int br_mdb_parse(struct sk_buff *skb, struct nlmsghdr *nlh,
struct net_device **pdev, struct br_mdb_entry **pentry)
{
struct net *net = sock_net(skb->sk);
struct br_mdb_entry *entry;
struct br_port_msg *bpm;
struct nlattr *tb[MDBA_SET_ENTRY_MAX+1];
struct net_device *dev;
int err;
err = nlmsg_parse(nlh, sizeof(*bpm), tb, MDBA_SET_ENTRY, NULL);
if (err < 0)
return err;
bpm = nlmsg_data(nlh);
if (bpm->ifindex == 0) {
pr_info("PF_BRIDGE: br_mdb_parse() with invalid ifindex\n");
return -EINVAL;
}
dev = __dev_get_by_index(net, bpm->ifindex);
if (dev == NULL) {
pr_info("PF_BRIDGE: br_mdb_parse() with unknown ifindex\n");
return -ENODEV;
}
if (!(dev->priv_flags & IFF_EBRIDGE)) {
pr_info("PF_BRIDGE: br_mdb_parse() with non-bridge\n");
return -EOPNOTSUPP;
}
*pdev = dev;
if (!tb[MDBA_SET_ENTRY] ||
nla_len(tb[MDBA_SET_ENTRY]) != sizeof(struct br_mdb_entry)) {
pr_info("PF_BRIDGE: br_mdb_parse() with invalid attr\n");
return -EINVAL;
}
entry = nla_data(tb[MDBA_SET_ENTRY]);
if (!is_valid_mdb_entry(entry)) {
pr_info("PF_BRIDGE: br_mdb_parse() with invalid entry\n");
return -EINVAL;
}
*pentry = entry;
return 0;
}
static int br_mdb_add_group(struct net_bridge *br, struct net_bridge_port *port,
struct br_ip *group, unsigned char state)
{
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
struct net_bridge_mdb_htable *mdb;
int err;
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, group);
if (!mp) {
mp = br_multicast_new_group(br, port, group);
err = PTR_ERR(mp);
if (IS_ERR(mp))
return err;
}
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (p->port == port)
return -EEXIST;
if ((unsigned long)p->port < (unsigned long)port)
break;
}
p = br_multicast_new_port_group(port, group, *pp, state);
if (unlikely(!p))
return -ENOMEM;
rcu_assign_pointer(*pp, p);
br_mdb_notify(br->dev, port, group, RTM_NEWMDB);
return 0;
}
static int __br_mdb_add(struct net *net, struct net_bridge *br,
struct br_mdb_entry *entry)
{
struct br_ip ip;
struct net_device *dev;
struct net_bridge_port *p;
int ret;
if (!netif_running(br->dev) || br->multicast_disabled)
return -EINVAL;
dev = __dev_get_by_index(net, entry->ifindex);
if (!dev)
return -ENODEV;
p = br_port_get_rtnl(dev);
if (!p || p->br != br || p->state == BR_STATE_DISABLED)
return -EINVAL;
ip.proto = entry->addr.proto;
if (ip.proto == htons(ETH_P_IP))
ip.u.ip4 = entry->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
else
ip.u.ip6 = entry->addr.u.ip6;
#endif
spin_lock_bh(&br->multicast_lock);
ret = br_mdb_add_group(br, p, &ip, entry->state);
spin_unlock_bh(&br->multicast_lock);
return ret;
}
static int br_mdb_add(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(skb->sk);
struct br_mdb_entry *entry;
struct net_device *dev;
struct net_bridge *br;
int err;
err = br_mdb_parse(skb, nlh, &dev, &entry);
if (err < 0)
return err;
br = netdev_priv(dev);
err = __br_mdb_add(net, br, entry);
if (!err)
__br_mdb_notify(dev, entry, RTM_NEWMDB);
return err;
}
static int __br_mdb_del(struct net_bridge *br, struct br_mdb_entry *entry)
{
struct net_bridge_mdb_htable *mdb;
struct net_bridge_mdb_entry *mp;
struct net_bridge_port_group *p;
struct net_bridge_port_group __rcu **pp;
struct br_ip ip;
int err = -EINVAL;
if (!netif_running(br->dev) || br->multicast_disabled)
return -EINVAL;
if (timer_pending(&br->multicast_querier_timer))
return -EBUSY;
ip.proto = entry->addr.proto;
if (ip.proto == htons(ETH_P_IP))
ip.u.ip4 = entry->addr.u.ip4;
#if IS_ENABLED(CONFIG_IPV6)
else
ip.u.ip6 = entry->addr.u.ip6;
#endif
spin_lock_bh(&br->multicast_lock);
mdb = mlock_dereference(br->mdb, br);
mp = br_mdb_ip_get(mdb, &ip);
if (!mp)
goto unlock;
for (pp = &mp->ports;
(p = mlock_dereference(*pp, br)) != NULL;
pp = &p->next) {
if (!p->port || p->port->dev->ifindex != entry->ifindex)
continue;
if (p->port->state == BR_STATE_DISABLED)
goto unlock;
rcu_assign_pointer(*pp, p->next);
hlist_del_init(&p->mglist);
del_timer(&p->timer);
call_rcu_bh(&p->rcu, br_multicast_free_pg);
err = 0;
if (!mp->ports && !mp->mglist &&
netif_running(br->dev))
mod_timer(&mp->timer, jiffies);
break;
}
unlock:
spin_unlock_bh(&br->multicast_lock);
return err;
}
static int br_mdb_del(struct sk_buff *skb, struct nlmsghdr *nlh)
{
struct net_device *dev;
struct br_mdb_entry *entry;
struct net_bridge *br;
int err;
err = br_mdb_parse(skb, nlh, &dev, &entry);
if (err < 0)
return err;
br = netdev_priv(dev);
err = __br_mdb_del(br, entry);
if (!err)
__br_mdb_notify(dev, entry, RTM_DELMDB);
return err;
}
void br_mdb_init(void)
{
rtnl_register(PF_BRIDGE, RTM_GETMDB, NULL, br_mdb_dump, NULL);
rtnl_register(PF_BRIDGE, RTM_NEWMDB, br_mdb_add, NULL, NULL);
rtnl_register(PF_BRIDGE, RTM_DELMDB, br_mdb_del, NULL, NULL);
}
void br_mdb_uninit(void)
{
rtnl_unregister(PF_BRIDGE, RTM_GETMDB);
rtnl_unregister(PF_BRIDGE, RTM_NEWMDB);
rtnl_unregister(PF_BRIDGE, RTM_DELMDB);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5718_0 |
crossvul-cpp_data_good_132_0 | /*
* Copyright(C) 2015 Linaro Limited. All rights reserved.
* Author: Mathieu Poirier <mathieu.poirier@linaro.org>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/coresight.h>
#include <linux/coresight-pmu.h>
#include <linux/cpumask.h>
#include <linux/device.h>
#include <linux/list.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/perf_event.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/workqueue.h>
#include "coresight-etm-perf.h"
#include "coresight-priv.h"
static struct pmu etm_pmu;
static bool etm_perf_up;
/**
* struct etm_event_data - Coresight specifics associated to an event
* @work: Handle to free allocated memory outside IRQ context.
* @mask: Hold the CPU(s) this event was set for.
* @snk_config: The sink configuration.
* @path: An array of path, each slot for one CPU.
*/
struct etm_event_data {
struct work_struct work;
cpumask_t mask;
void *snk_config;
struct list_head **path;
};
static DEFINE_PER_CPU(struct perf_output_handle, ctx_handle);
static DEFINE_PER_CPU(struct coresight_device *, csdev_src);
/* ETMv3.5/PTM's ETMCR is 'config' */
PMU_FORMAT_ATTR(cycacc, "config:" __stringify(ETM_OPT_CYCACC));
PMU_FORMAT_ATTR(timestamp, "config:" __stringify(ETM_OPT_TS));
static struct attribute *etm_config_formats_attr[] = {
&format_attr_cycacc.attr,
&format_attr_timestamp.attr,
NULL,
};
static struct attribute_group etm_pmu_format_group = {
.name = "format",
.attrs = etm_config_formats_attr,
};
static const struct attribute_group *etm_pmu_attr_groups[] = {
&etm_pmu_format_group,
NULL,
};
static void etm_event_read(struct perf_event *event) {}
static int etm_addr_filters_alloc(struct perf_event *event)
{
struct etm_filters *filters;
int node = event->cpu == -1 ? -1 : cpu_to_node(event->cpu);
filters = kzalloc_node(sizeof(struct etm_filters), GFP_KERNEL, node);
if (!filters)
return -ENOMEM;
if (event->parent)
memcpy(filters, event->parent->hw.addr_filters,
sizeof(*filters));
event->hw.addr_filters = filters;
return 0;
}
static void etm_event_destroy(struct perf_event *event)
{
kfree(event->hw.addr_filters);
event->hw.addr_filters = NULL;
}
static int etm_event_init(struct perf_event *event)
{
int ret = 0;
if (event->attr.type != etm_pmu.type) {
ret = -ENOENT;
goto out;
}
ret = etm_addr_filters_alloc(event);
if (ret)
goto out;
event->destroy = etm_event_destroy;
out:
return ret;
}
static void free_event_data(struct work_struct *work)
{
int cpu;
cpumask_t *mask;
struct etm_event_data *event_data;
struct coresight_device *sink;
event_data = container_of(work, struct etm_event_data, work);
mask = &event_data->mask;
/*
* First deal with the sink configuration. See comment in
* etm_setup_aux() about why we take the first available path.
*/
if (event_data->snk_config) {
cpu = cpumask_first(mask);
sink = coresight_get_sink(event_data->path[cpu]);
if (sink_ops(sink)->free_buffer)
sink_ops(sink)->free_buffer(event_data->snk_config);
}
for_each_cpu(cpu, mask) {
if (!(IS_ERR_OR_NULL(event_data->path[cpu])))
coresight_release_path(event_data->path[cpu]);
}
kfree(event_data->path);
kfree(event_data);
}
static void *alloc_event_data(int cpu)
{
int size;
cpumask_t *mask;
struct etm_event_data *event_data;
/* First get memory for the session's data */
event_data = kzalloc(sizeof(struct etm_event_data), GFP_KERNEL);
if (!event_data)
return NULL;
/* Make sure nothing disappears under us */
get_online_cpus();
size = num_online_cpus();
mask = &event_data->mask;
if (cpu != -1)
cpumask_set_cpu(cpu, mask);
else
cpumask_copy(mask, cpu_online_mask);
put_online_cpus();
/*
* Each CPU has a single path between source and destination. As such
* allocate an array using CPU numbers as indexes. That way a path
* for any CPU can easily be accessed at any given time. We proceed
* the same way for sessions involving a single CPU. The cost of
* unused memory when dealing with single CPU trace scenarios is small
* compared to the cost of searching through an optimized array.
*/
event_data->path = kcalloc(size,
sizeof(struct list_head *), GFP_KERNEL);
if (!event_data->path) {
kfree(event_data);
return NULL;
}
return event_data;
}
static void etm_free_aux(void *data)
{
struct etm_event_data *event_data = data;
schedule_work(&event_data->work);
}
static void *etm_setup_aux(int event_cpu, void **pages,
int nr_pages, bool overwrite)
{
int cpu;
cpumask_t *mask;
struct coresight_device *sink;
struct etm_event_data *event_data = NULL;
event_data = alloc_event_data(event_cpu);
if (!event_data)
return NULL;
/*
* In theory nothing prevent tracers in a trace session from being
* associated with different sinks, nor having a sink per tracer. But
* until we have HW with this kind of topology we need to assume tracers
* in a trace session are using the same sink. Therefore go through
* the coresight bus and pick the first enabled sink.
*
* When operated from sysFS users are responsible to enable the sink
* while from perf, the perf tools will do it based on the choice made
* on the cmd line. As such the "enable_sink" flag in sysFS is reset.
*/
sink = coresight_get_enabled_sink(true);
if (!sink)
goto err;
INIT_WORK(&event_data->work, free_event_data);
mask = &event_data->mask;
/* Setup the path for each CPU in a trace session */
for_each_cpu(cpu, mask) {
struct coresight_device *csdev;
csdev = per_cpu(csdev_src, cpu);
if (!csdev)
goto err;
/*
* Building a path doesn't enable it, it simply builds a
* list of devices from source to sink that can be
* referenced later when the path is actually needed.
*/
event_data->path[cpu] = coresight_build_path(csdev, sink);
if (IS_ERR(event_data->path[cpu]))
goto err;
}
if (!sink_ops(sink)->alloc_buffer)
goto err;
cpu = cpumask_first(mask);
/* Get the AUX specific data from the sink buffer */
event_data->snk_config =
sink_ops(sink)->alloc_buffer(sink, cpu, pages,
nr_pages, overwrite);
if (!event_data->snk_config)
goto err;
out:
return event_data;
err:
etm_free_aux(event_data);
event_data = NULL;
goto out;
}
static void etm_event_start(struct perf_event *event, int flags)
{
int cpu = smp_processor_id();
struct etm_event_data *event_data;
struct perf_output_handle *handle = this_cpu_ptr(&ctx_handle);
struct coresight_device *sink, *csdev = per_cpu(csdev_src, cpu);
if (!csdev)
goto fail;
/*
* Deal with the ring buffer API and get a handle on the
* session's information.
*/
event_data = perf_aux_output_begin(handle, event);
if (!event_data)
goto fail;
/* We need a sink, no need to continue without one */
sink = coresight_get_sink(event_data->path[cpu]);
if (WARN_ON_ONCE(!sink || !sink_ops(sink)->set_buffer))
goto fail_end_stop;
/* Configure the sink */
if (sink_ops(sink)->set_buffer(sink, handle,
event_data->snk_config))
goto fail_end_stop;
/* Nothing will happen without a path */
if (coresight_enable_path(event_data->path[cpu], CS_MODE_PERF))
goto fail_end_stop;
/* Tell the perf core the event is alive */
event->hw.state = 0;
/* Finally enable the tracer */
if (source_ops(csdev)->enable(csdev, event, CS_MODE_PERF))
goto fail_end_stop;
out:
return;
fail_end_stop:
perf_aux_output_end(handle, 0, true);
fail:
event->hw.state = PERF_HES_STOPPED;
goto out;
}
static void etm_event_stop(struct perf_event *event, int mode)
{
bool lost;
int cpu = smp_processor_id();
unsigned long size;
struct coresight_device *sink, *csdev = per_cpu(csdev_src, cpu);
struct perf_output_handle *handle = this_cpu_ptr(&ctx_handle);
struct etm_event_data *event_data = perf_get_aux(handle);
if (event->hw.state == PERF_HES_STOPPED)
return;
if (!csdev)
return;
sink = coresight_get_sink(event_data->path[cpu]);
if (!sink)
return;
/* stop tracer */
source_ops(csdev)->disable(csdev, event);
/* tell the core */
event->hw.state = PERF_HES_STOPPED;
if (mode & PERF_EF_UPDATE) {
if (WARN_ON_ONCE(handle->event != event))
return;
/* update trace information */
if (!sink_ops(sink)->update_buffer)
return;
sink_ops(sink)->update_buffer(sink, handle,
event_data->snk_config);
if (!sink_ops(sink)->reset_buffer)
return;
size = sink_ops(sink)->reset_buffer(sink, handle,
event_data->snk_config,
&lost);
perf_aux_output_end(handle, size, lost);
}
/* Disabling the path make its elements available to other sessions */
coresight_disable_path(event_data->path[cpu]);
}
static int etm_event_add(struct perf_event *event, int mode)
{
int ret = 0;
struct hw_perf_event *hwc = &event->hw;
if (mode & PERF_EF_START) {
etm_event_start(event, 0);
if (hwc->state & PERF_HES_STOPPED)
ret = -EINVAL;
} else {
hwc->state = PERF_HES_STOPPED;
}
return ret;
}
static void etm_event_del(struct perf_event *event, int mode)
{
etm_event_stop(event, PERF_EF_UPDATE);
}
static int etm_addr_filters_validate(struct list_head *filters)
{
bool range = false, address = false;
int index = 0;
struct perf_addr_filter *filter;
list_for_each_entry(filter, filters, entry) {
/*
* No need to go further if there's no more
* room for filters.
*/
if (++index > ETM_ADDR_CMP_MAX)
return -EOPNOTSUPP;
/*
* As taken from the struct perf_addr_filter documentation:
* @range: 1: range, 0: address
*
* At this time we don't allow range and start/stop filtering
* to cohabitate, they have to be mutually exclusive.
*/
if ((filter->range == 1) && address)
return -EOPNOTSUPP;
if ((filter->range == 0) && range)
return -EOPNOTSUPP;
/*
* For range filtering, the second address in the address
* range comparator needs to be higher than the first.
* Invalid otherwise.
*/
if (filter->range && filter->size == 0)
return -EINVAL;
/*
* Everything checks out with this filter, record what we've
* received before moving on to the next one.
*/
if (filter->range)
range = true;
else
address = true;
}
return 0;
}
static void etm_addr_filters_sync(struct perf_event *event)
{
struct perf_addr_filters_head *head = perf_event_addr_filters(event);
unsigned long start, stop, *offs = event->addr_filters_offs;
struct etm_filters *filters = event->hw.addr_filters;
struct etm_filter *etm_filter;
struct perf_addr_filter *filter;
int i = 0;
list_for_each_entry(filter, &head->list, entry) {
start = filter->offset + offs[i];
stop = start + filter->size;
etm_filter = &filters->etm_filter[i];
if (filter->range == 1) {
etm_filter->start_addr = start;
etm_filter->stop_addr = stop;
etm_filter->type = ETM_ADDR_TYPE_RANGE;
} else {
if (filter->filter == 1) {
etm_filter->start_addr = start;
etm_filter->type = ETM_ADDR_TYPE_START;
} else {
etm_filter->stop_addr = stop;
etm_filter->type = ETM_ADDR_TYPE_STOP;
}
}
i++;
}
filters->nr_filters = i;
}
int etm_perf_symlink(struct coresight_device *csdev, bool link)
{
char entry[sizeof("cpu9999999")];
int ret = 0, cpu = source_ops(csdev)->cpu_id(csdev);
struct device *pmu_dev = etm_pmu.dev;
struct device *cs_dev = &csdev->dev;
sprintf(entry, "cpu%d", cpu);
if (!etm_perf_up)
return -EPROBE_DEFER;
if (link) {
ret = sysfs_create_link(&pmu_dev->kobj, &cs_dev->kobj, entry);
if (ret)
return ret;
per_cpu(csdev_src, cpu) = csdev;
} else {
sysfs_remove_link(&pmu_dev->kobj, entry);
per_cpu(csdev_src, cpu) = NULL;
}
return 0;
}
static int __init etm_perf_init(void)
{
int ret;
etm_pmu.capabilities = PERF_PMU_CAP_EXCLUSIVE;
etm_pmu.attr_groups = etm_pmu_attr_groups;
etm_pmu.task_ctx_nr = perf_sw_context;
etm_pmu.read = etm_event_read;
etm_pmu.event_init = etm_event_init;
etm_pmu.setup_aux = etm_setup_aux;
etm_pmu.free_aux = etm_free_aux;
etm_pmu.start = etm_event_start;
etm_pmu.stop = etm_event_stop;
etm_pmu.add = etm_event_add;
etm_pmu.del = etm_event_del;
etm_pmu.addr_filters_sync = etm_addr_filters_sync;
etm_pmu.addr_filters_validate = etm_addr_filters_validate;
etm_pmu.nr_addr_filters = ETM_ADDR_CMP_MAX;
ret = perf_pmu_register(&etm_pmu, CORESIGHT_ETM_PMU_NAME, -1);
if (ret == 0)
etm_perf_up = true;
return ret;
}
device_initcall(etm_perf_init);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_132_0 |
crossvul-cpp_data_good_2162_2 | /*
* Kernel-based Virtual Machine driver for Linux
*
* This module enables machines with Intel VT-x extensions to run virtual
* machines without emulation or binary translation.
*
* MMU support
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Yaniv Kamay <yaniv@qumranet.com>
* Avi Kivity <avi@qumranet.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include "irq.h"
#include "mmu.h"
#include "x86.h"
#include "kvm_cache_regs.h"
#include <linux/kvm_host.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/module.h>
#include <linux/swap.h>
#include <linux/hugetlb.h>
#include <linux/compiler.h>
#include <linux/srcu.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <asm/page.h>
#include <asm/cmpxchg.h>
#include <asm/io.h>
#include <asm/vmx.h>
/*
* When setting this variable to true it enables Two-Dimensional-Paging
* where the hardware walks 2 page tables:
* 1. the guest-virtual to guest-physical
* 2. while doing 1. it walks guest-physical to host-physical
* If the hardware supports that we don't need to do shadow paging.
*/
bool tdp_enabled = false;
enum {
AUDIT_PRE_PAGE_FAULT,
AUDIT_POST_PAGE_FAULT,
AUDIT_PRE_PTE_WRITE,
AUDIT_POST_PTE_WRITE,
AUDIT_PRE_SYNC,
AUDIT_POST_SYNC
};
#undef MMU_DEBUG
#ifdef MMU_DEBUG
#define pgprintk(x...) do { if (dbg) printk(x); } while (0)
#define rmap_printk(x...) do { if (dbg) printk(x); } while (0)
#else
#define pgprintk(x...) do { } while (0)
#define rmap_printk(x...) do { } while (0)
#endif
#ifdef MMU_DEBUG
static bool dbg = 0;
module_param(dbg, bool, 0644);
#endif
#ifndef MMU_DEBUG
#define ASSERT(x) do { } while (0)
#else
#define ASSERT(x) \
if (!(x)) { \
printk(KERN_WARNING "assertion failed %s:%d: %s\n", \
__FILE__, __LINE__, #x); \
}
#endif
#define PTE_PREFETCH_NUM 8
#define PT_FIRST_AVAIL_BITS_SHIFT 10
#define PT64_SECOND_AVAIL_BITS_SHIFT 52
#define PT64_LEVEL_BITS 9
#define PT64_LEVEL_SHIFT(level) \
(PAGE_SHIFT + (level - 1) * PT64_LEVEL_BITS)
#define PT64_INDEX(address, level)\
(((address) >> PT64_LEVEL_SHIFT(level)) & ((1 << PT64_LEVEL_BITS) - 1))
#define PT32_LEVEL_BITS 10
#define PT32_LEVEL_SHIFT(level) \
(PAGE_SHIFT + (level - 1) * PT32_LEVEL_BITS)
#define PT32_LVL_OFFSET_MASK(level) \
(PT32_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
* PT32_LEVEL_BITS))) - 1))
#define PT32_INDEX(address, level)\
(((address) >> PT32_LEVEL_SHIFT(level)) & ((1 << PT32_LEVEL_BITS) - 1))
#define PT64_BASE_ADDR_MASK (((1ULL << 52) - 1) & ~(u64)(PAGE_SIZE-1))
#define PT64_DIR_BASE_ADDR_MASK \
(PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + PT64_LEVEL_BITS)) - 1))
#define PT64_LVL_ADDR_MASK(level) \
(PT64_BASE_ADDR_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
* PT64_LEVEL_BITS))) - 1))
#define PT64_LVL_OFFSET_MASK(level) \
(PT64_BASE_ADDR_MASK & ((1ULL << (PAGE_SHIFT + (((level) - 1) \
* PT64_LEVEL_BITS))) - 1))
#define PT32_BASE_ADDR_MASK PAGE_MASK
#define PT32_DIR_BASE_ADDR_MASK \
(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + PT32_LEVEL_BITS)) - 1))
#define PT32_LVL_ADDR_MASK(level) \
(PAGE_MASK & ~((1ULL << (PAGE_SHIFT + (((level) - 1) \
* PT32_LEVEL_BITS))) - 1))
#define PT64_PERM_MASK (PT_PRESENT_MASK | PT_WRITABLE_MASK | shadow_user_mask \
| shadow_x_mask | shadow_nx_mask)
#define ACC_EXEC_MASK 1
#define ACC_WRITE_MASK PT_WRITABLE_MASK
#define ACC_USER_MASK PT_USER_MASK
#define ACC_ALL (ACC_EXEC_MASK | ACC_WRITE_MASK | ACC_USER_MASK)
#include <trace/events/kvm.h>
#define CREATE_TRACE_POINTS
#include "mmutrace.h"
#define SPTE_HOST_WRITEABLE (1ULL << PT_FIRST_AVAIL_BITS_SHIFT)
#define SPTE_MMU_WRITEABLE (1ULL << (PT_FIRST_AVAIL_BITS_SHIFT + 1))
#define SHADOW_PT_INDEX(addr, level) PT64_INDEX(addr, level)
/* make pte_list_desc fit well in cache line */
#define PTE_LIST_EXT 3
struct pte_list_desc {
u64 *sptes[PTE_LIST_EXT];
struct pte_list_desc *more;
};
struct kvm_shadow_walk_iterator {
u64 addr;
hpa_t shadow_addr;
u64 *sptep;
int level;
unsigned index;
};
#define for_each_shadow_entry(_vcpu, _addr, _walker) \
for (shadow_walk_init(&(_walker), _vcpu, _addr); \
shadow_walk_okay(&(_walker)); \
shadow_walk_next(&(_walker)))
#define for_each_shadow_entry_lockless(_vcpu, _addr, _walker, spte) \
for (shadow_walk_init(&(_walker), _vcpu, _addr); \
shadow_walk_okay(&(_walker)) && \
({ spte = mmu_spte_get_lockless(_walker.sptep); 1; }); \
__shadow_walk_next(&(_walker), spte))
static struct kmem_cache *pte_list_desc_cache;
static struct kmem_cache *mmu_page_header_cache;
static struct percpu_counter kvm_total_used_mmu_pages;
static u64 __read_mostly shadow_nx_mask;
static u64 __read_mostly shadow_x_mask; /* mutual exclusive with nx_mask */
static u64 __read_mostly shadow_user_mask;
static u64 __read_mostly shadow_accessed_mask;
static u64 __read_mostly shadow_dirty_mask;
static u64 __read_mostly shadow_mmio_mask;
static void mmu_spte_set(u64 *sptep, u64 spte);
static void mmu_free_roots(struct kvm_vcpu *vcpu);
void kvm_mmu_set_mmio_spte_mask(u64 mmio_mask)
{
shadow_mmio_mask = mmio_mask;
}
EXPORT_SYMBOL_GPL(kvm_mmu_set_mmio_spte_mask);
/*
* spte bits of bit 3 ~ bit 11 are used as low 9 bits of generation number,
* the bits of bits 52 ~ bit 61 are used as high 10 bits of generation
* number.
*/
#define MMIO_SPTE_GEN_LOW_SHIFT 3
#define MMIO_SPTE_GEN_HIGH_SHIFT 52
#define MMIO_GEN_SHIFT 19
#define MMIO_GEN_LOW_SHIFT 9
#define MMIO_GEN_LOW_MASK ((1 << MMIO_GEN_LOW_SHIFT) - 1)
#define MMIO_GEN_MASK ((1 << MMIO_GEN_SHIFT) - 1)
#define MMIO_MAX_GEN ((1 << MMIO_GEN_SHIFT) - 1)
static u64 generation_mmio_spte_mask(unsigned int gen)
{
u64 mask;
WARN_ON(gen > MMIO_MAX_GEN);
mask = (gen & MMIO_GEN_LOW_MASK) << MMIO_SPTE_GEN_LOW_SHIFT;
mask |= ((u64)gen >> MMIO_GEN_LOW_SHIFT) << MMIO_SPTE_GEN_HIGH_SHIFT;
return mask;
}
static unsigned int get_mmio_spte_generation(u64 spte)
{
unsigned int gen;
spte &= ~shadow_mmio_mask;
gen = (spte >> MMIO_SPTE_GEN_LOW_SHIFT) & MMIO_GEN_LOW_MASK;
gen |= (spte >> MMIO_SPTE_GEN_HIGH_SHIFT) << MMIO_GEN_LOW_SHIFT;
return gen;
}
static unsigned int kvm_current_mmio_generation(struct kvm *kvm)
{
/*
* Init kvm generation close to MMIO_MAX_GEN to easily test the
* code of handling generation number wrap-around.
*/
return (kvm_memslots(kvm)->generation +
MMIO_MAX_GEN - 150) & MMIO_GEN_MASK;
}
static void mark_mmio_spte(struct kvm *kvm, u64 *sptep, u64 gfn,
unsigned access)
{
unsigned int gen = kvm_current_mmio_generation(kvm);
u64 mask = generation_mmio_spte_mask(gen);
access &= ACC_WRITE_MASK | ACC_USER_MASK;
mask |= shadow_mmio_mask | access | gfn << PAGE_SHIFT;
trace_mark_mmio_spte(sptep, gfn, access, gen);
mmu_spte_set(sptep, mask);
}
static bool is_mmio_spte(u64 spte)
{
return (spte & shadow_mmio_mask) == shadow_mmio_mask;
}
static gfn_t get_mmio_spte_gfn(u64 spte)
{
u64 mask = generation_mmio_spte_mask(MMIO_MAX_GEN) | shadow_mmio_mask;
return (spte & ~mask) >> PAGE_SHIFT;
}
static unsigned get_mmio_spte_access(u64 spte)
{
u64 mask = generation_mmio_spte_mask(MMIO_MAX_GEN) | shadow_mmio_mask;
return (spte & ~mask) & ~PAGE_MASK;
}
static bool set_mmio_spte(struct kvm *kvm, u64 *sptep, gfn_t gfn,
pfn_t pfn, unsigned access)
{
if (unlikely(is_noslot_pfn(pfn))) {
mark_mmio_spte(kvm, sptep, gfn, access);
return true;
}
return false;
}
static bool check_mmio_spte(struct kvm *kvm, u64 spte)
{
unsigned int kvm_gen, spte_gen;
kvm_gen = kvm_current_mmio_generation(kvm);
spte_gen = get_mmio_spte_generation(spte);
trace_check_mmio_spte(spte, kvm_gen, spte_gen);
return likely(kvm_gen == spte_gen);
}
static inline u64 rsvd_bits(int s, int e)
{
return ((1ULL << (e - s + 1)) - 1) << s;
}
void kvm_mmu_set_mask_ptes(u64 user_mask, u64 accessed_mask,
u64 dirty_mask, u64 nx_mask, u64 x_mask)
{
shadow_user_mask = user_mask;
shadow_accessed_mask = accessed_mask;
shadow_dirty_mask = dirty_mask;
shadow_nx_mask = nx_mask;
shadow_x_mask = x_mask;
}
EXPORT_SYMBOL_GPL(kvm_mmu_set_mask_ptes);
static int is_cpuid_PSE36(void)
{
return 1;
}
static int is_nx(struct kvm_vcpu *vcpu)
{
return vcpu->arch.efer & EFER_NX;
}
static int is_shadow_present_pte(u64 pte)
{
return pte & PT_PRESENT_MASK && !is_mmio_spte(pte);
}
static int is_large_pte(u64 pte)
{
return pte & PT_PAGE_SIZE_MASK;
}
static int is_rmap_spte(u64 pte)
{
return is_shadow_present_pte(pte);
}
static int is_last_spte(u64 pte, int level)
{
if (level == PT_PAGE_TABLE_LEVEL)
return 1;
if (is_large_pte(pte))
return 1;
return 0;
}
static pfn_t spte_to_pfn(u64 pte)
{
return (pte & PT64_BASE_ADDR_MASK) >> PAGE_SHIFT;
}
static gfn_t pse36_gfn_delta(u32 gpte)
{
int shift = 32 - PT32_DIR_PSE36_SHIFT - PAGE_SHIFT;
return (gpte & PT32_DIR_PSE36_MASK) << shift;
}
#ifdef CONFIG_X86_64
static void __set_spte(u64 *sptep, u64 spte)
{
*sptep = spte;
}
static void __update_clear_spte_fast(u64 *sptep, u64 spte)
{
*sptep = spte;
}
static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
{
return xchg(sptep, spte);
}
static u64 __get_spte_lockless(u64 *sptep)
{
return ACCESS_ONCE(*sptep);
}
static bool __check_direct_spte_mmio_pf(u64 spte)
{
/* It is valid if the spte is zapped. */
return spte == 0ull;
}
#else
union split_spte {
struct {
u32 spte_low;
u32 spte_high;
};
u64 spte;
};
static void count_spte_clear(u64 *sptep, u64 spte)
{
struct kvm_mmu_page *sp = page_header(__pa(sptep));
if (is_shadow_present_pte(spte))
return;
/* Ensure the spte is completely set before we increase the count */
smp_wmb();
sp->clear_spte_count++;
}
static void __set_spte(u64 *sptep, u64 spte)
{
union split_spte *ssptep, sspte;
ssptep = (union split_spte *)sptep;
sspte = (union split_spte)spte;
ssptep->spte_high = sspte.spte_high;
/*
* If we map the spte from nonpresent to present, We should store
* the high bits firstly, then set present bit, so cpu can not
* fetch this spte while we are setting the spte.
*/
smp_wmb();
ssptep->spte_low = sspte.spte_low;
}
static void __update_clear_spte_fast(u64 *sptep, u64 spte)
{
union split_spte *ssptep, sspte;
ssptep = (union split_spte *)sptep;
sspte = (union split_spte)spte;
ssptep->spte_low = sspte.spte_low;
/*
* If we map the spte from present to nonpresent, we should clear
* present bit firstly to avoid vcpu fetch the old high bits.
*/
smp_wmb();
ssptep->spte_high = sspte.spte_high;
count_spte_clear(sptep, spte);
}
static u64 __update_clear_spte_slow(u64 *sptep, u64 spte)
{
union split_spte *ssptep, sspte, orig;
ssptep = (union split_spte *)sptep;
sspte = (union split_spte)spte;
/* xchg acts as a barrier before the setting of the high bits */
orig.spte_low = xchg(&ssptep->spte_low, sspte.spte_low);
orig.spte_high = ssptep->spte_high;
ssptep->spte_high = sspte.spte_high;
count_spte_clear(sptep, spte);
return orig.spte;
}
/*
* The idea using the light way get the spte on x86_32 guest is from
* gup_get_pte(arch/x86/mm/gup.c).
*
* An spte tlb flush may be pending, because kvm_set_pte_rmapp
* coalesces them and we are running out of the MMU lock. Therefore
* we need to protect against in-progress updates of the spte.
*
* Reading the spte while an update is in progress may get the old value
* for the high part of the spte. The race is fine for a present->non-present
* change (because the high part of the spte is ignored for non-present spte),
* but for a present->present change we must reread the spte.
*
* All such changes are done in two steps (present->non-present and
* non-present->present), hence it is enough to count the number of
* present->non-present updates: if it changed while reading the spte,
* we might have hit the race. This is done using clear_spte_count.
*/
static u64 __get_spte_lockless(u64 *sptep)
{
struct kvm_mmu_page *sp = page_header(__pa(sptep));
union split_spte spte, *orig = (union split_spte *)sptep;
int count;
retry:
count = sp->clear_spte_count;
smp_rmb();
spte.spte_low = orig->spte_low;
smp_rmb();
spte.spte_high = orig->spte_high;
smp_rmb();
if (unlikely(spte.spte_low != orig->spte_low ||
count != sp->clear_spte_count))
goto retry;
return spte.spte;
}
static bool __check_direct_spte_mmio_pf(u64 spte)
{
union split_spte sspte = (union split_spte)spte;
u32 high_mmio_mask = shadow_mmio_mask >> 32;
/* It is valid if the spte is zapped. */
if (spte == 0ull)
return true;
/* It is valid if the spte is being zapped. */
if (sspte.spte_low == 0ull &&
(sspte.spte_high & high_mmio_mask) == high_mmio_mask)
return true;
return false;
}
#endif
static bool spte_is_locklessly_modifiable(u64 spte)
{
return (spte & (SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE)) ==
(SPTE_HOST_WRITEABLE | SPTE_MMU_WRITEABLE);
}
static bool spte_has_volatile_bits(u64 spte)
{
/*
* Always atomicly update spte if it can be updated
* out of mmu-lock, it can ensure dirty bit is not lost,
* also, it can help us to get a stable is_writable_pte()
* to ensure tlb flush is not missed.
*/
if (spte_is_locklessly_modifiable(spte))
return true;
if (!shadow_accessed_mask)
return false;
if (!is_shadow_present_pte(spte))
return false;
if ((spte & shadow_accessed_mask) &&
(!is_writable_pte(spte) || (spte & shadow_dirty_mask)))
return false;
return true;
}
static bool spte_is_bit_cleared(u64 old_spte, u64 new_spte, u64 bit_mask)
{
return (old_spte & bit_mask) && !(new_spte & bit_mask);
}
/* Rules for using mmu_spte_set:
* Set the sptep from nonpresent to present.
* Note: the sptep being assigned *must* be either not present
* or in a state where the hardware will not attempt to update
* the spte.
*/
static void mmu_spte_set(u64 *sptep, u64 new_spte)
{
WARN_ON(is_shadow_present_pte(*sptep));
__set_spte(sptep, new_spte);
}
/* Rules for using mmu_spte_update:
* Update the state bits, it means the mapped pfn is not changged.
*
* Whenever we overwrite a writable spte with a read-only one we
* should flush remote TLBs. Otherwise rmap_write_protect
* will find a read-only spte, even though the writable spte
* might be cached on a CPU's TLB, the return value indicates this
* case.
*/
static bool mmu_spte_update(u64 *sptep, u64 new_spte)
{
u64 old_spte = *sptep;
bool ret = false;
WARN_ON(!is_rmap_spte(new_spte));
if (!is_shadow_present_pte(old_spte)) {
mmu_spte_set(sptep, new_spte);
return ret;
}
if (!spte_has_volatile_bits(old_spte))
__update_clear_spte_fast(sptep, new_spte);
else
old_spte = __update_clear_spte_slow(sptep, new_spte);
/*
* For the spte updated out of mmu-lock is safe, since
* we always atomicly update it, see the comments in
* spte_has_volatile_bits().
*/
if (is_writable_pte(old_spte) && !is_writable_pte(new_spte))
ret = true;
if (!shadow_accessed_mask)
return ret;
if (spte_is_bit_cleared(old_spte, new_spte, shadow_accessed_mask))
kvm_set_pfn_accessed(spte_to_pfn(old_spte));
if (spte_is_bit_cleared(old_spte, new_spte, shadow_dirty_mask))
kvm_set_pfn_dirty(spte_to_pfn(old_spte));
return ret;
}
/*
* Rules for using mmu_spte_clear_track_bits:
* It sets the sptep from present to nonpresent, and track the
* state bits, it is used to clear the last level sptep.
*/
static int mmu_spte_clear_track_bits(u64 *sptep)
{
pfn_t pfn;
u64 old_spte = *sptep;
if (!spte_has_volatile_bits(old_spte))
__update_clear_spte_fast(sptep, 0ull);
else
old_spte = __update_clear_spte_slow(sptep, 0ull);
if (!is_rmap_spte(old_spte))
return 0;
pfn = spte_to_pfn(old_spte);
/*
* KVM does not hold the refcount of the page used by
* kvm mmu, before reclaiming the page, we should
* unmap it from mmu first.
*/
WARN_ON(!kvm_is_mmio_pfn(pfn) && !page_count(pfn_to_page(pfn)));
if (!shadow_accessed_mask || old_spte & shadow_accessed_mask)
kvm_set_pfn_accessed(pfn);
if (!shadow_dirty_mask || (old_spte & shadow_dirty_mask))
kvm_set_pfn_dirty(pfn);
return 1;
}
/*
* Rules for using mmu_spte_clear_no_track:
* Directly clear spte without caring the state bits of sptep,
* it is used to set the upper level spte.
*/
static void mmu_spte_clear_no_track(u64 *sptep)
{
__update_clear_spte_fast(sptep, 0ull);
}
static u64 mmu_spte_get_lockless(u64 *sptep)
{
return __get_spte_lockless(sptep);
}
static void walk_shadow_page_lockless_begin(struct kvm_vcpu *vcpu)
{
/*
* Prevent page table teardown by making any free-er wait during
* kvm_flush_remote_tlbs() IPI to all active vcpus.
*/
local_irq_disable();
vcpu->mode = READING_SHADOW_PAGE_TABLES;
/*
* Make sure a following spte read is not reordered ahead of the write
* to vcpu->mode.
*/
smp_mb();
}
static void walk_shadow_page_lockless_end(struct kvm_vcpu *vcpu)
{
/*
* Make sure the write to vcpu->mode is not reordered in front of
* reads to sptes. If it does, kvm_commit_zap_page() can see us
* OUTSIDE_GUEST_MODE and proceed to free the shadow page table.
*/
smp_mb();
vcpu->mode = OUTSIDE_GUEST_MODE;
local_irq_enable();
}
static int mmu_topup_memory_cache(struct kvm_mmu_memory_cache *cache,
struct kmem_cache *base_cache, int min)
{
void *obj;
if (cache->nobjs >= min)
return 0;
while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
obj = kmem_cache_zalloc(base_cache, GFP_KERNEL);
if (!obj)
return -ENOMEM;
cache->objects[cache->nobjs++] = obj;
}
return 0;
}
static int mmu_memory_cache_free_objects(struct kvm_mmu_memory_cache *cache)
{
return cache->nobjs;
}
static void mmu_free_memory_cache(struct kvm_mmu_memory_cache *mc,
struct kmem_cache *cache)
{
while (mc->nobjs)
kmem_cache_free(cache, mc->objects[--mc->nobjs]);
}
static int mmu_topup_memory_cache_page(struct kvm_mmu_memory_cache *cache,
int min)
{
void *page;
if (cache->nobjs >= min)
return 0;
while (cache->nobjs < ARRAY_SIZE(cache->objects)) {
page = (void *)__get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
cache->objects[cache->nobjs++] = page;
}
return 0;
}
static void mmu_free_memory_cache_page(struct kvm_mmu_memory_cache *mc)
{
while (mc->nobjs)
free_page((unsigned long)mc->objects[--mc->nobjs]);
}
static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu)
{
int r;
r = mmu_topup_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
pte_list_desc_cache, 8 + PTE_PREFETCH_NUM);
if (r)
goto out;
r = mmu_topup_memory_cache_page(&vcpu->arch.mmu_page_cache, 8);
if (r)
goto out;
r = mmu_topup_memory_cache(&vcpu->arch.mmu_page_header_cache,
mmu_page_header_cache, 4);
out:
return r;
}
static void mmu_free_memory_caches(struct kvm_vcpu *vcpu)
{
mmu_free_memory_cache(&vcpu->arch.mmu_pte_list_desc_cache,
pte_list_desc_cache);
mmu_free_memory_cache_page(&vcpu->arch.mmu_page_cache);
mmu_free_memory_cache(&vcpu->arch.mmu_page_header_cache,
mmu_page_header_cache);
}
static void *mmu_memory_cache_alloc(struct kvm_mmu_memory_cache *mc)
{
void *p;
BUG_ON(!mc->nobjs);
p = mc->objects[--mc->nobjs];
return p;
}
static struct pte_list_desc *mmu_alloc_pte_list_desc(struct kvm_vcpu *vcpu)
{
return mmu_memory_cache_alloc(&vcpu->arch.mmu_pte_list_desc_cache);
}
static void mmu_free_pte_list_desc(struct pte_list_desc *pte_list_desc)
{
kmem_cache_free(pte_list_desc_cache, pte_list_desc);
}
static gfn_t kvm_mmu_page_get_gfn(struct kvm_mmu_page *sp, int index)
{
if (!sp->role.direct)
return sp->gfns[index];
return sp->gfn + (index << ((sp->role.level - 1) * PT64_LEVEL_BITS));
}
static void kvm_mmu_page_set_gfn(struct kvm_mmu_page *sp, int index, gfn_t gfn)
{
if (sp->role.direct)
BUG_ON(gfn != kvm_mmu_page_get_gfn(sp, index));
else
sp->gfns[index] = gfn;
}
/*
* Return the pointer to the large page information for a given gfn,
* handling slots that are not large page aligned.
*/
static struct kvm_lpage_info *lpage_info_slot(gfn_t gfn,
struct kvm_memory_slot *slot,
int level)
{
unsigned long idx;
idx = gfn_to_index(gfn, slot->base_gfn, level);
return &slot->arch.lpage_info[level - 2][idx];
}
static void account_shadowed(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *slot;
struct kvm_lpage_info *linfo;
int i;
slot = gfn_to_memslot(kvm, gfn);
for (i = PT_DIRECTORY_LEVEL;
i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) {
linfo = lpage_info_slot(gfn, slot, i);
linfo->write_count += 1;
}
kvm->arch.indirect_shadow_pages++;
}
static void unaccount_shadowed(struct kvm *kvm, gfn_t gfn)
{
struct kvm_memory_slot *slot;
struct kvm_lpage_info *linfo;
int i;
slot = gfn_to_memslot(kvm, gfn);
for (i = PT_DIRECTORY_LEVEL;
i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) {
linfo = lpage_info_slot(gfn, slot, i);
linfo->write_count -= 1;
WARN_ON(linfo->write_count < 0);
}
kvm->arch.indirect_shadow_pages--;
}
static int has_wrprotected_page(struct kvm *kvm,
gfn_t gfn,
int level)
{
struct kvm_memory_slot *slot;
struct kvm_lpage_info *linfo;
slot = gfn_to_memslot(kvm, gfn);
if (slot) {
linfo = lpage_info_slot(gfn, slot, level);
return linfo->write_count;
}
return 1;
}
static int host_mapping_level(struct kvm *kvm, gfn_t gfn)
{
unsigned long page_size;
int i, ret = 0;
page_size = kvm_host_page_size(kvm, gfn);
for (i = PT_PAGE_TABLE_LEVEL;
i < (PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES); ++i) {
if (page_size >= KVM_HPAGE_SIZE(i))
ret = i;
else
break;
}
return ret;
}
static struct kvm_memory_slot *
gfn_to_memslot_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t gfn,
bool no_dirty_log)
{
struct kvm_memory_slot *slot;
slot = gfn_to_memslot(vcpu->kvm, gfn);
if (!slot || slot->flags & KVM_MEMSLOT_INVALID ||
(no_dirty_log && slot->dirty_bitmap))
slot = NULL;
return slot;
}
static bool mapping_level_dirty_bitmap(struct kvm_vcpu *vcpu, gfn_t large_gfn)
{
return !gfn_to_memslot_dirty_bitmap(vcpu, large_gfn, true);
}
static int mapping_level(struct kvm_vcpu *vcpu, gfn_t large_gfn)
{
int host_level, level, max_level;
host_level = host_mapping_level(vcpu->kvm, large_gfn);
if (host_level == PT_PAGE_TABLE_LEVEL)
return host_level;
max_level = min(kvm_x86_ops->get_lpage_level(), host_level);
for (level = PT_DIRECTORY_LEVEL; level <= max_level; ++level)
if (has_wrprotected_page(vcpu->kvm, large_gfn, level))
break;
return level - 1;
}
/*
* Pte mapping structures:
*
* If pte_list bit zero is zero, then pte_list point to the spte.
*
* If pte_list bit zero is one, (then pte_list & ~1) points to a struct
* pte_list_desc containing more mappings.
*
* Returns the number of pte entries before the spte was added or zero if
* the spte was not added.
*
*/
static int pte_list_add(struct kvm_vcpu *vcpu, u64 *spte,
unsigned long *pte_list)
{
struct pte_list_desc *desc;
int i, count = 0;
if (!*pte_list) {
rmap_printk("pte_list_add: %p %llx 0->1\n", spte, *spte);
*pte_list = (unsigned long)spte;
} else if (!(*pte_list & 1)) {
rmap_printk("pte_list_add: %p %llx 1->many\n", spte, *spte);
desc = mmu_alloc_pte_list_desc(vcpu);
desc->sptes[0] = (u64 *)*pte_list;
desc->sptes[1] = spte;
*pte_list = (unsigned long)desc | 1;
++count;
} else {
rmap_printk("pte_list_add: %p %llx many->many\n", spte, *spte);
desc = (struct pte_list_desc *)(*pte_list & ~1ul);
while (desc->sptes[PTE_LIST_EXT-1] && desc->more) {
desc = desc->more;
count += PTE_LIST_EXT;
}
if (desc->sptes[PTE_LIST_EXT-1]) {
desc->more = mmu_alloc_pte_list_desc(vcpu);
desc = desc->more;
}
for (i = 0; desc->sptes[i]; ++i)
++count;
desc->sptes[i] = spte;
}
return count;
}
static void
pte_list_desc_remove_entry(unsigned long *pte_list, struct pte_list_desc *desc,
int i, struct pte_list_desc *prev_desc)
{
int j;
for (j = PTE_LIST_EXT - 1; !desc->sptes[j] && j > i; --j)
;
desc->sptes[i] = desc->sptes[j];
desc->sptes[j] = NULL;
if (j != 0)
return;
if (!prev_desc && !desc->more)
*pte_list = (unsigned long)desc->sptes[0];
else
if (prev_desc)
prev_desc->more = desc->more;
else
*pte_list = (unsigned long)desc->more | 1;
mmu_free_pte_list_desc(desc);
}
static void pte_list_remove(u64 *spte, unsigned long *pte_list)
{
struct pte_list_desc *desc;
struct pte_list_desc *prev_desc;
int i;
if (!*pte_list) {
printk(KERN_ERR "pte_list_remove: %p 0->BUG\n", spte);
BUG();
} else if (!(*pte_list & 1)) {
rmap_printk("pte_list_remove: %p 1->0\n", spte);
if ((u64 *)*pte_list != spte) {
printk(KERN_ERR "pte_list_remove: %p 1->BUG\n", spte);
BUG();
}
*pte_list = 0;
} else {
rmap_printk("pte_list_remove: %p many->many\n", spte);
desc = (struct pte_list_desc *)(*pte_list & ~1ul);
prev_desc = NULL;
while (desc) {
for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i)
if (desc->sptes[i] == spte) {
pte_list_desc_remove_entry(pte_list,
desc, i,
prev_desc);
return;
}
prev_desc = desc;
desc = desc->more;
}
pr_err("pte_list_remove: %p many->many\n", spte);
BUG();
}
}
typedef void (*pte_list_walk_fn) (u64 *spte);
static void pte_list_walk(unsigned long *pte_list, pte_list_walk_fn fn)
{
struct pte_list_desc *desc;
int i;
if (!*pte_list)
return;
if (!(*pte_list & 1))
return fn((u64 *)*pte_list);
desc = (struct pte_list_desc *)(*pte_list & ~1ul);
while (desc) {
for (i = 0; i < PTE_LIST_EXT && desc->sptes[i]; ++i)
fn(desc->sptes[i]);
desc = desc->more;
}
}
static unsigned long *__gfn_to_rmap(gfn_t gfn, int level,
struct kvm_memory_slot *slot)
{
unsigned long idx;
idx = gfn_to_index(gfn, slot->base_gfn, level);
return &slot->arch.rmap[level - PT_PAGE_TABLE_LEVEL][idx];
}
/*
* Take gfn and return the reverse mapping to it.
*/
static unsigned long *gfn_to_rmap(struct kvm *kvm, gfn_t gfn, int level)
{
struct kvm_memory_slot *slot;
slot = gfn_to_memslot(kvm, gfn);
return __gfn_to_rmap(gfn, level, slot);
}
static bool rmap_can_add(struct kvm_vcpu *vcpu)
{
struct kvm_mmu_memory_cache *cache;
cache = &vcpu->arch.mmu_pte_list_desc_cache;
return mmu_memory_cache_free_objects(cache);
}
static int rmap_add(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
{
struct kvm_mmu_page *sp;
unsigned long *rmapp;
sp = page_header(__pa(spte));
kvm_mmu_page_set_gfn(sp, spte - sp->spt, gfn);
rmapp = gfn_to_rmap(vcpu->kvm, gfn, sp->role.level);
return pte_list_add(vcpu, spte, rmapp);
}
static void rmap_remove(struct kvm *kvm, u64 *spte)
{
struct kvm_mmu_page *sp;
gfn_t gfn;
unsigned long *rmapp;
sp = page_header(__pa(spte));
gfn = kvm_mmu_page_get_gfn(sp, spte - sp->spt);
rmapp = gfn_to_rmap(kvm, gfn, sp->role.level);
pte_list_remove(spte, rmapp);
}
/*
* Used by the following functions to iterate through the sptes linked by a
* rmap. All fields are private and not assumed to be used outside.
*/
struct rmap_iterator {
/* private fields */
struct pte_list_desc *desc; /* holds the sptep if not NULL */
int pos; /* index of the sptep */
};
/*
* Iteration must be started by this function. This should also be used after
* removing/dropping sptes from the rmap link because in such cases the
* information in the itererator may not be valid.
*
* Returns sptep if found, NULL otherwise.
*/
static u64 *rmap_get_first(unsigned long rmap, struct rmap_iterator *iter)
{
if (!rmap)
return NULL;
if (!(rmap & 1)) {
iter->desc = NULL;
return (u64 *)rmap;
}
iter->desc = (struct pte_list_desc *)(rmap & ~1ul);
iter->pos = 0;
return iter->desc->sptes[iter->pos];
}
/*
* Must be used with a valid iterator: e.g. after rmap_get_first().
*
* Returns sptep if found, NULL otherwise.
*/
static u64 *rmap_get_next(struct rmap_iterator *iter)
{
if (iter->desc) {
if (iter->pos < PTE_LIST_EXT - 1) {
u64 *sptep;
++iter->pos;
sptep = iter->desc->sptes[iter->pos];
if (sptep)
return sptep;
}
iter->desc = iter->desc->more;
if (iter->desc) {
iter->pos = 0;
/* desc->sptes[0] cannot be NULL */
return iter->desc->sptes[iter->pos];
}
}
return NULL;
}
static void drop_spte(struct kvm *kvm, u64 *sptep)
{
if (mmu_spte_clear_track_bits(sptep))
rmap_remove(kvm, sptep);
}
static bool __drop_large_spte(struct kvm *kvm, u64 *sptep)
{
if (is_large_pte(*sptep)) {
WARN_ON(page_header(__pa(sptep))->role.level ==
PT_PAGE_TABLE_LEVEL);
drop_spte(kvm, sptep);
--kvm->stat.lpages;
return true;
}
return false;
}
static void drop_large_spte(struct kvm_vcpu *vcpu, u64 *sptep)
{
if (__drop_large_spte(vcpu->kvm, sptep))
kvm_flush_remote_tlbs(vcpu->kvm);
}
/*
* Write-protect on the specified @sptep, @pt_protect indicates whether
* spte writ-protection is caused by protecting shadow page table.
* @flush indicates whether tlb need be flushed.
*
* Note: write protection is difference between drity logging and spte
* protection:
* - for dirty logging, the spte can be set to writable at anytime if
* its dirty bitmap is properly set.
* - for spte protection, the spte can be writable only after unsync-ing
* shadow page.
*
* Return true if the spte is dropped.
*/
static bool
spte_write_protect(struct kvm *kvm, u64 *sptep, bool *flush, bool pt_protect)
{
u64 spte = *sptep;
if (!is_writable_pte(spte) &&
!(pt_protect && spte_is_locklessly_modifiable(spte)))
return false;
rmap_printk("rmap_write_protect: spte %p %llx\n", sptep, *sptep);
if (__drop_large_spte(kvm, sptep)) {
*flush |= true;
return true;
}
if (pt_protect)
spte &= ~SPTE_MMU_WRITEABLE;
spte = spte & ~PT_WRITABLE_MASK;
*flush |= mmu_spte_update(sptep, spte);
return false;
}
static bool __rmap_write_protect(struct kvm *kvm, unsigned long *rmapp,
bool pt_protect)
{
u64 *sptep;
struct rmap_iterator iter;
bool flush = false;
for (sptep = rmap_get_first(*rmapp, &iter); sptep;) {
BUG_ON(!(*sptep & PT_PRESENT_MASK));
if (spte_write_protect(kvm, sptep, &flush, pt_protect)) {
sptep = rmap_get_first(*rmapp, &iter);
continue;
}
sptep = rmap_get_next(&iter);
}
return flush;
}
/**
* kvm_mmu_write_protect_pt_masked - write protect selected PT level pages
* @kvm: kvm instance
* @slot: slot to protect
* @gfn_offset: start of the BITS_PER_LONG pages we care about
* @mask: indicates which pages we should protect
*
* Used when we do not need to care about huge page mappings: e.g. during dirty
* logging we do not have any such mappings.
*/
void kvm_mmu_write_protect_pt_masked(struct kvm *kvm,
struct kvm_memory_slot *slot,
gfn_t gfn_offset, unsigned long mask)
{
unsigned long *rmapp;
while (mask) {
rmapp = __gfn_to_rmap(slot->base_gfn + gfn_offset + __ffs(mask),
PT_PAGE_TABLE_LEVEL, slot);
__rmap_write_protect(kvm, rmapp, false);
/* clear the first set bit */
mask &= mask - 1;
}
}
static bool rmap_write_protect(struct kvm *kvm, u64 gfn)
{
struct kvm_memory_slot *slot;
unsigned long *rmapp;
int i;
bool write_protected = false;
slot = gfn_to_memslot(kvm, gfn);
for (i = PT_PAGE_TABLE_LEVEL;
i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) {
rmapp = __gfn_to_rmap(gfn, i, slot);
write_protected |= __rmap_write_protect(kvm, rmapp, true);
}
return write_protected;
}
static int kvm_unmap_rmapp(struct kvm *kvm, unsigned long *rmapp,
struct kvm_memory_slot *slot, unsigned long data)
{
u64 *sptep;
struct rmap_iterator iter;
int need_tlb_flush = 0;
while ((sptep = rmap_get_first(*rmapp, &iter))) {
BUG_ON(!(*sptep & PT_PRESENT_MASK));
rmap_printk("kvm_rmap_unmap_hva: spte %p %llx\n", sptep, *sptep);
drop_spte(kvm, sptep);
need_tlb_flush = 1;
}
return need_tlb_flush;
}
static int kvm_set_pte_rmapp(struct kvm *kvm, unsigned long *rmapp,
struct kvm_memory_slot *slot, unsigned long data)
{
u64 *sptep;
struct rmap_iterator iter;
int need_flush = 0;
u64 new_spte;
pte_t *ptep = (pte_t *)data;
pfn_t new_pfn;
WARN_ON(pte_huge(*ptep));
new_pfn = pte_pfn(*ptep);
for (sptep = rmap_get_first(*rmapp, &iter); sptep;) {
BUG_ON(!is_shadow_present_pte(*sptep));
rmap_printk("kvm_set_pte_rmapp: spte %p %llx\n", sptep, *sptep);
need_flush = 1;
if (pte_write(*ptep)) {
drop_spte(kvm, sptep);
sptep = rmap_get_first(*rmapp, &iter);
} else {
new_spte = *sptep & ~PT64_BASE_ADDR_MASK;
new_spte |= (u64)new_pfn << PAGE_SHIFT;
new_spte &= ~PT_WRITABLE_MASK;
new_spte &= ~SPTE_HOST_WRITEABLE;
new_spte &= ~shadow_accessed_mask;
mmu_spte_clear_track_bits(sptep);
mmu_spte_set(sptep, new_spte);
sptep = rmap_get_next(&iter);
}
}
if (need_flush)
kvm_flush_remote_tlbs(kvm);
return 0;
}
static int kvm_handle_hva_range(struct kvm *kvm,
unsigned long start,
unsigned long end,
unsigned long data,
int (*handler)(struct kvm *kvm,
unsigned long *rmapp,
struct kvm_memory_slot *slot,
unsigned long data))
{
int j;
int ret = 0;
struct kvm_memslots *slots;
struct kvm_memory_slot *memslot;
slots = kvm_memslots(kvm);
kvm_for_each_memslot(memslot, slots) {
unsigned long hva_start, hva_end;
gfn_t gfn_start, gfn_end;
hva_start = max(start, memslot->userspace_addr);
hva_end = min(end, memslot->userspace_addr +
(memslot->npages << PAGE_SHIFT));
if (hva_start >= hva_end)
continue;
/*
* {gfn(page) | page intersects with [hva_start, hva_end)} =
* {gfn_start, gfn_start+1, ..., gfn_end-1}.
*/
gfn_start = hva_to_gfn_memslot(hva_start, memslot);
gfn_end = hva_to_gfn_memslot(hva_end + PAGE_SIZE - 1, memslot);
for (j = PT_PAGE_TABLE_LEVEL;
j < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++j) {
unsigned long idx, idx_end;
unsigned long *rmapp;
/*
* {idx(page_j) | page_j intersects with
* [hva_start, hva_end)} = {idx, idx+1, ..., idx_end}.
*/
idx = gfn_to_index(gfn_start, memslot->base_gfn, j);
idx_end = gfn_to_index(gfn_end - 1, memslot->base_gfn, j);
rmapp = __gfn_to_rmap(gfn_start, j, memslot);
for (; idx <= idx_end; ++idx)
ret |= handler(kvm, rmapp++, memslot, data);
}
}
return ret;
}
static int kvm_handle_hva(struct kvm *kvm, unsigned long hva,
unsigned long data,
int (*handler)(struct kvm *kvm, unsigned long *rmapp,
struct kvm_memory_slot *slot,
unsigned long data))
{
return kvm_handle_hva_range(kvm, hva, hva + 1, data, handler);
}
int kvm_unmap_hva(struct kvm *kvm, unsigned long hva)
{
return kvm_handle_hva(kvm, hva, 0, kvm_unmap_rmapp);
}
int kvm_unmap_hva_range(struct kvm *kvm, unsigned long start, unsigned long end)
{
return kvm_handle_hva_range(kvm, start, end, 0, kvm_unmap_rmapp);
}
void kvm_set_spte_hva(struct kvm *kvm, unsigned long hva, pte_t pte)
{
kvm_handle_hva(kvm, hva, (unsigned long)&pte, kvm_set_pte_rmapp);
}
static int kvm_age_rmapp(struct kvm *kvm, unsigned long *rmapp,
struct kvm_memory_slot *slot, unsigned long data)
{
u64 *sptep;
struct rmap_iterator uninitialized_var(iter);
int young = 0;
/*
* In case of absence of EPT Access and Dirty Bits supports,
* emulate the accessed bit for EPT, by checking if this page has
* an EPT mapping, and clearing it if it does. On the next access,
* a new EPT mapping will be established.
* This has some overhead, but not as much as the cost of swapping
* out actively used pages or breaking up actively used hugepages.
*/
if (!shadow_accessed_mask) {
young = kvm_unmap_rmapp(kvm, rmapp, slot, data);
goto out;
}
for (sptep = rmap_get_first(*rmapp, &iter); sptep;
sptep = rmap_get_next(&iter)) {
BUG_ON(!is_shadow_present_pte(*sptep));
if (*sptep & shadow_accessed_mask) {
young = 1;
clear_bit((ffs(shadow_accessed_mask) - 1),
(unsigned long *)sptep);
}
}
out:
/* @data has hva passed to kvm_age_hva(). */
trace_kvm_age_page(data, slot, young);
return young;
}
static int kvm_test_age_rmapp(struct kvm *kvm, unsigned long *rmapp,
struct kvm_memory_slot *slot, unsigned long data)
{
u64 *sptep;
struct rmap_iterator iter;
int young = 0;
/*
* If there's no access bit in the secondary pte set by the
* hardware it's up to gup-fast/gup to set the access bit in
* the primary pte or in the page structure.
*/
if (!shadow_accessed_mask)
goto out;
for (sptep = rmap_get_first(*rmapp, &iter); sptep;
sptep = rmap_get_next(&iter)) {
BUG_ON(!is_shadow_present_pte(*sptep));
if (*sptep & shadow_accessed_mask) {
young = 1;
break;
}
}
out:
return young;
}
#define RMAP_RECYCLE_THRESHOLD 1000
static void rmap_recycle(struct kvm_vcpu *vcpu, u64 *spte, gfn_t gfn)
{
unsigned long *rmapp;
struct kvm_mmu_page *sp;
sp = page_header(__pa(spte));
rmapp = gfn_to_rmap(vcpu->kvm, gfn, sp->role.level);
kvm_unmap_rmapp(vcpu->kvm, rmapp, NULL, 0);
kvm_flush_remote_tlbs(vcpu->kvm);
}
int kvm_age_hva(struct kvm *kvm, unsigned long hva)
{
return kvm_handle_hva(kvm, hva, hva, kvm_age_rmapp);
}
int kvm_test_age_hva(struct kvm *kvm, unsigned long hva)
{
return kvm_handle_hva(kvm, hva, 0, kvm_test_age_rmapp);
}
#ifdef MMU_DEBUG
static int is_empty_shadow_page(u64 *spt)
{
u64 *pos;
u64 *end;
for (pos = spt, end = pos + PAGE_SIZE / sizeof(u64); pos != end; pos++)
if (is_shadow_present_pte(*pos)) {
printk(KERN_ERR "%s: %p %llx\n", __func__,
pos, *pos);
return 0;
}
return 1;
}
#endif
/*
* This value is the sum of all of the kvm instances's
* kvm->arch.n_used_mmu_pages values. We need a global,
* aggregate version in order to make the slab shrinker
* faster
*/
static inline void kvm_mod_used_mmu_pages(struct kvm *kvm, int nr)
{
kvm->arch.n_used_mmu_pages += nr;
percpu_counter_add(&kvm_total_used_mmu_pages, nr);
}
static void kvm_mmu_free_page(struct kvm_mmu_page *sp)
{
ASSERT(is_empty_shadow_page(sp->spt));
hlist_del(&sp->hash_link);
list_del(&sp->link);
free_page((unsigned long)sp->spt);
if (!sp->role.direct)
free_page((unsigned long)sp->gfns);
kmem_cache_free(mmu_page_header_cache, sp);
}
static unsigned kvm_page_table_hashfn(gfn_t gfn)
{
return gfn & ((1 << KVM_MMU_HASH_SHIFT) - 1);
}
static void mmu_page_add_parent_pte(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp, u64 *parent_pte)
{
if (!parent_pte)
return;
pte_list_add(vcpu, parent_pte, &sp->parent_ptes);
}
static void mmu_page_remove_parent_pte(struct kvm_mmu_page *sp,
u64 *parent_pte)
{
pte_list_remove(parent_pte, &sp->parent_ptes);
}
static void drop_parent_pte(struct kvm_mmu_page *sp,
u64 *parent_pte)
{
mmu_page_remove_parent_pte(sp, parent_pte);
mmu_spte_clear_no_track(parent_pte);
}
static struct kvm_mmu_page *kvm_mmu_alloc_page(struct kvm_vcpu *vcpu,
u64 *parent_pte, int direct)
{
struct kvm_mmu_page *sp;
sp = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_header_cache);
sp->spt = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
if (!direct)
sp->gfns = mmu_memory_cache_alloc(&vcpu->arch.mmu_page_cache);
set_page_private(virt_to_page(sp->spt), (unsigned long)sp);
/*
* The active_mmu_pages list is the FIFO list, do not move the
* page until it is zapped. kvm_zap_obsolete_pages depends on
* this feature. See the comments in kvm_zap_obsolete_pages().
*/
list_add(&sp->link, &vcpu->kvm->arch.active_mmu_pages);
sp->parent_ptes = 0;
mmu_page_add_parent_pte(vcpu, sp, parent_pte);
kvm_mod_used_mmu_pages(vcpu->kvm, +1);
return sp;
}
static void mark_unsync(u64 *spte);
static void kvm_mmu_mark_parents_unsync(struct kvm_mmu_page *sp)
{
pte_list_walk(&sp->parent_ptes, mark_unsync);
}
static void mark_unsync(u64 *spte)
{
struct kvm_mmu_page *sp;
unsigned int index;
sp = page_header(__pa(spte));
index = spte - sp->spt;
if (__test_and_set_bit(index, sp->unsync_child_bitmap))
return;
if (sp->unsync_children++)
return;
kvm_mmu_mark_parents_unsync(sp);
}
static int nonpaging_sync_page(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp)
{
return 1;
}
static void nonpaging_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
{
}
static void nonpaging_update_pte(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp, u64 *spte,
const void *pte)
{
WARN_ON(1);
}
#define KVM_PAGE_ARRAY_NR 16
struct kvm_mmu_pages {
struct mmu_page_and_offset {
struct kvm_mmu_page *sp;
unsigned int idx;
} page[KVM_PAGE_ARRAY_NR];
unsigned int nr;
};
static int mmu_pages_add(struct kvm_mmu_pages *pvec, struct kvm_mmu_page *sp,
int idx)
{
int i;
if (sp->unsync)
for (i=0; i < pvec->nr; i++)
if (pvec->page[i].sp == sp)
return 0;
pvec->page[pvec->nr].sp = sp;
pvec->page[pvec->nr].idx = idx;
pvec->nr++;
return (pvec->nr == KVM_PAGE_ARRAY_NR);
}
static int __mmu_unsync_walk(struct kvm_mmu_page *sp,
struct kvm_mmu_pages *pvec)
{
int i, ret, nr_unsync_leaf = 0;
for_each_set_bit(i, sp->unsync_child_bitmap, 512) {
struct kvm_mmu_page *child;
u64 ent = sp->spt[i];
if (!is_shadow_present_pte(ent) || is_large_pte(ent))
goto clear_child_bitmap;
child = page_header(ent & PT64_BASE_ADDR_MASK);
if (child->unsync_children) {
if (mmu_pages_add(pvec, child, i))
return -ENOSPC;
ret = __mmu_unsync_walk(child, pvec);
if (!ret)
goto clear_child_bitmap;
else if (ret > 0)
nr_unsync_leaf += ret;
else
return ret;
} else if (child->unsync) {
nr_unsync_leaf++;
if (mmu_pages_add(pvec, child, i))
return -ENOSPC;
} else
goto clear_child_bitmap;
continue;
clear_child_bitmap:
__clear_bit(i, sp->unsync_child_bitmap);
sp->unsync_children--;
WARN_ON((int)sp->unsync_children < 0);
}
return nr_unsync_leaf;
}
static int mmu_unsync_walk(struct kvm_mmu_page *sp,
struct kvm_mmu_pages *pvec)
{
if (!sp->unsync_children)
return 0;
mmu_pages_add(pvec, sp, 0);
return __mmu_unsync_walk(sp, pvec);
}
static void kvm_unlink_unsync_page(struct kvm *kvm, struct kvm_mmu_page *sp)
{
WARN_ON(!sp->unsync);
trace_kvm_mmu_sync_page(sp);
sp->unsync = 0;
--kvm->stat.mmu_unsync;
}
static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
struct list_head *invalid_list);
static void kvm_mmu_commit_zap_page(struct kvm *kvm,
struct list_head *invalid_list);
/*
* NOTE: we should pay more attention on the zapped-obsolete page
* (is_obsolete_sp(sp) && sp->role.invalid) when you do hash list walk
* since it has been deleted from active_mmu_pages but still can be found
* at hast list.
*
* for_each_gfn_indirect_valid_sp has skipped that kind of page and
* kvm_mmu_get_page(), the only user of for_each_gfn_sp(), has skipped
* all the obsolete pages.
*/
#define for_each_gfn_sp(_kvm, _sp, _gfn) \
hlist_for_each_entry(_sp, \
&(_kvm)->arch.mmu_page_hash[kvm_page_table_hashfn(_gfn)], hash_link) \
if ((_sp)->gfn != (_gfn)) {} else
#define for_each_gfn_indirect_valid_sp(_kvm, _sp, _gfn) \
for_each_gfn_sp(_kvm, _sp, _gfn) \
if ((_sp)->role.direct || (_sp)->role.invalid) {} else
/* @sp->gfn should be write-protected at the call site */
static int __kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
struct list_head *invalid_list, bool clear_unsync)
{
if (sp->role.cr4_pae != !!is_pae(vcpu)) {
kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
return 1;
}
if (clear_unsync)
kvm_unlink_unsync_page(vcpu->kvm, sp);
if (vcpu->arch.mmu.sync_page(vcpu, sp)) {
kvm_mmu_prepare_zap_page(vcpu->kvm, sp, invalid_list);
return 1;
}
kvm_mmu_flush_tlb(vcpu);
return 0;
}
static int kvm_sync_page_transient(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp)
{
LIST_HEAD(invalid_list);
int ret;
ret = __kvm_sync_page(vcpu, sp, &invalid_list, false);
if (ret)
kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
return ret;
}
#ifdef CONFIG_KVM_MMU_AUDIT
#include "mmu_audit.c"
#else
static void kvm_mmu_audit(struct kvm_vcpu *vcpu, int point) { }
static void mmu_audit_disable(void) { }
#endif
static int kvm_sync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp,
struct list_head *invalid_list)
{
return __kvm_sync_page(vcpu, sp, invalid_list, true);
}
/* @gfn should be write-protected at the call site */
static void kvm_sync_pages(struct kvm_vcpu *vcpu, gfn_t gfn)
{
struct kvm_mmu_page *s;
LIST_HEAD(invalid_list);
bool flush = false;
for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
if (!s->unsync)
continue;
WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
kvm_unlink_unsync_page(vcpu->kvm, s);
if ((s->role.cr4_pae != !!is_pae(vcpu)) ||
(vcpu->arch.mmu.sync_page(vcpu, s))) {
kvm_mmu_prepare_zap_page(vcpu->kvm, s, &invalid_list);
continue;
}
flush = true;
}
kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
if (flush)
kvm_mmu_flush_tlb(vcpu);
}
struct mmu_page_path {
struct kvm_mmu_page *parent[PT64_ROOT_LEVEL-1];
unsigned int idx[PT64_ROOT_LEVEL-1];
};
#define for_each_sp(pvec, sp, parents, i) \
for (i = mmu_pages_next(&pvec, &parents, -1), \
sp = pvec.page[i].sp; \
i < pvec.nr && ({ sp = pvec.page[i].sp; 1;}); \
i = mmu_pages_next(&pvec, &parents, i))
static int mmu_pages_next(struct kvm_mmu_pages *pvec,
struct mmu_page_path *parents,
int i)
{
int n;
for (n = i+1; n < pvec->nr; n++) {
struct kvm_mmu_page *sp = pvec->page[n].sp;
if (sp->role.level == PT_PAGE_TABLE_LEVEL) {
parents->idx[0] = pvec->page[n].idx;
return n;
}
parents->parent[sp->role.level-2] = sp;
parents->idx[sp->role.level-1] = pvec->page[n].idx;
}
return n;
}
static void mmu_pages_clear_parents(struct mmu_page_path *parents)
{
struct kvm_mmu_page *sp;
unsigned int level = 0;
do {
unsigned int idx = parents->idx[level];
sp = parents->parent[level];
if (!sp)
return;
--sp->unsync_children;
WARN_ON((int)sp->unsync_children < 0);
__clear_bit(idx, sp->unsync_child_bitmap);
level++;
} while (level < PT64_ROOT_LEVEL-1 && !sp->unsync_children);
}
static void kvm_mmu_pages_init(struct kvm_mmu_page *parent,
struct mmu_page_path *parents,
struct kvm_mmu_pages *pvec)
{
parents->parent[parent->role.level-1] = NULL;
pvec->nr = 0;
}
static void mmu_sync_children(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *parent)
{
int i;
struct kvm_mmu_page *sp;
struct mmu_page_path parents;
struct kvm_mmu_pages pages;
LIST_HEAD(invalid_list);
kvm_mmu_pages_init(parent, &parents, &pages);
while (mmu_unsync_walk(parent, &pages)) {
bool protected = false;
for_each_sp(pages, sp, parents, i)
protected |= rmap_write_protect(vcpu->kvm, sp->gfn);
if (protected)
kvm_flush_remote_tlbs(vcpu->kvm);
for_each_sp(pages, sp, parents, i) {
kvm_sync_page(vcpu, sp, &invalid_list);
mmu_pages_clear_parents(&parents);
}
kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
cond_resched_lock(&vcpu->kvm->mmu_lock);
kvm_mmu_pages_init(parent, &parents, &pages);
}
}
static void init_shadow_page_table(struct kvm_mmu_page *sp)
{
int i;
for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
sp->spt[i] = 0ull;
}
static void __clear_sp_write_flooding_count(struct kvm_mmu_page *sp)
{
sp->write_flooding_count = 0;
}
static void clear_sp_write_flooding_count(u64 *spte)
{
struct kvm_mmu_page *sp = page_header(__pa(spte));
__clear_sp_write_flooding_count(sp);
}
static bool is_obsolete_sp(struct kvm *kvm, struct kvm_mmu_page *sp)
{
return unlikely(sp->mmu_valid_gen != kvm->arch.mmu_valid_gen);
}
static struct kvm_mmu_page *kvm_mmu_get_page(struct kvm_vcpu *vcpu,
gfn_t gfn,
gva_t gaddr,
unsigned level,
int direct,
unsigned access,
u64 *parent_pte)
{
union kvm_mmu_page_role role;
unsigned quadrant;
struct kvm_mmu_page *sp;
bool need_sync = false;
role = vcpu->arch.mmu.base_role;
role.level = level;
role.direct = direct;
if (role.direct)
role.cr4_pae = 0;
role.access = access;
if (!vcpu->arch.mmu.direct_map
&& vcpu->arch.mmu.root_level <= PT32_ROOT_LEVEL) {
quadrant = gaddr >> (PAGE_SHIFT + (PT64_PT_BITS * level));
quadrant &= (1 << ((PT32_PT_BITS - PT64_PT_BITS) * level)) - 1;
role.quadrant = quadrant;
}
for_each_gfn_sp(vcpu->kvm, sp, gfn) {
if (is_obsolete_sp(vcpu->kvm, sp))
continue;
if (!need_sync && sp->unsync)
need_sync = true;
if (sp->role.word != role.word)
continue;
if (sp->unsync && kvm_sync_page_transient(vcpu, sp))
break;
mmu_page_add_parent_pte(vcpu, sp, parent_pte);
if (sp->unsync_children) {
kvm_make_request(KVM_REQ_MMU_SYNC, vcpu);
kvm_mmu_mark_parents_unsync(sp);
} else if (sp->unsync)
kvm_mmu_mark_parents_unsync(sp);
__clear_sp_write_flooding_count(sp);
trace_kvm_mmu_get_page(sp, false);
return sp;
}
++vcpu->kvm->stat.mmu_cache_miss;
sp = kvm_mmu_alloc_page(vcpu, parent_pte, direct);
if (!sp)
return sp;
sp->gfn = gfn;
sp->role = role;
hlist_add_head(&sp->hash_link,
&vcpu->kvm->arch.mmu_page_hash[kvm_page_table_hashfn(gfn)]);
if (!direct) {
if (rmap_write_protect(vcpu->kvm, gfn))
kvm_flush_remote_tlbs(vcpu->kvm);
if (level > PT_PAGE_TABLE_LEVEL && need_sync)
kvm_sync_pages(vcpu, gfn);
account_shadowed(vcpu->kvm, gfn);
}
sp->mmu_valid_gen = vcpu->kvm->arch.mmu_valid_gen;
init_shadow_page_table(sp);
trace_kvm_mmu_get_page(sp, true);
return sp;
}
static void shadow_walk_init(struct kvm_shadow_walk_iterator *iterator,
struct kvm_vcpu *vcpu, u64 addr)
{
iterator->addr = addr;
iterator->shadow_addr = vcpu->arch.mmu.root_hpa;
iterator->level = vcpu->arch.mmu.shadow_root_level;
if (iterator->level == PT64_ROOT_LEVEL &&
vcpu->arch.mmu.root_level < PT64_ROOT_LEVEL &&
!vcpu->arch.mmu.direct_map)
--iterator->level;
if (iterator->level == PT32E_ROOT_LEVEL) {
iterator->shadow_addr
= vcpu->arch.mmu.pae_root[(addr >> 30) & 3];
iterator->shadow_addr &= PT64_BASE_ADDR_MASK;
--iterator->level;
if (!iterator->shadow_addr)
iterator->level = 0;
}
}
static bool shadow_walk_okay(struct kvm_shadow_walk_iterator *iterator)
{
if (iterator->level < PT_PAGE_TABLE_LEVEL)
return false;
iterator->index = SHADOW_PT_INDEX(iterator->addr, iterator->level);
iterator->sptep = ((u64 *)__va(iterator->shadow_addr)) + iterator->index;
return true;
}
static void __shadow_walk_next(struct kvm_shadow_walk_iterator *iterator,
u64 spte)
{
if (is_last_spte(spte, iterator->level)) {
iterator->level = 0;
return;
}
iterator->shadow_addr = spte & PT64_BASE_ADDR_MASK;
--iterator->level;
}
static void shadow_walk_next(struct kvm_shadow_walk_iterator *iterator)
{
return __shadow_walk_next(iterator, *iterator->sptep);
}
static void link_shadow_page(u64 *sptep, struct kvm_mmu_page *sp, bool accessed)
{
u64 spte;
BUILD_BUG_ON(VMX_EPT_READABLE_MASK != PT_PRESENT_MASK ||
VMX_EPT_WRITABLE_MASK != PT_WRITABLE_MASK);
spte = __pa(sp->spt) | PT_PRESENT_MASK | PT_WRITABLE_MASK |
shadow_user_mask | shadow_x_mask;
if (accessed)
spte |= shadow_accessed_mask;
mmu_spte_set(sptep, spte);
}
static void validate_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep,
unsigned direct_access)
{
if (is_shadow_present_pte(*sptep) && !is_large_pte(*sptep)) {
struct kvm_mmu_page *child;
/*
* For the direct sp, if the guest pte's dirty bit
* changed form clean to dirty, it will corrupt the
* sp's access: allow writable in the read-only sp,
* so we should update the spte at this point to get
* a new sp with the correct access.
*/
child = page_header(*sptep & PT64_BASE_ADDR_MASK);
if (child->role.access == direct_access)
return;
drop_parent_pte(child, sptep);
kvm_flush_remote_tlbs(vcpu->kvm);
}
}
static bool mmu_page_zap_pte(struct kvm *kvm, struct kvm_mmu_page *sp,
u64 *spte)
{
u64 pte;
struct kvm_mmu_page *child;
pte = *spte;
if (is_shadow_present_pte(pte)) {
if (is_last_spte(pte, sp->role.level)) {
drop_spte(kvm, spte);
if (is_large_pte(pte))
--kvm->stat.lpages;
} else {
child = page_header(pte & PT64_BASE_ADDR_MASK);
drop_parent_pte(child, spte);
}
return true;
}
if (is_mmio_spte(pte))
mmu_spte_clear_no_track(spte);
return false;
}
static void kvm_mmu_page_unlink_children(struct kvm *kvm,
struct kvm_mmu_page *sp)
{
unsigned i;
for (i = 0; i < PT64_ENT_PER_PAGE; ++i)
mmu_page_zap_pte(kvm, sp, sp->spt + i);
}
static void kvm_mmu_put_page(struct kvm_mmu_page *sp, u64 *parent_pte)
{
mmu_page_remove_parent_pte(sp, parent_pte);
}
static void kvm_mmu_unlink_parents(struct kvm *kvm, struct kvm_mmu_page *sp)
{
u64 *sptep;
struct rmap_iterator iter;
while ((sptep = rmap_get_first(sp->parent_ptes, &iter)))
drop_parent_pte(sp, sptep);
}
static int mmu_zap_unsync_children(struct kvm *kvm,
struct kvm_mmu_page *parent,
struct list_head *invalid_list)
{
int i, zapped = 0;
struct mmu_page_path parents;
struct kvm_mmu_pages pages;
if (parent->role.level == PT_PAGE_TABLE_LEVEL)
return 0;
kvm_mmu_pages_init(parent, &parents, &pages);
while (mmu_unsync_walk(parent, &pages)) {
struct kvm_mmu_page *sp;
for_each_sp(pages, sp, parents, i) {
kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
mmu_pages_clear_parents(&parents);
zapped++;
}
kvm_mmu_pages_init(parent, &parents, &pages);
}
return zapped;
}
static int kvm_mmu_prepare_zap_page(struct kvm *kvm, struct kvm_mmu_page *sp,
struct list_head *invalid_list)
{
int ret;
trace_kvm_mmu_prepare_zap_page(sp);
++kvm->stat.mmu_shadow_zapped;
ret = mmu_zap_unsync_children(kvm, sp, invalid_list);
kvm_mmu_page_unlink_children(kvm, sp);
kvm_mmu_unlink_parents(kvm, sp);
if (!sp->role.invalid && !sp->role.direct)
unaccount_shadowed(kvm, sp->gfn);
if (sp->unsync)
kvm_unlink_unsync_page(kvm, sp);
if (!sp->root_count) {
/* Count self */
ret++;
list_move(&sp->link, invalid_list);
kvm_mod_used_mmu_pages(kvm, -1);
} else {
list_move(&sp->link, &kvm->arch.active_mmu_pages);
/*
* The obsolete pages can not be used on any vcpus.
* See the comments in kvm_mmu_invalidate_zap_all_pages().
*/
if (!sp->role.invalid && !is_obsolete_sp(kvm, sp))
kvm_reload_remote_mmus(kvm);
}
sp->role.invalid = 1;
return ret;
}
static void kvm_mmu_commit_zap_page(struct kvm *kvm,
struct list_head *invalid_list)
{
struct kvm_mmu_page *sp, *nsp;
if (list_empty(invalid_list))
return;
/*
* wmb: make sure everyone sees our modifications to the page tables
* rmb: make sure we see changes to vcpu->mode
*/
smp_mb();
/*
* Wait for all vcpus to exit guest mode and/or lockless shadow
* page table walks.
*/
kvm_flush_remote_tlbs(kvm);
list_for_each_entry_safe(sp, nsp, invalid_list, link) {
WARN_ON(!sp->role.invalid || sp->root_count);
kvm_mmu_free_page(sp);
}
}
static bool prepare_zap_oldest_mmu_page(struct kvm *kvm,
struct list_head *invalid_list)
{
struct kvm_mmu_page *sp;
if (list_empty(&kvm->arch.active_mmu_pages))
return false;
sp = list_entry(kvm->arch.active_mmu_pages.prev,
struct kvm_mmu_page, link);
kvm_mmu_prepare_zap_page(kvm, sp, invalid_list);
return true;
}
/*
* Changing the number of mmu pages allocated to the vm
* Note: if goal_nr_mmu_pages is too small, you will get dead lock
*/
void kvm_mmu_change_mmu_pages(struct kvm *kvm, unsigned int goal_nr_mmu_pages)
{
LIST_HEAD(invalid_list);
spin_lock(&kvm->mmu_lock);
if (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages) {
/* Need to free some mmu pages to achieve the goal. */
while (kvm->arch.n_used_mmu_pages > goal_nr_mmu_pages)
if (!prepare_zap_oldest_mmu_page(kvm, &invalid_list))
break;
kvm_mmu_commit_zap_page(kvm, &invalid_list);
goal_nr_mmu_pages = kvm->arch.n_used_mmu_pages;
}
kvm->arch.n_max_mmu_pages = goal_nr_mmu_pages;
spin_unlock(&kvm->mmu_lock);
}
int kvm_mmu_unprotect_page(struct kvm *kvm, gfn_t gfn)
{
struct kvm_mmu_page *sp;
LIST_HEAD(invalid_list);
int r;
pgprintk("%s: looking for gfn %llx\n", __func__, gfn);
r = 0;
spin_lock(&kvm->mmu_lock);
for_each_gfn_indirect_valid_sp(kvm, sp, gfn) {
pgprintk("%s: gfn %llx role %x\n", __func__, gfn,
sp->role.word);
r = 1;
kvm_mmu_prepare_zap_page(kvm, sp, &invalid_list);
}
kvm_mmu_commit_zap_page(kvm, &invalid_list);
spin_unlock(&kvm->mmu_lock);
return r;
}
EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page);
/*
* The function is based on mtrr_type_lookup() in
* arch/x86/kernel/cpu/mtrr/generic.c
*/
static int get_mtrr_type(struct mtrr_state_type *mtrr_state,
u64 start, u64 end)
{
int i;
u64 base, mask;
u8 prev_match, curr_match;
int num_var_ranges = KVM_NR_VAR_MTRR;
if (!mtrr_state->enabled)
return 0xFF;
/* Make end inclusive end, instead of exclusive */
end--;
/* Look in fixed ranges. Just return the type as per start */
if (mtrr_state->have_fixed && (start < 0x100000)) {
int idx;
if (start < 0x80000) {
idx = 0;
idx += (start >> 16);
return mtrr_state->fixed_ranges[idx];
} else if (start < 0xC0000) {
idx = 1 * 8;
idx += ((start - 0x80000) >> 14);
return mtrr_state->fixed_ranges[idx];
} else if (start < 0x1000000) {
idx = 3 * 8;
idx += ((start - 0xC0000) >> 12);
return mtrr_state->fixed_ranges[idx];
}
}
/*
* Look in variable ranges
* Look of multiple ranges matching this address and pick type
* as per MTRR precedence
*/
if (!(mtrr_state->enabled & 2))
return mtrr_state->def_type;
prev_match = 0xFF;
for (i = 0; i < num_var_ranges; ++i) {
unsigned short start_state, end_state;
if (!(mtrr_state->var_ranges[i].mask_lo & (1 << 11)))
continue;
base = (((u64)mtrr_state->var_ranges[i].base_hi) << 32) +
(mtrr_state->var_ranges[i].base_lo & PAGE_MASK);
mask = (((u64)mtrr_state->var_ranges[i].mask_hi) << 32) +
(mtrr_state->var_ranges[i].mask_lo & PAGE_MASK);
start_state = ((start & mask) == (base & mask));
end_state = ((end & mask) == (base & mask));
if (start_state != end_state)
return 0xFE;
if ((start & mask) != (base & mask))
continue;
curr_match = mtrr_state->var_ranges[i].base_lo & 0xff;
if (prev_match == 0xFF) {
prev_match = curr_match;
continue;
}
if (prev_match == MTRR_TYPE_UNCACHABLE ||
curr_match == MTRR_TYPE_UNCACHABLE)
return MTRR_TYPE_UNCACHABLE;
if ((prev_match == MTRR_TYPE_WRBACK &&
curr_match == MTRR_TYPE_WRTHROUGH) ||
(prev_match == MTRR_TYPE_WRTHROUGH &&
curr_match == MTRR_TYPE_WRBACK)) {
prev_match = MTRR_TYPE_WRTHROUGH;
curr_match = MTRR_TYPE_WRTHROUGH;
}
if (prev_match != curr_match)
return MTRR_TYPE_UNCACHABLE;
}
if (prev_match != 0xFF)
return prev_match;
return mtrr_state->def_type;
}
u8 kvm_get_guest_memory_type(struct kvm_vcpu *vcpu, gfn_t gfn)
{
u8 mtrr;
mtrr = get_mtrr_type(&vcpu->arch.mtrr_state, gfn << PAGE_SHIFT,
(gfn << PAGE_SHIFT) + PAGE_SIZE);
if (mtrr == 0xfe || mtrr == 0xff)
mtrr = MTRR_TYPE_WRBACK;
return mtrr;
}
EXPORT_SYMBOL_GPL(kvm_get_guest_memory_type);
static void __kvm_unsync_page(struct kvm_vcpu *vcpu, struct kvm_mmu_page *sp)
{
trace_kvm_mmu_unsync_page(sp);
++vcpu->kvm->stat.mmu_unsync;
sp->unsync = 1;
kvm_mmu_mark_parents_unsync(sp);
}
static void kvm_unsync_pages(struct kvm_vcpu *vcpu, gfn_t gfn)
{
struct kvm_mmu_page *s;
for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
if (s->unsync)
continue;
WARN_ON(s->role.level != PT_PAGE_TABLE_LEVEL);
__kvm_unsync_page(vcpu, s);
}
}
static int mmu_need_write_protect(struct kvm_vcpu *vcpu, gfn_t gfn,
bool can_unsync)
{
struct kvm_mmu_page *s;
bool need_unsync = false;
for_each_gfn_indirect_valid_sp(vcpu->kvm, s, gfn) {
if (!can_unsync)
return 1;
if (s->role.level != PT_PAGE_TABLE_LEVEL)
return 1;
if (!s->unsync)
need_unsync = true;
}
if (need_unsync)
kvm_unsync_pages(vcpu, gfn);
return 0;
}
static int set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
unsigned pte_access, int level,
gfn_t gfn, pfn_t pfn, bool speculative,
bool can_unsync, bool host_writable)
{
u64 spte;
int ret = 0;
if (set_mmio_spte(vcpu->kvm, sptep, gfn, pfn, pte_access))
return 0;
spte = PT_PRESENT_MASK;
if (!speculative)
spte |= shadow_accessed_mask;
if (pte_access & ACC_EXEC_MASK)
spte |= shadow_x_mask;
else
spte |= shadow_nx_mask;
if (pte_access & ACC_USER_MASK)
spte |= shadow_user_mask;
if (level > PT_PAGE_TABLE_LEVEL)
spte |= PT_PAGE_SIZE_MASK;
if (tdp_enabled)
spte |= kvm_x86_ops->get_mt_mask(vcpu, gfn,
kvm_is_mmio_pfn(pfn));
if (host_writable)
spte |= SPTE_HOST_WRITEABLE;
else
pte_access &= ~ACC_WRITE_MASK;
spte |= (u64)pfn << PAGE_SHIFT;
if (pte_access & ACC_WRITE_MASK) {
/*
* Other vcpu creates new sp in the window between
* mapping_level() and acquiring mmu-lock. We can
* allow guest to retry the access, the mapping can
* be fixed if guest refault.
*/
if (level > PT_PAGE_TABLE_LEVEL &&
has_wrprotected_page(vcpu->kvm, gfn, level))
goto done;
spte |= PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE;
/*
* Optimization: for pte sync, if spte was writable the hash
* lookup is unnecessary (and expensive). Write protection
* is responsibility of mmu_get_page / kvm_sync_page.
* Same reasoning can be applied to dirty page accounting.
*/
if (!can_unsync && is_writable_pte(*sptep))
goto set_pte;
if (mmu_need_write_protect(vcpu, gfn, can_unsync)) {
pgprintk("%s: found shadow page for %llx, marking ro\n",
__func__, gfn);
ret = 1;
pte_access &= ~ACC_WRITE_MASK;
spte &= ~(PT_WRITABLE_MASK | SPTE_MMU_WRITEABLE);
}
}
if (pte_access & ACC_WRITE_MASK)
mark_page_dirty(vcpu->kvm, gfn);
set_pte:
if (mmu_spte_update(sptep, spte))
kvm_flush_remote_tlbs(vcpu->kvm);
done:
return ret;
}
static void mmu_set_spte(struct kvm_vcpu *vcpu, u64 *sptep,
unsigned pte_access, int write_fault, int *emulate,
int level, gfn_t gfn, pfn_t pfn, bool speculative,
bool host_writable)
{
int was_rmapped = 0;
int rmap_count;
pgprintk("%s: spte %llx write_fault %d gfn %llx\n", __func__,
*sptep, write_fault, gfn);
if (is_rmap_spte(*sptep)) {
/*
* If we overwrite a PTE page pointer with a 2MB PMD, unlink
* the parent of the now unreachable PTE.
*/
if (level > PT_PAGE_TABLE_LEVEL &&
!is_large_pte(*sptep)) {
struct kvm_mmu_page *child;
u64 pte = *sptep;
child = page_header(pte & PT64_BASE_ADDR_MASK);
drop_parent_pte(child, sptep);
kvm_flush_remote_tlbs(vcpu->kvm);
} else if (pfn != spte_to_pfn(*sptep)) {
pgprintk("hfn old %llx new %llx\n",
spte_to_pfn(*sptep), pfn);
drop_spte(vcpu->kvm, sptep);
kvm_flush_remote_tlbs(vcpu->kvm);
} else
was_rmapped = 1;
}
if (set_spte(vcpu, sptep, pte_access, level, gfn, pfn, speculative,
true, host_writable)) {
if (write_fault)
*emulate = 1;
kvm_mmu_flush_tlb(vcpu);
}
if (unlikely(is_mmio_spte(*sptep) && emulate))
*emulate = 1;
pgprintk("%s: setting spte %llx\n", __func__, *sptep);
pgprintk("instantiating %s PTE (%s) at %llx (%llx) addr %p\n",
is_large_pte(*sptep)? "2MB" : "4kB",
*sptep & PT_PRESENT_MASK ?"RW":"R", gfn,
*sptep, sptep);
if (!was_rmapped && is_large_pte(*sptep))
++vcpu->kvm->stat.lpages;
if (is_shadow_present_pte(*sptep)) {
if (!was_rmapped) {
rmap_count = rmap_add(vcpu, sptep, gfn);
if (rmap_count > RMAP_RECYCLE_THRESHOLD)
rmap_recycle(vcpu, sptep, gfn);
}
}
kvm_release_pfn_clean(pfn);
}
static void nonpaging_new_cr3(struct kvm_vcpu *vcpu)
{
mmu_free_roots(vcpu);
}
static pfn_t pte_prefetch_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn,
bool no_dirty_log)
{
struct kvm_memory_slot *slot;
slot = gfn_to_memslot_dirty_bitmap(vcpu, gfn, no_dirty_log);
if (!slot)
return KVM_PFN_ERR_FAULT;
return gfn_to_pfn_memslot_atomic(slot, gfn);
}
static int direct_pte_prefetch_many(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp,
u64 *start, u64 *end)
{
struct page *pages[PTE_PREFETCH_NUM];
unsigned access = sp->role.access;
int i, ret;
gfn_t gfn;
gfn = kvm_mmu_page_get_gfn(sp, start - sp->spt);
if (!gfn_to_memslot_dirty_bitmap(vcpu, gfn, access & ACC_WRITE_MASK))
return -1;
ret = gfn_to_page_many_atomic(vcpu->kvm, gfn, pages, end - start);
if (ret <= 0)
return -1;
for (i = 0; i < ret; i++, gfn++, start++)
mmu_set_spte(vcpu, start, access, 0, NULL,
sp->role.level, gfn, page_to_pfn(pages[i]),
true, true);
return 0;
}
static void __direct_pte_prefetch(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp, u64 *sptep)
{
u64 *spte, *start = NULL;
int i;
WARN_ON(!sp->role.direct);
i = (sptep - sp->spt) & ~(PTE_PREFETCH_NUM - 1);
spte = sp->spt + i;
for (i = 0; i < PTE_PREFETCH_NUM; i++, spte++) {
if (is_shadow_present_pte(*spte) || spte == sptep) {
if (!start)
continue;
if (direct_pte_prefetch_many(vcpu, sp, start, spte) < 0)
break;
start = NULL;
} else if (!start)
start = spte;
}
}
static void direct_pte_prefetch(struct kvm_vcpu *vcpu, u64 *sptep)
{
struct kvm_mmu_page *sp;
/*
* Since it's no accessed bit on EPT, it's no way to
* distinguish between actually accessed translations
* and prefetched, so disable pte prefetch if EPT is
* enabled.
*/
if (!shadow_accessed_mask)
return;
sp = page_header(__pa(sptep));
if (sp->role.level > PT_PAGE_TABLE_LEVEL)
return;
__direct_pte_prefetch(vcpu, sp, sptep);
}
static int __direct_map(struct kvm_vcpu *vcpu, gpa_t v, int write,
int map_writable, int level, gfn_t gfn, pfn_t pfn,
bool prefault)
{
struct kvm_shadow_walk_iterator iterator;
struct kvm_mmu_page *sp;
int emulate = 0;
gfn_t pseudo_gfn;
for_each_shadow_entry(vcpu, (u64)gfn << PAGE_SHIFT, iterator) {
if (iterator.level == level) {
mmu_set_spte(vcpu, iterator.sptep, ACC_ALL,
write, &emulate, level, gfn, pfn,
prefault, map_writable);
direct_pte_prefetch(vcpu, iterator.sptep);
++vcpu->stat.pf_fixed;
break;
}
if (!is_shadow_present_pte(*iterator.sptep)) {
u64 base_addr = iterator.addr;
base_addr &= PT64_LVL_ADDR_MASK(iterator.level);
pseudo_gfn = base_addr >> PAGE_SHIFT;
sp = kvm_mmu_get_page(vcpu, pseudo_gfn, iterator.addr,
iterator.level - 1,
1, ACC_ALL, iterator.sptep);
link_shadow_page(iterator.sptep, sp, true);
}
}
return emulate;
}
static void kvm_send_hwpoison_signal(unsigned long address, struct task_struct *tsk)
{
siginfo_t info;
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_MCEERR_AR;
info.si_addr = (void __user *)address;
info.si_addr_lsb = PAGE_SHIFT;
send_sig_info(SIGBUS, &info, tsk);
}
static int kvm_handle_bad_page(struct kvm_vcpu *vcpu, gfn_t gfn, pfn_t pfn)
{
/*
* Do not cache the mmio info caused by writing the readonly gfn
* into the spte otherwise read access on readonly gfn also can
* caused mmio page fault and treat it as mmio access.
* Return 1 to tell kvm to emulate it.
*/
if (pfn == KVM_PFN_ERR_RO_FAULT)
return 1;
if (pfn == KVM_PFN_ERR_HWPOISON) {
kvm_send_hwpoison_signal(gfn_to_hva(vcpu->kvm, gfn), current);
return 0;
}
return -EFAULT;
}
static void transparent_hugepage_adjust(struct kvm_vcpu *vcpu,
gfn_t *gfnp, pfn_t *pfnp, int *levelp)
{
pfn_t pfn = *pfnp;
gfn_t gfn = *gfnp;
int level = *levelp;
/*
* Check if it's a transparent hugepage. If this would be an
* hugetlbfs page, level wouldn't be set to
* PT_PAGE_TABLE_LEVEL and there would be no adjustment done
* here.
*/
if (!is_error_noslot_pfn(pfn) && !kvm_is_mmio_pfn(pfn) &&
level == PT_PAGE_TABLE_LEVEL &&
PageTransCompound(pfn_to_page(pfn)) &&
!has_wrprotected_page(vcpu->kvm, gfn, PT_DIRECTORY_LEVEL)) {
unsigned long mask;
/*
* mmu_notifier_retry was successful and we hold the
* mmu_lock here, so the pmd can't become splitting
* from under us, and in turn
* __split_huge_page_refcount() can't run from under
* us and we can safely transfer the refcount from
* PG_tail to PG_head as we switch the pfn to tail to
* head.
*/
*levelp = level = PT_DIRECTORY_LEVEL;
mask = KVM_PAGES_PER_HPAGE(level) - 1;
VM_BUG_ON((gfn & mask) != (pfn & mask));
if (pfn & mask) {
gfn &= ~mask;
*gfnp = gfn;
kvm_release_pfn_clean(pfn);
pfn &= ~mask;
kvm_get_pfn(pfn);
*pfnp = pfn;
}
}
}
static bool handle_abnormal_pfn(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn,
pfn_t pfn, unsigned access, int *ret_val)
{
bool ret = true;
/* The pfn is invalid, report the error! */
if (unlikely(is_error_pfn(pfn))) {
*ret_val = kvm_handle_bad_page(vcpu, gfn, pfn);
goto exit;
}
if (unlikely(is_noslot_pfn(pfn)))
vcpu_cache_mmio_info(vcpu, gva, gfn, access);
ret = false;
exit:
return ret;
}
static bool page_fault_can_be_fast(struct kvm_vcpu *vcpu, u32 error_code)
{
/*
* Do not fix the mmio spte with invalid generation number which
* need to be updated by slow page fault path.
*/
if (unlikely(error_code & PFERR_RSVD_MASK))
return false;
/*
* #PF can be fast only if the shadow page table is present and it
* is caused by write-protect, that means we just need change the
* W bit of the spte which can be done out of mmu-lock.
*/
if (!(error_code & PFERR_PRESENT_MASK) ||
!(error_code & PFERR_WRITE_MASK))
return false;
return true;
}
static bool
fast_pf_fix_direct_spte(struct kvm_vcpu *vcpu, u64 *sptep, u64 spte)
{
struct kvm_mmu_page *sp = page_header(__pa(sptep));
gfn_t gfn;
WARN_ON(!sp->role.direct);
/*
* The gfn of direct spte is stable since it is calculated
* by sp->gfn.
*/
gfn = kvm_mmu_page_get_gfn(sp, sptep - sp->spt);
if (cmpxchg64(sptep, spte, spte | PT_WRITABLE_MASK) == spte)
mark_page_dirty(vcpu->kvm, gfn);
return true;
}
/*
* Return value:
* - true: let the vcpu to access on the same address again.
* - false: let the real page fault path to fix it.
*/
static bool fast_page_fault(struct kvm_vcpu *vcpu, gva_t gva, int level,
u32 error_code)
{
struct kvm_shadow_walk_iterator iterator;
bool ret = false;
u64 spte = 0ull;
if (!page_fault_can_be_fast(vcpu, error_code))
return false;
walk_shadow_page_lockless_begin(vcpu);
for_each_shadow_entry_lockless(vcpu, gva, iterator, spte)
if (!is_shadow_present_pte(spte) || iterator.level < level)
break;
/*
* If the mapping has been changed, let the vcpu fault on the
* same address again.
*/
if (!is_rmap_spte(spte)) {
ret = true;
goto exit;
}
if (!is_last_spte(spte, level))
goto exit;
/*
* Check if it is a spurious fault caused by TLB lazily flushed.
*
* Need not check the access of upper level table entries since
* they are always ACC_ALL.
*/
if (is_writable_pte(spte)) {
ret = true;
goto exit;
}
/*
* Currently, to simplify the code, only the spte write-protected
* by dirty-log can be fast fixed.
*/
if (!spte_is_locklessly_modifiable(spte))
goto exit;
/*
* Currently, fast page fault only works for direct mapping since
* the gfn is not stable for indirect shadow page.
* See Documentation/virtual/kvm/locking.txt to get more detail.
*/
ret = fast_pf_fix_direct_spte(vcpu, iterator.sptep, spte);
exit:
trace_fast_page_fault(vcpu, gva, error_code, iterator.sptep,
spte, ret);
walk_shadow_page_lockless_end(vcpu);
return ret;
}
static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
gva_t gva, pfn_t *pfn, bool write, bool *writable);
static void make_mmu_pages_available(struct kvm_vcpu *vcpu);
static int nonpaging_map(struct kvm_vcpu *vcpu, gva_t v, u32 error_code,
gfn_t gfn, bool prefault)
{
int r;
int level;
int force_pt_level;
pfn_t pfn;
unsigned long mmu_seq;
bool map_writable, write = error_code & PFERR_WRITE_MASK;
force_pt_level = mapping_level_dirty_bitmap(vcpu, gfn);
if (likely(!force_pt_level)) {
level = mapping_level(vcpu, gfn);
/*
* This path builds a PAE pagetable - so we can map
* 2mb pages at maximum. Therefore check if the level
* is larger than that.
*/
if (level > PT_DIRECTORY_LEVEL)
level = PT_DIRECTORY_LEVEL;
gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
} else
level = PT_PAGE_TABLE_LEVEL;
if (fast_page_fault(vcpu, v, level, error_code))
return 0;
mmu_seq = vcpu->kvm->mmu_notifier_seq;
smp_rmb();
if (try_async_pf(vcpu, prefault, gfn, v, &pfn, write, &map_writable))
return 0;
if (handle_abnormal_pfn(vcpu, v, gfn, pfn, ACC_ALL, &r))
return r;
spin_lock(&vcpu->kvm->mmu_lock);
if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
goto out_unlock;
make_mmu_pages_available(vcpu);
if (likely(!force_pt_level))
transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
r = __direct_map(vcpu, v, write, map_writable, level, gfn, pfn,
prefault);
spin_unlock(&vcpu->kvm->mmu_lock);
return r;
out_unlock:
spin_unlock(&vcpu->kvm->mmu_lock);
kvm_release_pfn_clean(pfn);
return 0;
}
static void mmu_free_roots(struct kvm_vcpu *vcpu)
{
int i;
struct kvm_mmu_page *sp;
LIST_HEAD(invalid_list);
if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
return;
if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL &&
(vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL ||
vcpu->arch.mmu.direct_map)) {
hpa_t root = vcpu->arch.mmu.root_hpa;
spin_lock(&vcpu->kvm->mmu_lock);
sp = page_header(root);
--sp->root_count;
if (!sp->root_count && sp->role.invalid) {
kvm_mmu_prepare_zap_page(vcpu->kvm, sp, &invalid_list);
kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
}
spin_unlock(&vcpu->kvm->mmu_lock);
vcpu->arch.mmu.root_hpa = INVALID_PAGE;
return;
}
spin_lock(&vcpu->kvm->mmu_lock);
for (i = 0; i < 4; ++i) {
hpa_t root = vcpu->arch.mmu.pae_root[i];
if (root) {
root &= PT64_BASE_ADDR_MASK;
sp = page_header(root);
--sp->root_count;
if (!sp->root_count && sp->role.invalid)
kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
&invalid_list);
}
vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
}
kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
spin_unlock(&vcpu->kvm->mmu_lock);
vcpu->arch.mmu.root_hpa = INVALID_PAGE;
}
static int mmu_check_root(struct kvm_vcpu *vcpu, gfn_t root_gfn)
{
int ret = 0;
if (!kvm_is_visible_gfn(vcpu->kvm, root_gfn)) {
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
ret = 1;
}
return ret;
}
static int mmu_alloc_direct_roots(struct kvm_vcpu *vcpu)
{
struct kvm_mmu_page *sp;
unsigned i;
if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
spin_lock(&vcpu->kvm->mmu_lock);
make_mmu_pages_available(vcpu);
sp = kvm_mmu_get_page(vcpu, 0, 0, PT64_ROOT_LEVEL,
1, ACC_ALL, NULL);
++sp->root_count;
spin_unlock(&vcpu->kvm->mmu_lock);
vcpu->arch.mmu.root_hpa = __pa(sp->spt);
} else if (vcpu->arch.mmu.shadow_root_level == PT32E_ROOT_LEVEL) {
for (i = 0; i < 4; ++i) {
hpa_t root = vcpu->arch.mmu.pae_root[i];
ASSERT(!VALID_PAGE(root));
spin_lock(&vcpu->kvm->mmu_lock);
make_mmu_pages_available(vcpu);
sp = kvm_mmu_get_page(vcpu, i << (30 - PAGE_SHIFT),
i << 30,
PT32_ROOT_LEVEL, 1, ACC_ALL,
NULL);
root = __pa(sp->spt);
++sp->root_count;
spin_unlock(&vcpu->kvm->mmu_lock);
vcpu->arch.mmu.pae_root[i] = root | PT_PRESENT_MASK;
}
vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
} else
BUG();
return 0;
}
static int mmu_alloc_shadow_roots(struct kvm_vcpu *vcpu)
{
struct kvm_mmu_page *sp;
u64 pdptr, pm_mask;
gfn_t root_gfn;
int i;
root_gfn = vcpu->arch.mmu.get_cr3(vcpu) >> PAGE_SHIFT;
if (mmu_check_root(vcpu, root_gfn))
return 1;
/*
* Do we shadow a long mode page table? If so we need to
* write-protect the guests page table root.
*/
if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
hpa_t root = vcpu->arch.mmu.root_hpa;
ASSERT(!VALID_PAGE(root));
spin_lock(&vcpu->kvm->mmu_lock);
make_mmu_pages_available(vcpu);
sp = kvm_mmu_get_page(vcpu, root_gfn, 0, PT64_ROOT_LEVEL,
0, ACC_ALL, NULL);
root = __pa(sp->spt);
++sp->root_count;
spin_unlock(&vcpu->kvm->mmu_lock);
vcpu->arch.mmu.root_hpa = root;
return 0;
}
/*
* We shadow a 32 bit page table. This may be a legacy 2-level
* or a PAE 3-level page table. In either case we need to be aware that
* the shadow page table may be a PAE or a long mode page table.
*/
pm_mask = PT_PRESENT_MASK;
if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL)
pm_mask |= PT_ACCESSED_MASK | PT_WRITABLE_MASK | PT_USER_MASK;
for (i = 0; i < 4; ++i) {
hpa_t root = vcpu->arch.mmu.pae_root[i];
ASSERT(!VALID_PAGE(root));
if (vcpu->arch.mmu.root_level == PT32E_ROOT_LEVEL) {
pdptr = vcpu->arch.mmu.get_pdptr(vcpu, i);
if (!is_present_gpte(pdptr)) {
vcpu->arch.mmu.pae_root[i] = 0;
continue;
}
root_gfn = pdptr >> PAGE_SHIFT;
if (mmu_check_root(vcpu, root_gfn))
return 1;
}
spin_lock(&vcpu->kvm->mmu_lock);
make_mmu_pages_available(vcpu);
sp = kvm_mmu_get_page(vcpu, root_gfn, i << 30,
PT32_ROOT_LEVEL, 0,
ACC_ALL, NULL);
root = __pa(sp->spt);
++sp->root_count;
spin_unlock(&vcpu->kvm->mmu_lock);
vcpu->arch.mmu.pae_root[i] = root | pm_mask;
}
vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.pae_root);
/*
* If we shadow a 32 bit page table with a long mode page
* table we enter this path.
*/
if (vcpu->arch.mmu.shadow_root_level == PT64_ROOT_LEVEL) {
if (vcpu->arch.mmu.lm_root == NULL) {
/*
* The additional page necessary for this is only
* allocated on demand.
*/
u64 *lm_root;
lm_root = (void*)get_zeroed_page(GFP_KERNEL);
if (lm_root == NULL)
return 1;
lm_root[0] = __pa(vcpu->arch.mmu.pae_root) | pm_mask;
vcpu->arch.mmu.lm_root = lm_root;
}
vcpu->arch.mmu.root_hpa = __pa(vcpu->arch.mmu.lm_root);
}
return 0;
}
static int mmu_alloc_roots(struct kvm_vcpu *vcpu)
{
if (vcpu->arch.mmu.direct_map)
return mmu_alloc_direct_roots(vcpu);
else
return mmu_alloc_shadow_roots(vcpu);
}
static void mmu_sync_roots(struct kvm_vcpu *vcpu)
{
int i;
struct kvm_mmu_page *sp;
if (vcpu->arch.mmu.direct_map)
return;
if (!VALID_PAGE(vcpu->arch.mmu.root_hpa))
return;
vcpu_clear_mmio_info(vcpu, ~0ul);
kvm_mmu_audit(vcpu, AUDIT_PRE_SYNC);
if (vcpu->arch.mmu.root_level == PT64_ROOT_LEVEL) {
hpa_t root = vcpu->arch.mmu.root_hpa;
sp = page_header(root);
mmu_sync_children(vcpu, sp);
kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
return;
}
for (i = 0; i < 4; ++i) {
hpa_t root = vcpu->arch.mmu.pae_root[i];
if (root && VALID_PAGE(root)) {
root &= PT64_BASE_ADDR_MASK;
sp = page_header(root);
mmu_sync_children(vcpu, sp);
}
}
kvm_mmu_audit(vcpu, AUDIT_POST_SYNC);
}
void kvm_mmu_sync_roots(struct kvm_vcpu *vcpu)
{
spin_lock(&vcpu->kvm->mmu_lock);
mmu_sync_roots(vcpu);
spin_unlock(&vcpu->kvm->mmu_lock);
}
EXPORT_SYMBOL_GPL(kvm_mmu_sync_roots);
static gpa_t nonpaging_gva_to_gpa(struct kvm_vcpu *vcpu, gva_t vaddr,
u32 access, struct x86_exception *exception)
{
if (exception)
exception->error_code = 0;
return vaddr;
}
static gpa_t nonpaging_gva_to_gpa_nested(struct kvm_vcpu *vcpu, gva_t vaddr,
u32 access,
struct x86_exception *exception)
{
if (exception)
exception->error_code = 0;
return vcpu->arch.nested_mmu.translate_gpa(vcpu, vaddr, access);
}
static bool quickly_check_mmio_pf(struct kvm_vcpu *vcpu, u64 addr, bool direct)
{
if (direct)
return vcpu_match_mmio_gpa(vcpu, addr);
return vcpu_match_mmio_gva(vcpu, addr);
}
/*
* On direct hosts, the last spte is only allows two states
* for mmio page fault:
* - It is the mmio spte
* - It is zapped or it is being zapped.
*
* This function completely checks the spte when the last spte
* is not the mmio spte.
*/
static bool check_direct_spte_mmio_pf(u64 spte)
{
return __check_direct_spte_mmio_pf(spte);
}
static u64 walk_shadow_page_get_mmio_spte(struct kvm_vcpu *vcpu, u64 addr)
{
struct kvm_shadow_walk_iterator iterator;
u64 spte = 0ull;
walk_shadow_page_lockless_begin(vcpu);
for_each_shadow_entry_lockless(vcpu, addr, iterator, spte)
if (!is_shadow_present_pte(spte))
break;
walk_shadow_page_lockless_end(vcpu);
return spte;
}
int handle_mmio_page_fault_common(struct kvm_vcpu *vcpu, u64 addr, bool direct)
{
u64 spte;
if (quickly_check_mmio_pf(vcpu, addr, direct))
return RET_MMIO_PF_EMULATE;
spte = walk_shadow_page_get_mmio_spte(vcpu, addr);
if (is_mmio_spte(spte)) {
gfn_t gfn = get_mmio_spte_gfn(spte);
unsigned access = get_mmio_spte_access(spte);
if (!check_mmio_spte(vcpu->kvm, spte))
return RET_MMIO_PF_INVALID;
if (direct)
addr = 0;
trace_handle_mmio_page_fault(addr, gfn, access);
vcpu_cache_mmio_info(vcpu, addr, gfn, access);
return RET_MMIO_PF_EMULATE;
}
/*
* It's ok if the gva is remapped by other cpus on shadow guest,
* it's a BUG if the gfn is not a mmio page.
*/
if (direct && !check_direct_spte_mmio_pf(spte))
return RET_MMIO_PF_BUG;
/*
* If the page table is zapped by other cpus, let CPU fault again on
* the address.
*/
return RET_MMIO_PF_RETRY;
}
EXPORT_SYMBOL_GPL(handle_mmio_page_fault_common);
static int handle_mmio_page_fault(struct kvm_vcpu *vcpu, u64 addr,
u32 error_code, bool direct)
{
int ret;
ret = handle_mmio_page_fault_common(vcpu, addr, direct);
WARN_ON(ret == RET_MMIO_PF_BUG);
return ret;
}
static int nonpaging_page_fault(struct kvm_vcpu *vcpu, gva_t gva,
u32 error_code, bool prefault)
{
gfn_t gfn;
int r;
pgprintk("%s: gva %lx error %x\n", __func__, gva, error_code);
if (unlikely(error_code & PFERR_RSVD_MASK)) {
r = handle_mmio_page_fault(vcpu, gva, error_code, true);
if (likely(r != RET_MMIO_PF_INVALID))
return r;
}
r = mmu_topup_memory_caches(vcpu);
if (r)
return r;
ASSERT(vcpu);
ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
gfn = gva >> PAGE_SHIFT;
return nonpaging_map(vcpu, gva & PAGE_MASK,
error_code, gfn, prefault);
}
static int kvm_arch_setup_async_pf(struct kvm_vcpu *vcpu, gva_t gva, gfn_t gfn)
{
struct kvm_arch_async_pf arch;
arch.token = (vcpu->arch.apf.id++ << 12) | vcpu->vcpu_id;
arch.gfn = gfn;
arch.direct_map = vcpu->arch.mmu.direct_map;
arch.cr3 = vcpu->arch.mmu.get_cr3(vcpu);
return kvm_setup_async_pf(vcpu, gva, gfn, &arch);
}
static bool can_do_async_pf(struct kvm_vcpu *vcpu)
{
if (unlikely(!irqchip_in_kernel(vcpu->kvm) ||
kvm_event_needs_reinjection(vcpu)))
return false;
return kvm_x86_ops->interrupt_allowed(vcpu);
}
static bool try_async_pf(struct kvm_vcpu *vcpu, bool prefault, gfn_t gfn,
gva_t gva, pfn_t *pfn, bool write, bool *writable)
{
bool async;
*pfn = gfn_to_pfn_async(vcpu->kvm, gfn, &async, write, writable);
if (!async)
return false; /* *pfn has correct page already */
if (!prefault && can_do_async_pf(vcpu)) {
trace_kvm_try_async_get_page(gva, gfn);
if (kvm_find_async_pf_gfn(vcpu, gfn)) {
trace_kvm_async_pf_doublefault(gva, gfn);
kvm_make_request(KVM_REQ_APF_HALT, vcpu);
return true;
} else if (kvm_arch_setup_async_pf(vcpu, gva, gfn))
return true;
}
*pfn = gfn_to_pfn_prot(vcpu->kvm, gfn, write, writable);
return false;
}
static int tdp_page_fault(struct kvm_vcpu *vcpu, gva_t gpa, u32 error_code,
bool prefault)
{
pfn_t pfn;
int r;
int level;
int force_pt_level;
gfn_t gfn = gpa >> PAGE_SHIFT;
unsigned long mmu_seq;
int write = error_code & PFERR_WRITE_MASK;
bool map_writable;
ASSERT(vcpu);
ASSERT(VALID_PAGE(vcpu->arch.mmu.root_hpa));
if (unlikely(error_code & PFERR_RSVD_MASK)) {
r = handle_mmio_page_fault(vcpu, gpa, error_code, true);
if (likely(r != RET_MMIO_PF_INVALID))
return r;
}
r = mmu_topup_memory_caches(vcpu);
if (r)
return r;
force_pt_level = mapping_level_dirty_bitmap(vcpu, gfn);
if (likely(!force_pt_level)) {
level = mapping_level(vcpu, gfn);
gfn &= ~(KVM_PAGES_PER_HPAGE(level) - 1);
} else
level = PT_PAGE_TABLE_LEVEL;
if (fast_page_fault(vcpu, gpa, level, error_code))
return 0;
mmu_seq = vcpu->kvm->mmu_notifier_seq;
smp_rmb();
if (try_async_pf(vcpu, prefault, gfn, gpa, &pfn, write, &map_writable))
return 0;
if (handle_abnormal_pfn(vcpu, 0, gfn, pfn, ACC_ALL, &r))
return r;
spin_lock(&vcpu->kvm->mmu_lock);
if (mmu_notifier_retry(vcpu->kvm, mmu_seq))
goto out_unlock;
make_mmu_pages_available(vcpu);
if (likely(!force_pt_level))
transparent_hugepage_adjust(vcpu, &gfn, &pfn, &level);
r = __direct_map(vcpu, gpa, write, map_writable,
level, gfn, pfn, prefault);
spin_unlock(&vcpu->kvm->mmu_lock);
return r;
out_unlock:
spin_unlock(&vcpu->kvm->mmu_lock);
kvm_release_pfn_clean(pfn);
return 0;
}
static void nonpaging_free(struct kvm_vcpu *vcpu)
{
mmu_free_roots(vcpu);
}
static int nonpaging_init_context(struct kvm_vcpu *vcpu,
struct kvm_mmu *context)
{
context->new_cr3 = nonpaging_new_cr3;
context->page_fault = nonpaging_page_fault;
context->gva_to_gpa = nonpaging_gva_to_gpa;
context->free = nonpaging_free;
context->sync_page = nonpaging_sync_page;
context->invlpg = nonpaging_invlpg;
context->update_pte = nonpaging_update_pte;
context->root_level = 0;
context->shadow_root_level = PT32E_ROOT_LEVEL;
context->root_hpa = INVALID_PAGE;
context->direct_map = true;
context->nx = false;
return 0;
}
void kvm_mmu_flush_tlb(struct kvm_vcpu *vcpu)
{
++vcpu->stat.tlb_flush;
kvm_make_request(KVM_REQ_TLB_FLUSH, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_mmu_flush_tlb);
static void paging_new_cr3(struct kvm_vcpu *vcpu)
{
pgprintk("%s: cr3 %lx\n", __func__, kvm_read_cr3(vcpu));
mmu_free_roots(vcpu);
}
static unsigned long get_cr3(struct kvm_vcpu *vcpu)
{
return kvm_read_cr3(vcpu);
}
static void inject_page_fault(struct kvm_vcpu *vcpu,
struct x86_exception *fault)
{
vcpu->arch.mmu.inject_page_fault(vcpu, fault);
}
static void paging_free(struct kvm_vcpu *vcpu)
{
nonpaging_free(vcpu);
}
static bool sync_mmio_spte(struct kvm *kvm, u64 *sptep, gfn_t gfn,
unsigned access, int *nr_present)
{
if (unlikely(is_mmio_spte(*sptep))) {
if (gfn != get_mmio_spte_gfn(*sptep)) {
mmu_spte_clear_no_track(sptep);
return true;
}
(*nr_present)++;
mark_mmio_spte(kvm, sptep, gfn, access);
return true;
}
return false;
}
static inline bool is_last_gpte(struct kvm_mmu *mmu, unsigned level, unsigned gpte)
{
unsigned index;
index = level - 1;
index |= (gpte & PT_PAGE_SIZE_MASK) >> (PT_PAGE_SIZE_SHIFT - 2);
return mmu->last_pte_bitmap & (1 << index);
}
#define PTTYPE_EPT 18 /* arbitrary */
#define PTTYPE PTTYPE_EPT
#include "paging_tmpl.h"
#undef PTTYPE
#define PTTYPE 64
#include "paging_tmpl.h"
#undef PTTYPE
#define PTTYPE 32
#include "paging_tmpl.h"
#undef PTTYPE
static void reset_rsvds_bits_mask(struct kvm_vcpu *vcpu,
struct kvm_mmu *context)
{
int maxphyaddr = cpuid_maxphyaddr(vcpu);
u64 exb_bit_rsvd = 0;
context->bad_mt_xwr = 0;
if (!context->nx)
exb_bit_rsvd = rsvd_bits(63, 63);
switch (context->root_level) {
case PT32_ROOT_LEVEL:
/* no rsvd bits for 2 level 4K page table entries */
context->rsvd_bits_mask[0][1] = 0;
context->rsvd_bits_mask[0][0] = 0;
context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0];
if (!is_pse(vcpu)) {
context->rsvd_bits_mask[1][1] = 0;
break;
}
if (is_cpuid_PSE36())
/* 36bits PSE 4MB page */
context->rsvd_bits_mask[1][1] = rsvd_bits(17, 21);
else
/* 32 bits PSE 4MB page */
context->rsvd_bits_mask[1][1] = rsvd_bits(13, 21);
break;
case PT32E_ROOT_LEVEL:
context->rsvd_bits_mask[0][2] =
rsvd_bits(maxphyaddr, 63) |
rsvd_bits(7, 8) | rsvd_bits(1, 2); /* PDPTE */
context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 62); /* PDE */
context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 62); /* PTE */
context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 62) |
rsvd_bits(13, 20); /* large page */
context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0];
break;
case PT64_ROOT_LEVEL:
context->rsvd_bits_mask[0][3] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
context->rsvd_bits_mask[0][2] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 51) | rsvd_bits(7, 8);
context->rsvd_bits_mask[0][1] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 51);
context->rsvd_bits_mask[0][0] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 51);
context->rsvd_bits_mask[1][3] = context->rsvd_bits_mask[0][3];
context->rsvd_bits_mask[1][2] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 51) |
rsvd_bits(13, 29);
context->rsvd_bits_mask[1][1] = exb_bit_rsvd |
rsvd_bits(maxphyaddr, 51) |
rsvd_bits(13, 20); /* large page */
context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0];
break;
}
}
static void reset_rsvds_bits_mask_ept(struct kvm_vcpu *vcpu,
struct kvm_mmu *context, bool execonly)
{
int maxphyaddr = cpuid_maxphyaddr(vcpu);
int pte;
context->rsvd_bits_mask[0][3] =
rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 7);
context->rsvd_bits_mask[0][2] =
rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
context->rsvd_bits_mask[0][1] =
rsvd_bits(maxphyaddr, 51) | rsvd_bits(3, 6);
context->rsvd_bits_mask[0][0] = rsvd_bits(maxphyaddr, 51);
/* large page */
context->rsvd_bits_mask[1][3] = context->rsvd_bits_mask[0][3];
context->rsvd_bits_mask[1][2] =
rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 29);
context->rsvd_bits_mask[1][1] =
rsvd_bits(maxphyaddr, 51) | rsvd_bits(12, 20);
context->rsvd_bits_mask[1][0] = context->rsvd_bits_mask[0][0];
for (pte = 0; pte < 64; pte++) {
int rwx_bits = pte & 7;
int mt = pte >> 3;
if (mt == 0x2 || mt == 0x3 || mt == 0x7 ||
rwx_bits == 0x2 || rwx_bits == 0x6 ||
(rwx_bits == 0x4 && !execonly))
context->bad_mt_xwr |= (1ull << pte);
}
}
static void update_permission_bitmask(struct kvm_vcpu *vcpu,
struct kvm_mmu *mmu, bool ept)
{
unsigned bit, byte, pfec;
u8 map;
bool fault, x, w, u, wf, uf, ff, smep;
smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
for (byte = 0; byte < ARRAY_SIZE(mmu->permissions); ++byte) {
pfec = byte << 1;
map = 0;
wf = pfec & PFERR_WRITE_MASK;
uf = pfec & PFERR_USER_MASK;
ff = pfec & PFERR_FETCH_MASK;
for (bit = 0; bit < 8; ++bit) {
x = bit & ACC_EXEC_MASK;
w = bit & ACC_WRITE_MASK;
u = bit & ACC_USER_MASK;
if (!ept) {
/* Not really needed: !nx will cause pte.nx to fault */
x |= !mmu->nx;
/* Allow supervisor writes if !cr0.wp */
w |= !is_write_protection(vcpu) && !uf;
/* Disallow supervisor fetches of user code if cr4.smep */
x &= !(smep && u && !uf);
} else
/* Not really needed: no U/S accesses on ept */
u = 1;
fault = (ff && !x) || (uf && !u) || (wf && !w);
map |= fault << bit;
}
mmu->permissions[byte] = map;
}
}
static void update_last_pte_bitmap(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu)
{
u8 map;
unsigned level, root_level = mmu->root_level;
const unsigned ps_set_index = 1 << 2; /* bit 2 of index: ps */
if (root_level == PT32E_ROOT_LEVEL)
--root_level;
/* PT_PAGE_TABLE_LEVEL always terminates */
map = 1 | (1 << ps_set_index);
for (level = PT_DIRECTORY_LEVEL; level <= root_level; ++level) {
if (level <= PT_PDPE_LEVEL
&& (mmu->root_level >= PT32E_ROOT_LEVEL || is_pse(vcpu)))
map |= 1 << (ps_set_index | (level - 1));
}
mmu->last_pte_bitmap = map;
}
static int paging64_init_context_common(struct kvm_vcpu *vcpu,
struct kvm_mmu *context,
int level)
{
context->nx = is_nx(vcpu);
context->root_level = level;
reset_rsvds_bits_mask(vcpu, context);
update_permission_bitmask(vcpu, context, false);
update_last_pte_bitmap(vcpu, context);
ASSERT(is_pae(vcpu));
context->new_cr3 = paging_new_cr3;
context->page_fault = paging64_page_fault;
context->gva_to_gpa = paging64_gva_to_gpa;
context->sync_page = paging64_sync_page;
context->invlpg = paging64_invlpg;
context->update_pte = paging64_update_pte;
context->free = paging_free;
context->shadow_root_level = level;
context->root_hpa = INVALID_PAGE;
context->direct_map = false;
return 0;
}
static int paging64_init_context(struct kvm_vcpu *vcpu,
struct kvm_mmu *context)
{
return paging64_init_context_common(vcpu, context, PT64_ROOT_LEVEL);
}
static int paging32_init_context(struct kvm_vcpu *vcpu,
struct kvm_mmu *context)
{
context->nx = false;
context->root_level = PT32_ROOT_LEVEL;
reset_rsvds_bits_mask(vcpu, context);
update_permission_bitmask(vcpu, context, false);
update_last_pte_bitmap(vcpu, context);
context->new_cr3 = paging_new_cr3;
context->page_fault = paging32_page_fault;
context->gva_to_gpa = paging32_gva_to_gpa;
context->free = paging_free;
context->sync_page = paging32_sync_page;
context->invlpg = paging32_invlpg;
context->update_pte = paging32_update_pte;
context->shadow_root_level = PT32E_ROOT_LEVEL;
context->root_hpa = INVALID_PAGE;
context->direct_map = false;
return 0;
}
static int paging32E_init_context(struct kvm_vcpu *vcpu,
struct kvm_mmu *context)
{
return paging64_init_context_common(vcpu, context, PT32E_ROOT_LEVEL);
}
static int init_kvm_tdp_mmu(struct kvm_vcpu *vcpu)
{
struct kvm_mmu *context = vcpu->arch.walk_mmu;
context->base_role.word = 0;
context->new_cr3 = nonpaging_new_cr3;
context->page_fault = tdp_page_fault;
context->free = nonpaging_free;
context->sync_page = nonpaging_sync_page;
context->invlpg = nonpaging_invlpg;
context->update_pte = nonpaging_update_pte;
context->shadow_root_level = kvm_x86_ops->get_tdp_level();
context->root_hpa = INVALID_PAGE;
context->direct_map = true;
context->set_cr3 = kvm_x86_ops->set_tdp_cr3;
context->get_cr3 = get_cr3;
context->get_pdptr = kvm_pdptr_read;
context->inject_page_fault = kvm_inject_page_fault;
if (!is_paging(vcpu)) {
context->nx = false;
context->gva_to_gpa = nonpaging_gva_to_gpa;
context->root_level = 0;
} else if (is_long_mode(vcpu)) {
context->nx = is_nx(vcpu);
context->root_level = PT64_ROOT_LEVEL;
reset_rsvds_bits_mask(vcpu, context);
context->gva_to_gpa = paging64_gva_to_gpa;
} else if (is_pae(vcpu)) {
context->nx = is_nx(vcpu);
context->root_level = PT32E_ROOT_LEVEL;
reset_rsvds_bits_mask(vcpu, context);
context->gva_to_gpa = paging64_gva_to_gpa;
} else {
context->nx = false;
context->root_level = PT32_ROOT_LEVEL;
reset_rsvds_bits_mask(vcpu, context);
context->gva_to_gpa = paging32_gva_to_gpa;
}
update_permission_bitmask(vcpu, context, false);
update_last_pte_bitmap(vcpu, context);
return 0;
}
int kvm_init_shadow_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *context)
{
int r;
bool smep = kvm_read_cr4_bits(vcpu, X86_CR4_SMEP);
ASSERT(vcpu);
ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
if (!is_paging(vcpu))
r = nonpaging_init_context(vcpu, context);
else if (is_long_mode(vcpu))
r = paging64_init_context(vcpu, context);
else if (is_pae(vcpu))
r = paging32E_init_context(vcpu, context);
else
r = paging32_init_context(vcpu, context);
vcpu->arch.mmu.base_role.nxe = is_nx(vcpu);
vcpu->arch.mmu.base_role.cr4_pae = !!is_pae(vcpu);
vcpu->arch.mmu.base_role.cr0_wp = is_write_protection(vcpu);
vcpu->arch.mmu.base_role.smep_andnot_wp
= smep && !is_write_protection(vcpu);
return r;
}
EXPORT_SYMBOL_GPL(kvm_init_shadow_mmu);
int kvm_init_shadow_ept_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *context,
bool execonly)
{
ASSERT(vcpu);
ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
context->shadow_root_level = kvm_x86_ops->get_tdp_level();
context->nx = true;
context->new_cr3 = paging_new_cr3;
context->page_fault = ept_page_fault;
context->gva_to_gpa = ept_gva_to_gpa;
context->sync_page = ept_sync_page;
context->invlpg = ept_invlpg;
context->update_pte = ept_update_pte;
context->free = paging_free;
context->root_level = context->shadow_root_level;
context->root_hpa = INVALID_PAGE;
context->direct_map = false;
update_permission_bitmask(vcpu, context, true);
reset_rsvds_bits_mask_ept(vcpu, context, execonly);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_init_shadow_ept_mmu);
static int init_kvm_softmmu(struct kvm_vcpu *vcpu)
{
int r = kvm_init_shadow_mmu(vcpu, vcpu->arch.walk_mmu);
vcpu->arch.walk_mmu->set_cr3 = kvm_x86_ops->set_cr3;
vcpu->arch.walk_mmu->get_cr3 = get_cr3;
vcpu->arch.walk_mmu->get_pdptr = kvm_pdptr_read;
vcpu->arch.walk_mmu->inject_page_fault = kvm_inject_page_fault;
return r;
}
static int init_kvm_nested_mmu(struct kvm_vcpu *vcpu)
{
struct kvm_mmu *g_context = &vcpu->arch.nested_mmu;
g_context->get_cr3 = get_cr3;
g_context->get_pdptr = kvm_pdptr_read;
g_context->inject_page_fault = kvm_inject_page_fault;
/*
* Note that arch.mmu.gva_to_gpa translates l2_gva to l1_gpa. The
* translation of l2_gpa to l1_gpa addresses is done using the
* arch.nested_mmu.gva_to_gpa function. Basically the gva_to_gpa
* functions between mmu and nested_mmu are swapped.
*/
if (!is_paging(vcpu)) {
g_context->nx = false;
g_context->root_level = 0;
g_context->gva_to_gpa = nonpaging_gva_to_gpa_nested;
} else if (is_long_mode(vcpu)) {
g_context->nx = is_nx(vcpu);
g_context->root_level = PT64_ROOT_LEVEL;
reset_rsvds_bits_mask(vcpu, g_context);
g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
} else if (is_pae(vcpu)) {
g_context->nx = is_nx(vcpu);
g_context->root_level = PT32E_ROOT_LEVEL;
reset_rsvds_bits_mask(vcpu, g_context);
g_context->gva_to_gpa = paging64_gva_to_gpa_nested;
} else {
g_context->nx = false;
g_context->root_level = PT32_ROOT_LEVEL;
reset_rsvds_bits_mask(vcpu, g_context);
g_context->gva_to_gpa = paging32_gva_to_gpa_nested;
}
update_permission_bitmask(vcpu, g_context, false);
update_last_pte_bitmap(vcpu, g_context);
return 0;
}
static int init_kvm_mmu(struct kvm_vcpu *vcpu)
{
if (mmu_is_nested(vcpu))
return init_kvm_nested_mmu(vcpu);
else if (tdp_enabled)
return init_kvm_tdp_mmu(vcpu);
else
return init_kvm_softmmu(vcpu);
}
static void destroy_kvm_mmu(struct kvm_vcpu *vcpu)
{
ASSERT(vcpu);
if (VALID_PAGE(vcpu->arch.mmu.root_hpa))
/* mmu.free() should set root_hpa = INVALID_PAGE */
vcpu->arch.mmu.free(vcpu);
}
int kvm_mmu_reset_context(struct kvm_vcpu *vcpu)
{
destroy_kvm_mmu(vcpu);
return init_kvm_mmu(vcpu);
}
EXPORT_SYMBOL_GPL(kvm_mmu_reset_context);
int kvm_mmu_load(struct kvm_vcpu *vcpu)
{
int r;
r = mmu_topup_memory_caches(vcpu);
if (r)
goto out;
r = mmu_alloc_roots(vcpu);
kvm_mmu_sync_roots(vcpu);
if (r)
goto out;
/* set_cr3() should ensure TLB has been flushed */
vcpu->arch.mmu.set_cr3(vcpu, vcpu->arch.mmu.root_hpa);
out:
return r;
}
EXPORT_SYMBOL_GPL(kvm_mmu_load);
void kvm_mmu_unload(struct kvm_vcpu *vcpu)
{
mmu_free_roots(vcpu);
}
EXPORT_SYMBOL_GPL(kvm_mmu_unload);
static void mmu_pte_write_new_pte(struct kvm_vcpu *vcpu,
struct kvm_mmu_page *sp, u64 *spte,
const void *new)
{
if (sp->role.level != PT_PAGE_TABLE_LEVEL) {
++vcpu->kvm->stat.mmu_pde_zapped;
return;
}
++vcpu->kvm->stat.mmu_pte_updated;
vcpu->arch.mmu.update_pte(vcpu, sp, spte, new);
}
static bool need_remote_flush(u64 old, u64 new)
{
if (!is_shadow_present_pte(old))
return false;
if (!is_shadow_present_pte(new))
return true;
if ((old ^ new) & PT64_BASE_ADDR_MASK)
return true;
old ^= shadow_nx_mask;
new ^= shadow_nx_mask;
return (old & ~new & PT64_PERM_MASK) != 0;
}
static void mmu_pte_write_flush_tlb(struct kvm_vcpu *vcpu, bool zap_page,
bool remote_flush, bool local_flush)
{
if (zap_page)
return;
if (remote_flush)
kvm_flush_remote_tlbs(vcpu->kvm);
else if (local_flush)
kvm_mmu_flush_tlb(vcpu);
}
static u64 mmu_pte_write_fetch_gpte(struct kvm_vcpu *vcpu, gpa_t *gpa,
const u8 *new, int *bytes)
{
u64 gentry;
int r;
/*
* Assume that the pte write on a page table of the same type
* as the current vcpu paging mode since we update the sptes only
* when they have the same mode.
*/
if (is_pae(vcpu) && *bytes == 4) {
/* Handle a 32-bit guest writing two halves of a 64-bit gpte */
*gpa &= ~(gpa_t)7;
*bytes = 8;
r = kvm_read_guest(vcpu->kvm, *gpa, &gentry, 8);
if (r)
gentry = 0;
new = (const u8 *)&gentry;
}
switch (*bytes) {
case 4:
gentry = *(const u32 *)new;
break;
case 8:
gentry = *(const u64 *)new;
break;
default:
gentry = 0;
break;
}
return gentry;
}
/*
* If we're seeing too many writes to a page, it may no longer be a page table,
* or we may be forking, in which case it is better to unmap the page.
*/
static bool detect_write_flooding(struct kvm_mmu_page *sp)
{
/*
* Skip write-flooding detected for the sp whose level is 1, because
* it can become unsync, then the guest page is not write-protected.
*/
if (sp->role.level == PT_PAGE_TABLE_LEVEL)
return false;
return ++sp->write_flooding_count >= 3;
}
/*
* Misaligned accesses are too much trouble to fix up; also, they usually
* indicate a page is not used as a page table.
*/
static bool detect_write_misaligned(struct kvm_mmu_page *sp, gpa_t gpa,
int bytes)
{
unsigned offset, pte_size, misaligned;
pgprintk("misaligned: gpa %llx bytes %d role %x\n",
gpa, bytes, sp->role.word);
offset = offset_in_page(gpa);
pte_size = sp->role.cr4_pae ? 8 : 4;
/*
* Sometimes, the OS only writes the last one bytes to update status
* bits, for example, in linux, andb instruction is used in clear_bit().
*/
if (!(offset & (pte_size - 1)) && bytes == 1)
return false;
misaligned = (offset ^ (offset + bytes - 1)) & ~(pte_size - 1);
misaligned |= bytes < 4;
return misaligned;
}
static u64 *get_written_sptes(struct kvm_mmu_page *sp, gpa_t gpa, int *nspte)
{
unsigned page_offset, quadrant;
u64 *spte;
int level;
page_offset = offset_in_page(gpa);
level = sp->role.level;
*nspte = 1;
if (!sp->role.cr4_pae) {
page_offset <<= 1; /* 32->64 */
/*
* A 32-bit pde maps 4MB while the shadow pdes map
* only 2MB. So we need to double the offset again
* and zap two pdes instead of one.
*/
if (level == PT32_ROOT_LEVEL) {
page_offset &= ~7; /* kill rounding error */
page_offset <<= 1;
*nspte = 2;
}
quadrant = page_offset >> PAGE_SHIFT;
page_offset &= ~PAGE_MASK;
if (quadrant != sp->role.quadrant)
return NULL;
}
spte = &sp->spt[page_offset / sizeof(*spte)];
return spte;
}
void kvm_mmu_pte_write(struct kvm_vcpu *vcpu, gpa_t gpa,
const u8 *new, int bytes)
{
gfn_t gfn = gpa >> PAGE_SHIFT;
union kvm_mmu_page_role mask = { .word = 0 };
struct kvm_mmu_page *sp;
LIST_HEAD(invalid_list);
u64 entry, gentry, *spte;
int npte;
bool remote_flush, local_flush, zap_page;
/*
* If we don't have indirect shadow pages, it means no page is
* write-protected, so we can exit simply.
*/
if (!ACCESS_ONCE(vcpu->kvm->arch.indirect_shadow_pages))
return;
zap_page = remote_flush = local_flush = false;
pgprintk("%s: gpa %llx bytes %d\n", __func__, gpa, bytes);
gentry = mmu_pte_write_fetch_gpte(vcpu, &gpa, new, &bytes);
/*
* No need to care whether allocation memory is successful
* or not since pte prefetch is skiped if it does not have
* enough objects in the cache.
*/
mmu_topup_memory_caches(vcpu);
spin_lock(&vcpu->kvm->mmu_lock);
++vcpu->kvm->stat.mmu_pte_write;
kvm_mmu_audit(vcpu, AUDIT_PRE_PTE_WRITE);
mask.cr0_wp = mask.cr4_pae = mask.nxe = 1;
for_each_gfn_indirect_valid_sp(vcpu->kvm, sp, gfn) {
if (detect_write_misaligned(sp, gpa, bytes) ||
detect_write_flooding(sp)) {
zap_page |= !!kvm_mmu_prepare_zap_page(vcpu->kvm, sp,
&invalid_list);
++vcpu->kvm->stat.mmu_flooded;
continue;
}
spte = get_written_sptes(sp, gpa, &npte);
if (!spte)
continue;
local_flush = true;
while (npte--) {
entry = *spte;
mmu_page_zap_pte(vcpu->kvm, sp, spte);
if (gentry &&
!((sp->role.word ^ vcpu->arch.mmu.base_role.word)
& mask.word) && rmap_can_add(vcpu))
mmu_pte_write_new_pte(vcpu, sp, spte, &gentry);
if (need_remote_flush(entry, *spte))
remote_flush = true;
++spte;
}
}
mmu_pte_write_flush_tlb(vcpu, zap_page, remote_flush, local_flush);
kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
kvm_mmu_audit(vcpu, AUDIT_POST_PTE_WRITE);
spin_unlock(&vcpu->kvm->mmu_lock);
}
int kvm_mmu_unprotect_page_virt(struct kvm_vcpu *vcpu, gva_t gva)
{
gpa_t gpa;
int r;
if (vcpu->arch.mmu.direct_map)
return 0;
gpa = kvm_mmu_gva_to_gpa_read(vcpu, gva, NULL);
r = kvm_mmu_unprotect_page(vcpu->kvm, gpa >> PAGE_SHIFT);
return r;
}
EXPORT_SYMBOL_GPL(kvm_mmu_unprotect_page_virt);
static void make_mmu_pages_available(struct kvm_vcpu *vcpu)
{
LIST_HEAD(invalid_list);
if (likely(kvm_mmu_available_pages(vcpu->kvm) >= KVM_MIN_FREE_MMU_PAGES))
return;
while (kvm_mmu_available_pages(vcpu->kvm) < KVM_REFILL_PAGES) {
if (!prepare_zap_oldest_mmu_page(vcpu->kvm, &invalid_list))
break;
++vcpu->kvm->stat.mmu_recycled;
}
kvm_mmu_commit_zap_page(vcpu->kvm, &invalid_list);
}
static bool is_mmio_page_fault(struct kvm_vcpu *vcpu, gva_t addr)
{
if (vcpu->arch.mmu.direct_map || mmu_is_nested(vcpu))
return vcpu_match_mmio_gpa(vcpu, addr);
return vcpu_match_mmio_gva(vcpu, addr);
}
int kvm_mmu_page_fault(struct kvm_vcpu *vcpu, gva_t cr2, u32 error_code,
void *insn, int insn_len)
{
int r, emulation_type = EMULTYPE_RETRY;
enum emulation_result er;
r = vcpu->arch.mmu.page_fault(vcpu, cr2, error_code, false);
if (r < 0)
goto out;
if (!r) {
r = 1;
goto out;
}
if (is_mmio_page_fault(vcpu, cr2))
emulation_type = 0;
er = x86_emulate_instruction(vcpu, cr2, emulation_type, insn, insn_len);
switch (er) {
case EMULATE_DONE:
return 1;
case EMULATE_USER_EXIT:
++vcpu->stat.mmio_exits;
/* fall through */
case EMULATE_FAIL:
return 0;
default:
BUG();
}
out:
return r;
}
EXPORT_SYMBOL_GPL(kvm_mmu_page_fault);
void kvm_mmu_invlpg(struct kvm_vcpu *vcpu, gva_t gva)
{
vcpu->arch.mmu.invlpg(vcpu, gva);
kvm_mmu_flush_tlb(vcpu);
++vcpu->stat.invlpg;
}
EXPORT_SYMBOL_GPL(kvm_mmu_invlpg);
void kvm_enable_tdp(void)
{
tdp_enabled = true;
}
EXPORT_SYMBOL_GPL(kvm_enable_tdp);
void kvm_disable_tdp(void)
{
tdp_enabled = false;
}
EXPORT_SYMBOL_GPL(kvm_disable_tdp);
static void free_mmu_pages(struct kvm_vcpu *vcpu)
{
free_page((unsigned long)vcpu->arch.mmu.pae_root);
if (vcpu->arch.mmu.lm_root != NULL)
free_page((unsigned long)vcpu->arch.mmu.lm_root);
}
static int alloc_mmu_pages(struct kvm_vcpu *vcpu)
{
struct page *page;
int i;
ASSERT(vcpu);
/*
* When emulating 32-bit mode, cr3 is only 32 bits even on x86_64.
* Therefore we need to allocate shadow page tables in the first
* 4GB of memory, which happens to fit the DMA32 zone.
*/
page = alloc_page(GFP_KERNEL | __GFP_DMA32);
if (!page)
return -ENOMEM;
vcpu->arch.mmu.pae_root = page_address(page);
for (i = 0; i < 4; ++i)
vcpu->arch.mmu.pae_root[i] = INVALID_PAGE;
return 0;
}
int kvm_mmu_create(struct kvm_vcpu *vcpu)
{
ASSERT(vcpu);
vcpu->arch.walk_mmu = &vcpu->arch.mmu;
vcpu->arch.mmu.root_hpa = INVALID_PAGE;
vcpu->arch.mmu.translate_gpa = translate_gpa;
vcpu->arch.nested_mmu.translate_gpa = translate_nested_gpa;
return alloc_mmu_pages(vcpu);
}
int kvm_mmu_setup(struct kvm_vcpu *vcpu)
{
ASSERT(vcpu);
ASSERT(!VALID_PAGE(vcpu->arch.mmu.root_hpa));
return init_kvm_mmu(vcpu);
}
void kvm_mmu_slot_remove_write_access(struct kvm *kvm, int slot)
{
struct kvm_memory_slot *memslot;
gfn_t last_gfn;
int i;
memslot = id_to_memslot(kvm->memslots, slot);
last_gfn = memslot->base_gfn + memslot->npages - 1;
spin_lock(&kvm->mmu_lock);
for (i = PT_PAGE_TABLE_LEVEL;
i < PT_PAGE_TABLE_LEVEL + KVM_NR_PAGE_SIZES; ++i) {
unsigned long *rmapp;
unsigned long last_index, index;
rmapp = memslot->arch.rmap[i - PT_PAGE_TABLE_LEVEL];
last_index = gfn_to_index(last_gfn, memslot->base_gfn, i);
for (index = 0; index <= last_index; ++index, ++rmapp) {
if (*rmapp)
__rmap_write_protect(kvm, rmapp, false);
if (need_resched() || spin_needbreak(&kvm->mmu_lock)) {
kvm_flush_remote_tlbs(kvm);
cond_resched_lock(&kvm->mmu_lock);
}
}
}
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
}
#define BATCH_ZAP_PAGES 10
static void kvm_zap_obsolete_pages(struct kvm *kvm)
{
struct kvm_mmu_page *sp, *node;
int batch = 0;
restart:
list_for_each_entry_safe_reverse(sp, node,
&kvm->arch.active_mmu_pages, link) {
int ret;
/*
* No obsolete page exists before new created page since
* active_mmu_pages is the FIFO list.
*/
if (!is_obsolete_sp(kvm, sp))
break;
/*
* Since we are reversely walking the list and the invalid
* list will be moved to the head, skip the invalid page
* can help us to avoid the infinity list walking.
*/
if (sp->role.invalid)
continue;
/*
* Need not flush tlb since we only zap the sp with invalid
* generation number.
*/
if (batch >= BATCH_ZAP_PAGES &&
cond_resched_lock(&kvm->mmu_lock)) {
batch = 0;
goto restart;
}
ret = kvm_mmu_prepare_zap_page(kvm, sp,
&kvm->arch.zapped_obsolete_pages);
batch += ret;
if (ret)
goto restart;
}
/*
* Should flush tlb before free page tables since lockless-walking
* may use the pages.
*/
kvm_mmu_commit_zap_page(kvm, &kvm->arch.zapped_obsolete_pages);
}
/*
* Fast invalidate all shadow pages and use lock-break technique
* to zap obsolete pages.
*
* It's required when memslot is being deleted or VM is being
* destroyed, in these cases, we should ensure that KVM MMU does
* not use any resource of the being-deleted slot or all slots
* after calling the function.
*/
void kvm_mmu_invalidate_zap_all_pages(struct kvm *kvm)
{
spin_lock(&kvm->mmu_lock);
trace_kvm_mmu_invalidate_zap_all_pages(kvm);
kvm->arch.mmu_valid_gen++;
/*
* Notify all vcpus to reload its shadow page table
* and flush TLB. Then all vcpus will switch to new
* shadow page table with the new mmu_valid_gen.
*
* Note: we should do this under the protection of
* mmu-lock, otherwise, vcpu would purge shadow page
* but miss tlb flush.
*/
kvm_reload_remote_mmus(kvm);
kvm_zap_obsolete_pages(kvm);
spin_unlock(&kvm->mmu_lock);
}
static bool kvm_has_zapped_obsolete_pages(struct kvm *kvm)
{
return unlikely(!list_empty_careful(&kvm->arch.zapped_obsolete_pages));
}
void kvm_mmu_invalidate_mmio_sptes(struct kvm *kvm)
{
/*
* The very rare case: if the generation-number is round,
* zap all shadow pages.
*/
if (unlikely(kvm_current_mmio_generation(kvm) >= MMIO_MAX_GEN)) {
printk_ratelimited(KERN_INFO "kvm: zapping shadow pages for mmio generation wraparound\n");
kvm_mmu_invalidate_zap_all_pages(kvm);
}
}
static int mmu_shrink(struct shrinker *shrink, struct shrink_control *sc)
{
struct kvm *kvm;
int nr_to_scan = sc->nr_to_scan;
if (nr_to_scan == 0)
goto out;
raw_spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list) {
int idx;
LIST_HEAD(invalid_list);
/*
* Never scan more than sc->nr_to_scan VM instances.
* Will not hit this condition practically since we do not try
* to shrink more than one VM and it is very unlikely to see
* !n_used_mmu_pages so many times.
*/
if (!nr_to_scan--)
break;
/*
* n_used_mmu_pages is accessed without holding kvm->mmu_lock
* here. We may skip a VM instance errorneosly, but we do not
* want to shrink a VM that only started to populate its MMU
* anyway.
*/
if (!kvm->arch.n_used_mmu_pages &&
!kvm_has_zapped_obsolete_pages(kvm))
continue;
idx = srcu_read_lock(&kvm->srcu);
spin_lock(&kvm->mmu_lock);
if (kvm_has_zapped_obsolete_pages(kvm)) {
kvm_mmu_commit_zap_page(kvm,
&kvm->arch.zapped_obsolete_pages);
goto unlock;
}
prepare_zap_oldest_mmu_page(kvm, &invalid_list);
kvm_mmu_commit_zap_page(kvm, &invalid_list);
unlock:
spin_unlock(&kvm->mmu_lock);
srcu_read_unlock(&kvm->srcu, idx);
list_move_tail(&kvm->vm_list, &vm_list);
break;
}
raw_spin_unlock(&kvm_lock);
out:
return percpu_counter_read_positive(&kvm_total_used_mmu_pages);
}
static struct shrinker mmu_shrinker = {
.shrink = mmu_shrink,
.seeks = DEFAULT_SEEKS * 10,
};
static void mmu_destroy_caches(void)
{
if (pte_list_desc_cache)
kmem_cache_destroy(pte_list_desc_cache);
if (mmu_page_header_cache)
kmem_cache_destroy(mmu_page_header_cache);
}
int kvm_mmu_module_init(void)
{
pte_list_desc_cache = kmem_cache_create("pte_list_desc",
sizeof(struct pte_list_desc),
0, 0, NULL);
if (!pte_list_desc_cache)
goto nomem;
mmu_page_header_cache = kmem_cache_create("kvm_mmu_page_header",
sizeof(struct kvm_mmu_page),
0, 0, NULL);
if (!mmu_page_header_cache)
goto nomem;
if (percpu_counter_init(&kvm_total_used_mmu_pages, 0))
goto nomem;
register_shrinker(&mmu_shrinker);
return 0;
nomem:
mmu_destroy_caches();
return -ENOMEM;
}
/*
* Caculate mmu pages needed for kvm.
*/
unsigned int kvm_mmu_calculate_mmu_pages(struct kvm *kvm)
{
unsigned int nr_mmu_pages;
unsigned int nr_pages = 0;
struct kvm_memslots *slots;
struct kvm_memory_slot *memslot;
slots = kvm_memslots(kvm);
kvm_for_each_memslot(memslot, slots)
nr_pages += memslot->npages;
nr_mmu_pages = nr_pages * KVM_PERMILLE_MMU_PAGES / 1000;
nr_mmu_pages = max(nr_mmu_pages,
(unsigned int) KVM_MIN_ALLOC_MMU_PAGES);
return nr_mmu_pages;
}
int kvm_mmu_get_spte_hierarchy(struct kvm_vcpu *vcpu, u64 addr, u64 sptes[4])
{
struct kvm_shadow_walk_iterator iterator;
u64 spte;
int nr_sptes = 0;
walk_shadow_page_lockless_begin(vcpu);
for_each_shadow_entry_lockless(vcpu, addr, iterator, spte) {
sptes[iterator.level-1] = spte;
nr_sptes++;
if (!is_shadow_present_pte(spte))
break;
}
walk_shadow_page_lockless_end(vcpu);
return nr_sptes;
}
EXPORT_SYMBOL_GPL(kvm_mmu_get_spte_hierarchy);
void kvm_mmu_destroy(struct kvm_vcpu *vcpu)
{
ASSERT(vcpu);
destroy_kvm_mmu(vcpu);
free_mmu_pages(vcpu);
mmu_free_memory_caches(vcpu);
}
void kvm_mmu_module_exit(void)
{
mmu_destroy_caches();
percpu_counter_destroy(&kvm_total_used_mmu_pages);
unregister_shrinker(&mmu_shrinker);
mmu_audit_disable();
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_2162_2 |
crossvul-cpp_data_bad_1658_3 | /*
* ntp_util.c - stuff I didn't have any other place for
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "ntpd.h"
#include "ntp_unixtime.h"
#include "ntp_filegen.h"
#include "ntp_if.h"
#include "ntp_stdlib.h"
#include "ntp_assert.h"
#include "ntp_calendar.h"
#include "lib_strbuf.h"
#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_IEEEFP_H
# include <ieeefp.h>
#endif
#ifdef HAVE_MATH_H
# include <math.h>
#endif
#ifdef DOSYNCTODR
# if !defined(VMS)
# include <sys/resource.h>
# endif /* VMS */
#endif
#if defined(VMS)
# include <descrip.h>
#endif /* VMS */
/*
* Defines used by the leapseconds stuff
*/
#define MAX_TAI 100 /* max TAI offset (s) */
#define L_DAY 86400UL /* seconds per day */
#define L_YEAR (L_DAY * 365) /* days per year */
#define L_LYEAR (L_YEAR + L_DAY) /* days per leap year */
#define L_4YEAR (L_LYEAR + 3 * L_YEAR) /* days per leap cycle */
#define L_CENT (L_4YEAR * 25) /* days per century */
/*
* This contains odds and ends, including the hourly stats, various
* configuration items, leapseconds stuff, etc.
*/
/*
* File names
*/
static char *key_file_name; /* keys file name */
char *leapseconds_file_name; /* leapseconds file name */
char *stats_drift_file; /* frequency file name */
static char *stats_temp_file; /* temp frequency file name */
static double wander_resid; /* last frequency update */
double wander_threshold = 1e-7; /* initial frequency threshold */
/*
* Statistics file stuff
*/
#ifndef NTP_VAR
# ifndef SYS_WINNT
# define NTP_VAR "/var/NTP/" /* NOTE the trailing '/' */
# else
# define NTP_VAR "c:\\var\\ntp\\" /* NOTE the trailing '\\' */
# endif /* SYS_WINNT */
#endif
#ifndef MAXPATHLEN
# define MAXPATHLEN 256
#endif
#ifdef DEBUG_TIMING
static FILEGEN timingstats;
#endif
#ifdef AUTOKEY
static FILEGEN cryptostats;
#endif /* AUTOKEY */
static char statsdir[MAXPATHLEN] = NTP_VAR;
static FILEGEN peerstats;
static FILEGEN loopstats;
static FILEGEN clockstats;
static FILEGEN rawstats;
static FILEGEN sysstats;
static FILEGEN protostats;
/*
* This controls whether stats are written to the fileset. Provided
* so that ntpdc can turn off stats when the file system fills up.
*/
int stats_control;
/*
* Last frequency written to file.
*/
static double prev_drift_comp; /* last frequency update */
/*
* Function prototypes
*/
static int leap_file(FILE *);
static void record_sys_stats(void);
void ntpd_time_stepped(void);
/*
* Prototypes
*/
#ifdef DEBUG
void uninit_util(void);
#endif
/*
* uninit_util - free memory allocated by init_util
*/
#ifdef DEBUG
void
uninit_util(void)
{
#if defined(_MSC_VER) && defined (_DEBUG)
_CrtCheckMemory();
#endif
if (stats_drift_file) {
free(stats_drift_file);
free(stats_temp_file);
stats_drift_file = NULL;
stats_temp_file = NULL;
}
if (key_file_name) {
free(key_file_name);
key_file_name = NULL;
}
filegen_unregister("peerstats");
filegen_unregister("loopstats");
filegen_unregister("clockstats");
filegen_unregister("rawstats");
filegen_unregister("sysstats");
filegen_unregister("protostats");
#ifdef AUTOKEY
filegen_unregister("cryptostats");
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
filegen_unregister("timingstats");
#endif /* DEBUG_TIMING */
#if defined(_MSC_VER) && defined (_DEBUG)
_CrtCheckMemory();
#endif
}
#endif /* DEBUG */
/*
* init_util - initialize the util module of ntpd
*/
void
init_util(void)
{
filegen_register(statsdir, "peerstats", &peerstats);
filegen_register(statsdir, "loopstats", &loopstats);
filegen_register(statsdir, "clockstats", &clockstats);
filegen_register(statsdir, "rawstats", &rawstats);
filegen_register(statsdir, "sysstats", &sysstats);
filegen_register(statsdir, "protostats", &protostats);
#ifdef AUTOKEY
filegen_register(statsdir, "cryptostats", &cryptostats);
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
filegen_register(statsdir, "timingstats", &timingstats);
#endif /* DEBUG_TIMING */
/*
* register with libntp ntp_set_tod() to call us back
* when time is stepped.
*/
step_callback = &ntpd_time_stepped;
#ifdef DEBUG
atexit(&uninit_util);
#endif /* DEBUG */
}
/*
* hourly_stats - print some interesting stats
*/
void
write_stats(void)
{
FILE *fp;
#ifdef DOSYNCTODR
struct timeval tv;
#if !defined(VMS)
int prio_set;
#endif
#ifdef HAVE_GETCLOCK
struct timespec ts;
#endif
int o_prio;
/*
* Sometimes having a Sun can be a drag.
*
* The kernel variable dosynctodr controls whether the system's
* soft clock is kept in sync with the battery clock. If it
* is zero, then the soft clock is not synced, and the battery
* clock is simply left to rot. That means that when the system
* reboots, the battery clock (which has probably gone wacky)
* sets the soft clock. That means ntpd starts off with a very
* confused idea of what time it is. It then takes a large
* amount of time to figure out just how wacky the battery clock
* has made things drift, etc, etc. The solution is to make the
* battery clock sync up to system time. The way to do THAT is
* to simply set the time of day to the current time of day, but
* as quickly as possible. This may, or may not be a sensible
* thing to do.
*
* CAVEAT: settimeofday() steps the sun clock by about 800 us,
* so setting DOSYNCTODR seems a bad idea in the
* case of us resolution
*/
#if !defined(VMS)
/*
* (prr) getpriority returns -1 on error, but -1 is also a valid
* return value (!), so instead we have to zero errno before the
* call and check it for non-zero afterwards.
*/
errno = 0;
prio_set = 0;
o_prio = getpriority(PRIO_PROCESS,0); /* Save setting */
/*
* (prr) if getpriority succeeded, call setpriority to raise
* scheduling priority as high as possible. If that succeeds
* as well, set the prio_set flag so we remember to reset
* priority to its previous value below. Note that on Solaris
* 2.6 (and beyond?), both getpriority and setpriority will fail
* with ESRCH, because sched_setscheduler (called from main) put
* us in the real-time scheduling class which setpriority
* doesn't know about. Being in the real-time class is better
* than anything setpriority can do, anyhow, so this error is
* silently ignored.
*/
if ((errno == 0) && (setpriority(PRIO_PROCESS,0,-20) == 0))
prio_set = 1; /* overdrive */
#endif /* VMS */
#ifdef HAVE_GETCLOCK
(void) getclock(TIMEOFDAY, &ts);
tv.tv_sec = ts.tv_sec;
tv.tv_usec = ts.tv_nsec / 1000;
#else /* not HAVE_GETCLOCK */
GETTIMEOFDAY(&tv,(struct timezone *)NULL);
#endif /* not HAVE_GETCLOCK */
if (ntp_set_tod(&tv,(struct timezone *)NULL) != 0)
msyslog(LOG_ERR, "can't sync battery time: %m");
#if !defined(VMS)
if (prio_set)
setpriority(PRIO_PROCESS, 0, o_prio); /* downshift */
#endif /* VMS */
#endif /* DOSYNCTODR */
record_sys_stats();
if (stats_drift_file != 0) {
/*
* When the frequency file is written, initialize the
* prev_drift_comp and wander_resid. Thereafter,
* reduce the wander_resid by half each hour. When
* the difference between the prev_drift_comp and
* drift_comp is less than the wander_resid, update
* the frequncy file. This minimizes the file writes to
* nonvolaile storage.
*/
#ifdef DEBUG
if (debug)
printf("write_stats: frequency %.6lf thresh %.6lf, freq %.6lf\n",
(prev_drift_comp - drift_comp) * 1e6, wander_resid *
1e6, drift_comp * 1e6);
#endif
if (fabs(prev_drift_comp - drift_comp) < wander_resid) {
wander_resid *= 0.5;
return;
}
prev_drift_comp = drift_comp;
wander_resid = wander_threshold;
if ((fp = fopen(stats_temp_file, "w")) == NULL) {
msyslog(LOG_ERR, "frequency file %s: %m",
stats_temp_file);
return;
}
fprintf(fp, "%.3f\n", drift_comp * 1e6);
(void)fclose(fp);
/* atomic */
#ifdef SYS_WINNT
if (_unlink(stats_drift_file)) /* rename semantics differ under NT */
msyslog(LOG_WARNING,
"Unable to remove prior drift file %s, %m",
stats_drift_file);
#endif /* SYS_WINNT */
#ifndef NO_RENAME
if (rename(stats_temp_file, stats_drift_file))
msyslog(LOG_WARNING,
"Unable to rename temp drift file %s to %s, %m",
stats_temp_file, stats_drift_file);
#else
/* we have no rename NFS of ftp in use */
if ((fp = fopen(stats_drift_file, "w")) ==
NULL) {
msyslog(LOG_ERR,
"frequency file %s: %m",
stats_drift_file);
return;
}
#endif
#if defined(VMS)
/* PURGE */
{
$DESCRIPTOR(oldvers,";-1");
struct dsc$descriptor driftdsc = {
strlen(stats_drift_file), 0, 0,
stats_drift_file };
while(lib$delete_file(&oldvers,
&driftdsc) & 1);
}
#endif
}
}
/*
* stats_config - configure the stats operation
*/
void
stats_config(
int item,
const char *invalue /* only one type so far */
)
{
FILE *fp;
const char *value;
int len;
double old_drift;
#ifndef VMS
const char temp_ext[] = ".TEMP";
#else
const char temp_ext[] = "-TEMP";
#endif
/*
* Expand environment strings under Windows NT, since the
* command interpreter doesn't do this, the program must.
*/
#ifdef SYS_WINNT
char newvalue[MAX_PATH], parameter[MAX_PATH];
if (!ExpandEnvironmentStrings(invalue, newvalue, MAX_PATH)) {
switch (item) {
case STATS_FREQ_FILE:
strncpy(parameter, "STATS_FREQ_FILE",
sizeof(parameter));
break;
case STATS_LEAP_FILE:
strncpy(parameter, "STATS_LEAP_FILE",
sizeof(parameter));
break;
case STATS_STATSDIR:
strncpy(parameter, "STATS_STATSDIR",
sizeof(parameter));
break;
case STATS_PID_FILE:
strncpy(parameter, "STATS_PID_FILE",
sizeof(parameter));
break;
default:
strncpy(parameter, "UNKNOWN",
sizeof(parameter));
break;
}
value = invalue;
msyslog(LOG_ERR,
"ExpandEnvironmentStrings(%s) failed: %m\n",
parameter);
} else {
value = newvalue;
}
#else
value = invalue;
#endif /* SYS_WINNT */
switch (item) {
/*
* Open and read frequency file.
*/
case STATS_FREQ_FILE:
if (!value || (len = strlen(value)) == 0)
break;
stats_drift_file = erealloc(stats_drift_file, len + 1);
stats_temp_file = erealloc(stats_temp_file,
len + sizeof(".TEMP"));
memcpy(stats_drift_file, value, (size_t)(len+1));
memcpy(stats_temp_file, value, (size_t)len);
memcpy(stats_temp_file + len, temp_ext, sizeof(temp_ext));
/*
* Open drift file and read frequency. If the file is
* missing or contains errors, tell the loop to reset.
*/
if ((fp = fopen(stats_drift_file, "r")) == NULL)
break;
if (fscanf(fp, "%lf", &old_drift) != 1) {
msyslog(LOG_ERR,
"format error frequency file %s",
stats_drift_file);
fclose(fp);
break;
}
fclose(fp);
loop_config(LOOP_FREQ, old_drift);
prev_drift_comp = drift_comp;
break;
/*
* Specify statistics directory.
*/
case STATS_STATSDIR:
/*
* HMS: the following test is insufficient:
* - value may be missing the DIR_SEP
* - we still need the filename after it
*/
if (strlen(value) >= sizeof(statsdir)) {
msyslog(LOG_ERR,
"statsdir too long (>%d, sigh)",
(int)sizeof(statsdir) - 1);
} else {
l_fp now;
int add_dir_sep;
int value_l = strlen(value);
/* Add a DIR_SEP unless we already have one. */
if (value_l == 0)
add_dir_sep = 0;
else
add_dir_sep = (DIR_SEP !=
value[value_l - 1]);
if (add_dir_sep)
snprintf(statsdir, sizeof(statsdir),
"%s%c", value, DIR_SEP);
else
snprintf(statsdir, sizeof(statsdir),
"%s", value);
get_systime(&now);
if (peerstats.prefix == &statsdir[0] &&
peerstats.fp != NULL) {
fclose(peerstats.fp);
peerstats.fp = NULL;
filegen_setup(&peerstats, now.l_ui);
}
if (loopstats.prefix == &statsdir[0] &&
loopstats.fp != NULL) {
fclose(loopstats.fp);
loopstats.fp = NULL;
filegen_setup(&loopstats, now.l_ui);
}
if (clockstats.prefix == &statsdir[0] &&
clockstats.fp != NULL) {
fclose(clockstats.fp);
clockstats.fp = NULL;
filegen_setup(&clockstats, now.l_ui);
}
if (rawstats.prefix == &statsdir[0] &&
rawstats.fp != NULL) {
fclose(rawstats.fp);
rawstats.fp = NULL;
filegen_setup(&rawstats, now.l_ui);
}
if (sysstats.prefix == &statsdir[0] &&
sysstats.fp != NULL) {
fclose(sysstats.fp);
sysstats.fp = NULL;
filegen_setup(&sysstats, now.l_ui);
}
if (protostats.prefix == &statsdir[0] &&
protostats.fp != NULL) {
fclose(protostats.fp);
protostats.fp = NULL;
filegen_setup(&protostats, now.l_ui);
}
#ifdef AUTOKEY
if (cryptostats.prefix == &statsdir[0] &&
cryptostats.fp != NULL) {
fclose(cryptostats.fp);
cryptostats.fp = NULL;
filegen_setup(&cryptostats, now.l_ui);
}
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
if (timingstats.prefix == &statsdir[0] &&
timingstats.fp != NULL) {
fclose(timingstats.fp);
timingstats.fp = NULL;
filegen_setup(&timingstats, now.l_ui);
}
#endif /* DEBUG_TIMING */
}
break;
/*
* Open pid file.
*/
case STATS_PID_FILE:
if ((fp = fopen(value, "w")) == NULL) {
msyslog(LOG_ERR, "pid file %s: %m",
value);
break;
}
fprintf(fp, "%d", (int)getpid());
fclose(fp);;
break;
/*
* Read leapseconds file.
*/
case STATS_LEAP_FILE:
if ((fp = fopen(value, "r")) == NULL) {
msyslog(LOG_ERR, "leapseconds file %s: %m",
value);
break;
}
if (leap_file(fp) < 0)
msyslog(LOG_ERR,
"format error leapseconds file %s",
value);
else
mprintf_event(EVNT_TAI, NULL,
"%d leap %s expire %s", leap_tai,
fstostr(leap_sec),
fstostr(leap_expire));
fclose(fp);
break;
default:
/* oh well */
break;
}
}
/*
* record_peer_stats - write peer statistics to file
*
* file format:
* day (MJD)
* time (s past UTC midnight)
* IP address
* status word (hex)
* offset
* delay
* dispersion
* jitter
*/
void
record_peer_stats(
sockaddr_u *addr,
int status,
double offset, /* offset */
double delay, /* delay */
double dispersion, /* dispersion */
double jitter /* jitter */
)
{
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&peerstats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (peerstats.fp != NULL) {
fprintf(peerstats.fp,
"%lu %s %s %x %.9f %.9f %.9f %.9f\n", day,
ulfptoa(&now, 3), stoa(addr), status, offset,
delay, dispersion, jitter);
fflush(peerstats.fp);
}
}
/*
* record_loop_stats - write loop filter statistics to file
*
* file format:
* day (MJD)
* time (s past midnight)
* offset
* frequency (PPM)
* jitter
* wnder (PPM)
* time constant (log2)
*/
void
record_loop_stats(
double offset, /* offset */
double freq, /* frequency (PPM) */
double jitter, /* jitter */
double wander, /* wander (PPM) */
int spoll
)
{
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&loopstats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (loopstats.fp != NULL) {
fprintf(loopstats.fp, "%lu %s %.9f %.3f %.9f %.6f %d\n",
day, ulfptoa(&now, 3), offset, freq * 1e6, jitter,
wander * 1e6, spoll);
fflush(loopstats.fp);
}
}
/*
* record_clock_stats - write clock statistics to file
*
* file format:
* day (MJD)
* time (s past midnight)
* IP address
* text message
*/
void
record_clock_stats(
sockaddr_u *addr,
const char *text /* timecode string */
)
{
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&clockstats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (clockstats.fp != NULL) {
fprintf(clockstats.fp, "%lu %s %s %s\n", day,
ulfptoa(&now, 3), stoa(addr), text);
fflush(clockstats.fp);
}
}
/*
* mprintf_clock_stats - write clock statistics to file with
* msnprintf-style formatting.
*/
int
mprintf_clock_stats(
sockaddr_u *addr,
const char *fmt,
...
)
{
va_list ap;
int rc;
char msg[512];
va_start(ap, fmt);
rc = mvsnprintf(msg, sizeof(msg), fmt, ap);
va_end(ap);
if (stats_control)
record_clock_stats(addr, msg);
return rc;
}
/*
* record_raw_stats - write raw timestamps to file
*
* file format
* day (MJD)
* time (s past midnight)
* peer ip address
* IP address
* t1 t2 t3 t4 timestamps
*/
void
record_raw_stats(
sockaddr_u *srcadr,
sockaddr_u *dstadr,
l_fp *t1, /* originate timestamp */
l_fp *t2, /* receive timestamp */
l_fp *t3, /* transmit timestamp */
l_fp *t4 /* destination timestamp */
)
{
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&rawstats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (rawstats.fp != NULL) {
fprintf(rawstats.fp, "%lu %s %s %s %s %s %s %s\n", day,
ulfptoa(&now, 3), stoa(srcadr), dstadr ?
stoa(dstadr) : "-", ulfptoa(t1, 9), ulfptoa(t2, 9),
ulfptoa(t3, 9), ulfptoa(t4, 9));
fflush(rawstats.fp);
}
}
/*
* record_sys_stats - write system statistics to file
*
* file format
* day (MJD)
* time (s past midnight)
* time since reset
* packets recieved
* packets for this host
* current version
* old version
* access denied
* bad length or format
* bad authentication
* declined
* rate exceeded
* KoD sent
*/
void
record_sys_stats(void)
{
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&sysstats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (sysstats.fp != NULL) {
fprintf(sysstats.fp,
"%lu %s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
day, ulfptoa(&now, 3), current_time - sys_stattime,
sys_received, sys_processed, sys_newversion,
sys_oldversion, sys_restricted, sys_badlength,
sys_badauth, sys_declined, sys_limitrejected,
sys_kodsent);
fflush(sysstats.fp);
proto_clr_stats();
}
}
/*
* record_proto_stats - write system statistics to file
*
* file format
* day (MJD)
* time (s past midnight)
* text message
*/
void
record_proto_stats(
char *str /* text string */
)
{
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&protostats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (protostats.fp != NULL) {
fprintf(protostats.fp, "%lu %s %s\n", day,
ulfptoa(&now, 3), str);
fflush(protostats.fp);
}
}
#ifdef AUTOKEY
/*
* record_crypto_stats - write crypto statistics to file
*
* file format:
* day (mjd)
* time (s past midnight)
* peer ip address
* text message
*/
void
record_crypto_stats(
sockaddr_u *addr,
const char *text /* text message */
)
{
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&cryptostats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (cryptostats.fp != NULL) {
if (addr == NULL)
fprintf(cryptostats.fp, "%lu %s 0.0.0.0 %s\n",
day, ulfptoa(&now, 3), text);
else
fprintf(cryptostats.fp, "%lu %s %s %s\n",
day, ulfptoa(&now, 3), stoa(addr), text);
fflush(cryptostats.fp);
}
}
#endif /* AUTOKEY */
#ifdef DEBUG_TIMING
/*
* record_timing_stats - write timing statistics to file
*
* file format:
* day (mjd)
* time (s past midnight)
* text message
*/
void
record_timing_stats(
const char *text /* text message */
)
{
static unsigned int flshcnt;
l_fp now;
u_long day;
if (!stats_control)
return;
get_systime(&now);
filegen_setup(&timingstats, now.l_ui);
day = now.l_ui / 86400 + MJD_1900;
now.l_ui %= 86400;
if (timingstats.fp != NULL) {
fprintf(timingstats.fp, "%lu %s %s\n", day, lfptoa(&now,
3), text);
if (++flshcnt % 100 == 0)
fflush(timingstats.fp);
}
}
#endif
/*
* leap_file - read leapseconds file
*
* Read the ERTS leapsecond file in NIST text format and extract the
* NTP seconds of the latest leap and TAI offset after the leap.
*/
static int
leap_file(
FILE *fp /* file handle */
)
{
char buf[NTP_MAXSTRLEN]; /* file line buffer */
u_long leap; /* NTP time at leap */
u_long expire; /* NTP time when file expires */
int offset; /* TAI offset at leap (s) */
int i;
/*
* Read and parse the leapseconds file. Empty lines and comments
* are ignored. A line beginning with #@ contains the file
* expiration time in NTP seconds. Other lines begin with two
* integers followed by junk or comments. The first integer is
* the NTP seconds at the leap, the second is the TAI offset
* after the leap.
*/
offset = 0;
leap = 0;
expire = 0;
i = 10;
while (fgets(buf, NTP_MAXSTRLEN - 1, fp) != NULL) {
if (strlen(buf) < 1)
continue;
if (buf[0] == '#') {
if (strlen(buf) < 3)
continue;
/*
* Note the '@' flag was used only in the 2006
* table; previious to that the flag was '$'.
*/
if (buf[1] == '@' || buf[1] == '$') {
if (sscanf(&buf[2], "%lu", &expire) !=
1)
return (-1);
continue;
}
}
if (sscanf(buf, "%lu %d", &leap, &offset) == 2) {
/*
* Valid offsets must increase by one for each
* leap.
*/
if (i++ != offset)
return (-1);
}
}
/*
* There must be at least one leap.
*/
if (i == 10)
return (-1);
leap_tai = offset;
leap_sec = leap;
leap_expire = expire;
return (0);
}
/*
* leap_month - returns seconds until the end of the month.
*/
u_long
leap_month(
u_long sec /* current NTP second */
)
{
int leap;
int32 year, month;
u_int32 ndays;
ntpcal_split tmp;
vint64 tvl;
/* --*-- expand time and split to days */
tvl = ntpcal_ntp_to_ntp(sec, NULL);
tmp = ntpcal_daysplit(&tvl);
/* --*-- split to years and days in year */
tmp = ntpcal_split_eradays(tmp.hi + DAY_NTP_STARTS - 1, &leap);
year = tmp.hi;
/* --*-- split days of year to month */
tmp = ntpcal_split_yeardays(tmp.lo, leap);
month = tmp.hi;
/* --*-- get nominal start of next month */
ndays = ntpcal_edate_to_eradays(year, month+1, 0) + 1 - DAY_NTP_STARTS;
return (u_int32)(ndays*SECSPERDAY - sec);
}
/*
* getauthkeys - read the authentication keys from the specified file
*/
void
getauthkeys(
const char *keyfile
)
{
int len;
len = strlen(keyfile);
if (!len)
return;
#ifndef SYS_WINNT
key_file_name = erealloc(key_file_name, len + 1);
memcpy(key_file_name, keyfile, len + 1);
#else
key_file_name = erealloc(key_file_name, _MAX_PATH);
if (len + 1 > _MAX_PATH)
return;
if (!ExpandEnvironmentStrings(keyfile, key_file_name,
_MAX_PATH)) {
msyslog(LOG_ERR,
"ExpandEnvironmentStrings(KEY_FILE) failed: %m");
strncpy(key_file_name, keyfile, _MAX_PATH);
}
#endif /* SYS_WINNT */
authreadkeys(key_file_name);
}
/*
* rereadkeys - read the authentication key file over again.
*/
void
rereadkeys(void)
{
if (NULL != key_file_name)
authreadkeys(key_file_name);
}
#if notyet
/*
* ntp_exit - document explicitly that ntpd has exited
*/
void
ntp_exit(int retval)
{
msyslog(LOG_ERR, "EXITING with return code %d", retval);
exit(retval);
}
#endif
/*
* fstostr - prettyprint NTP seconds
*/
char * fstostr(
time_t ntp_stamp
)
{
char * buf;
struct tm * tm;
time_t unix_stamp;
LIB_GETBUF(buf);
unix_stamp = ntp_stamp - JAN_1970;
tm = gmtime(&unix_stamp);
if (NULL == tm)
#ifdef WAIT_FOR_NTP_CRYPTO_C_CALLERS_ABLE_TO_HANDLE_MORE_THAN_20_CHARS
msnprintf(buf, LIB_BUFLENGTH, "gmtime: %m");
#else
strncpy(buf, "gmtime() error", LIB_BUFLENGTH);
#endif
else
snprintf(buf, LIB_BUFLENGTH, "%04d%02d%02d%02d%02d",
tm->tm_year + 1900, tm->tm_mon + 1,
tm->tm_mday, tm->tm_hour, tm->tm_min);
return buf;
}
/*
* ntpd_time_stepped is called back by step_systime(), allowing ntpd
* to do any one-time processing necessitated by the step.
*/
void
ntpd_time_stepped(void)
{
u_int saved_mon_enabled;
/*
* flush the monitor MRU list which contains l_fp timestamps
* which should not be compared across the step.
*/
if (MON_OFF != mon_enabled) {
saved_mon_enabled = mon_enabled;
mon_stop(MON_OFF);
mon_start(saved_mon_enabled);
}
/* inform interpolating Windows code to allow time to go back */
#ifdef SYS_WINNT
win_time_stepped();
#endif
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1658_3 |
crossvul-cpp_data_bad_3174_1 | /*
* llc_sap.c - driver routines for SAP component.
*
* Copyright (c) 1997 by Procom Technology, Inc.
* 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
*
* This program can be redistributed or modified under the terms of the
* GNU General Public License as published by the Free Software Foundation.
* This program is distributed without any warranty or implied warranty
* of merchantability or fitness for a particular purpose.
*
* See the GNU General Public License for more details.
*/
#include <net/llc.h>
#include <net/llc_if.h>
#include <net/llc_conn.h>
#include <net/llc_pdu.h>
#include <net/llc_sap.h>
#include <net/llc_s_ac.h>
#include <net/llc_s_ev.h>
#include <net/llc_s_st.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <linux/llc.h>
#include <linux/slab.h>
static int llc_mac_header_len(unsigned short devtype)
{
switch (devtype) {
case ARPHRD_ETHER:
case ARPHRD_LOOPBACK:
return sizeof(struct ethhdr);
}
return 0;
}
/**
* llc_alloc_frame - allocates sk_buff for frame
* @dev: network device this skb will be sent over
* @type: pdu type to allocate
* @data_size: data size to allocate
*
* Allocates an sk_buff for frame and initializes sk_buff fields.
* Returns allocated skb or %NULL when out of memory.
*/
struct sk_buff *llc_alloc_frame(struct sock *sk, struct net_device *dev,
u8 type, u32 data_size)
{
int hlen = type == LLC_PDU_TYPE_U ? 3 : 4;
struct sk_buff *skb;
hlen += llc_mac_header_len(dev->type);
skb = alloc_skb(hlen + data_size, GFP_ATOMIC);
if (skb) {
skb_reset_mac_header(skb);
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
skb->protocol = htons(ETH_P_802_2);
skb->dev = dev;
if (sk != NULL)
skb_set_owner_w(skb, sk);
}
return skb;
}
void llc_save_primitive(struct sock *sk, struct sk_buff *skb, u8 prim)
{
struct sockaddr_llc *addr;
/* save primitive for use by the user. */
addr = llc_ui_skb_cb(skb);
memset(addr, 0, sizeof(*addr));
addr->sllc_family = sk->sk_family;
addr->sllc_arphrd = skb->dev->type;
addr->sllc_test = prim == LLC_TEST_PRIM;
addr->sllc_xid = prim == LLC_XID_PRIM;
addr->sllc_ua = prim == LLC_DATAUNIT_PRIM;
llc_pdu_decode_sa(skb, addr->sllc_mac);
llc_pdu_decode_ssap(skb, &addr->sllc_sap);
}
/**
* llc_sap_rtn_pdu - Informs upper layer on rx of an UI, XID or TEST pdu.
* @sap: pointer to SAP
* @skb: received pdu
*/
void llc_sap_rtn_pdu(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb);
switch (LLC_U_PDU_RSP(pdu)) {
case LLC_1_PDU_CMD_TEST:
ev->prim = LLC_TEST_PRIM; break;
case LLC_1_PDU_CMD_XID:
ev->prim = LLC_XID_PRIM; break;
case LLC_1_PDU_CMD_UI:
ev->prim = LLC_DATAUNIT_PRIM; break;
}
ev->ind_cfm_flag = LLC_IND;
}
/**
* llc_find_sap_trans - finds transition for event
* @sap: pointer to SAP
* @skb: happened event
*
* This function finds transition that matches with happened event.
* Returns the pointer to found transition on success or %NULL for
* failure.
*/
static struct llc_sap_state_trans *llc_find_sap_trans(struct llc_sap *sap,
struct sk_buff *skb)
{
int i = 0;
struct llc_sap_state_trans *rc = NULL;
struct llc_sap_state_trans **next_trans;
struct llc_sap_state *curr_state = &llc_sap_state_table[sap->state - 1];
/*
* Search thru events for this state until list exhausted or until
* its obvious the event is not valid for the current state
*/
for (next_trans = curr_state->transitions; next_trans[i]->ev; i++)
if (!next_trans[i]->ev(sap, skb)) {
rc = next_trans[i]; /* got event match; return it */
break;
}
return rc;
}
/**
* llc_exec_sap_trans_actions - execute actions related to event
* @sap: pointer to SAP
* @trans: pointer to transition that it's actions must be performed
* @skb: happened event.
*
* This function executes actions that is related to happened event.
* Returns 0 for success and 1 for failure of at least one action.
*/
static int llc_exec_sap_trans_actions(struct llc_sap *sap,
struct llc_sap_state_trans *trans,
struct sk_buff *skb)
{
int rc = 0;
const llc_sap_action_t *next_action = trans->ev_actions;
for (; next_action && *next_action; next_action++)
if ((*next_action)(sap, skb))
rc = 1;
return rc;
}
/**
* llc_sap_next_state - finds transition, execs actions & change SAP state
* @sap: pointer to SAP
* @skb: happened event
*
* This function finds transition that matches with happened event, then
* executes related actions and finally changes state of SAP. It returns
* 0 on success and 1 for failure.
*/
static int llc_sap_next_state(struct llc_sap *sap, struct sk_buff *skb)
{
int rc = 1;
struct llc_sap_state_trans *trans;
if (sap->state > LLC_NR_SAP_STATES)
goto out;
trans = llc_find_sap_trans(sap, skb);
if (!trans)
goto out;
/*
* Got the state to which we next transition; perform the actions
* associated with this transition before actually transitioning to the
* next state
*/
rc = llc_exec_sap_trans_actions(sap, trans, skb);
if (rc)
goto out;
/*
* Transition SAP to next state if all actions execute successfully
*/
sap->state = trans->next_state;
out:
return rc;
}
/**
* llc_sap_state_process - sends event to SAP state machine
* @sap: sap to use
* @skb: pointer to occurred event
*
* After executing actions of the event, upper layer will be indicated
* if needed(on receiving an UI frame). sk can be null for the
* datalink_proto case.
*/
static void llc_sap_state_process(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
/*
* We have to hold the skb, because llc_sap_next_state
* will kfree it in the sending path and we need to
* look at the skb->cb, where we encode llc_sap_state_ev.
*/
skb_get(skb);
ev->ind_cfm_flag = 0;
llc_sap_next_state(sap, skb);
if (ev->ind_cfm_flag == LLC_IND) {
if (skb->sk->sk_state == TCP_LISTEN)
kfree_skb(skb);
else {
llc_save_primitive(skb->sk, skb, ev->prim);
/* queue skb to the user. */
if (sock_queue_rcv_skb(skb->sk, skb))
kfree_skb(skb);
}
}
kfree_skb(skb);
}
/**
* llc_build_and_send_test_pkt - TEST interface for upper layers.
* @sap: sap to use
* @skb: packet to send
* @dmac: destination mac address
* @dsap: destination sap
*
* This function is called when upper layer wants to send a TEST pdu.
* Returns 0 for success, 1 otherwise.
*/
void llc_build_and_send_test_pkt(struct llc_sap *sap,
struct sk_buff *skb, u8 *dmac, u8 dsap)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->saddr.lsap = sap->laddr.lsap;
ev->daddr.lsap = dsap;
memcpy(ev->saddr.mac, skb->dev->dev_addr, IFHWADDRLEN);
memcpy(ev->daddr.mac, dmac, IFHWADDRLEN);
ev->type = LLC_SAP_EV_TYPE_PRIM;
ev->prim = LLC_TEST_PRIM;
ev->prim_type = LLC_PRIM_TYPE_REQ;
llc_sap_state_process(sap, skb);
}
/**
* llc_build_and_send_xid_pkt - XID interface for upper layers
* @sap: sap to use
* @skb: packet to send
* @dmac: destination mac address
* @dsap: destination sap
*
* This function is called when upper layer wants to send a XID pdu.
* Returns 0 for success, 1 otherwise.
*/
void llc_build_and_send_xid_pkt(struct llc_sap *sap, struct sk_buff *skb,
u8 *dmac, u8 dsap)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->saddr.lsap = sap->laddr.lsap;
ev->daddr.lsap = dsap;
memcpy(ev->saddr.mac, skb->dev->dev_addr, IFHWADDRLEN);
memcpy(ev->daddr.mac, dmac, IFHWADDRLEN);
ev->type = LLC_SAP_EV_TYPE_PRIM;
ev->prim = LLC_XID_PRIM;
ev->prim_type = LLC_PRIM_TYPE_REQ;
llc_sap_state_process(sap, skb);
}
/**
* llc_sap_rcv - sends received pdus to the sap state machine
* @sap: current sap component structure.
* @skb: received frame.
*
* Sends received pdus to the sap state machine.
*/
static void llc_sap_rcv(struct llc_sap *sap, struct sk_buff *skb,
struct sock *sk)
{
struct llc_sap_state_ev *ev = llc_sap_ev(skb);
ev->type = LLC_SAP_EV_TYPE_PDU;
ev->reason = 0;
skb->sk = sk;
llc_sap_state_process(sap, skb);
}
static inline bool llc_dgram_match(const struct llc_sap *sap,
const struct llc_addr *laddr,
const struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
return sk->sk_type == SOCK_DGRAM &&
llc->laddr.lsap == laddr->lsap &&
ether_addr_equal(llc->laddr.mac, laddr->mac);
}
/**
* llc_lookup_dgram - Finds dgram socket for the local sap/mac
* @sap: SAP
* @laddr: address of local LLC (MAC + SAP)
*
* Search socket list of the SAP and finds connection using the local
* mac, and local sap. Returns pointer for socket found, %NULL otherwise.
*/
static struct sock *llc_lookup_dgram(struct llc_sap *sap,
const struct llc_addr *laddr)
{
struct sock *rc;
struct hlist_nulls_node *node;
int slot = llc_sk_laddr_hashfn(sap, laddr);
struct hlist_nulls_head *laddr_hb = &sap->sk_laddr_hash[slot];
rcu_read_lock_bh();
again:
sk_nulls_for_each_rcu(rc, node, laddr_hb) {
if (llc_dgram_match(sap, laddr, rc)) {
/* Extra checks required by SLAB_DESTROY_BY_RCU */
if (unlikely(!atomic_inc_not_zero(&rc->sk_refcnt)))
goto again;
if (unlikely(llc_sk(rc)->sap != sap ||
!llc_dgram_match(sap, laddr, rc))) {
sock_put(rc);
continue;
}
goto found;
}
}
rc = NULL;
/*
* if the nulls value we got at the end of this lookup is
* not the expected one, we must restart lookup.
* We probably met an item that was moved to another chain.
*/
if (unlikely(get_nulls_value(node) != slot))
goto again;
found:
rcu_read_unlock_bh();
return rc;
}
static inline bool llc_mcast_match(const struct llc_sap *sap,
const struct llc_addr *laddr,
const struct sk_buff *skb,
const struct sock *sk)
{
struct llc_sock *llc = llc_sk(sk);
return sk->sk_type == SOCK_DGRAM &&
llc->laddr.lsap == laddr->lsap &&
llc->dev == skb->dev;
}
static void llc_do_mcast(struct llc_sap *sap, struct sk_buff *skb,
struct sock **stack, int count)
{
struct sk_buff *skb1;
int i;
for (i = 0; i < count; i++) {
skb1 = skb_clone(skb, GFP_ATOMIC);
if (!skb1) {
sock_put(stack[i]);
continue;
}
llc_sap_rcv(sap, skb1, stack[i]);
sock_put(stack[i]);
}
}
/**
* llc_sap_mcast - Deliver multicast PDU's to all matching datagram sockets.
* @sap: SAP
* @laddr: address of local LLC (MAC + SAP)
*
* Search socket list of the SAP and finds connections with same sap.
* Deliver clone to each.
*/
static void llc_sap_mcast(struct llc_sap *sap,
const struct llc_addr *laddr,
struct sk_buff *skb)
{
int i = 0, count = 256 / sizeof(struct sock *);
struct sock *sk, *stack[count];
struct llc_sock *llc;
struct hlist_head *dev_hb = llc_sk_dev_hash(sap, skb->dev->ifindex);
spin_lock_bh(&sap->sk_lock);
hlist_for_each_entry(llc, dev_hb, dev_hash_node) {
sk = &llc->sk;
if (!llc_mcast_match(sap, laddr, skb, sk))
continue;
sock_hold(sk);
if (i < count)
stack[i++] = sk;
else {
llc_do_mcast(sap, skb, stack, i);
i = 0;
}
}
spin_unlock_bh(&sap->sk_lock);
llc_do_mcast(sap, skb, stack, i);
}
void llc_sap_handler(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_addr laddr;
llc_pdu_decode_da(skb, laddr.mac);
llc_pdu_decode_dsap(skb, &laddr.lsap);
if (is_multicast_ether_addr(laddr.mac)) {
llc_sap_mcast(sap, &laddr, skb);
kfree_skb(skb);
} else {
struct sock *sk = llc_lookup_dgram(sap, &laddr);
if (sk) {
llc_sap_rcv(sap, skb, sk);
sock_put(sk);
} else
kfree_skb(skb);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3174_1 |
crossvul-cpp_data_good_3070_4 | /*
* Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* ====================================================================
* Copyright 2005 Nokia. All rights reserved.
*
* The portions of the attached software ("Contribution") is developed by
* Nokia Corporation and is licensed pursuant to the OpenSSL open source
* license.
*
* The Contribution, originally written by Mika Kousa and Pasi Eronen of
* Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
* support (see RFC 4279) to OpenSSL.
*
* No patent licenses or other rights except those expressly stated in
* the OpenSSL open source license shall be deemed granted or received
* expressly, by implication, estoppel, or otherwise.
*
* No assurances are provided by Nokia that the Contribution does not
* infringe the patent or other intellectual property rights of any third
* party or that the license provides you with all the necessary rights
* to make use of the Contribution.
*
* THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
* ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
* SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
* OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
* OTHERWISE.
*/
#include <stdio.h>
#include "ssl_locl.h"
#include <openssl/comp.h>
#include <openssl/evp.h>
#include <openssl/kdf.h>
#include <openssl/rand.h>
/* seed1 through seed5 are concatenated */
static int tls1_PRF(SSL *s,
const void *seed1, int seed1_len,
const void *seed2, int seed2_len,
const void *seed3, int seed3_len,
const void *seed4, int seed4_len,
const void *seed5, int seed5_len,
const unsigned char *sec, int slen,
unsigned char *out, int olen)
{
const EVP_MD *md = ssl_prf_md(s);
EVP_PKEY_CTX *pctx = NULL;
int ret = 0;
size_t outlen = olen;
if (md == NULL) {
/* Should never happen */
SSLerr(SSL_F_TLS1_PRF, ERR_R_INTERNAL_ERROR);
return 0;
}
pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_TLS1_PRF, NULL);
if (pctx == NULL || EVP_PKEY_derive_init(pctx) <= 0
|| EVP_PKEY_CTX_set_tls1_prf_md(pctx, md) <= 0
|| EVP_PKEY_CTX_set1_tls1_prf_secret(pctx, sec, slen) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed1, seed1_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed2, seed2_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed3, seed3_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed4, seed4_len) <= 0)
goto err;
if (EVP_PKEY_CTX_add1_tls1_prf_seed(pctx, seed5, seed5_len) <= 0)
goto err;
if (EVP_PKEY_derive(pctx, out, &outlen) <= 0)
goto err;
ret = 1;
err:
EVP_PKEY_CTX_free(pctx);
return ret;
}
static int tls1_generate_key_block(SSL *s, unsigned char *km, int num)
{
int ret;
ret = tls1_PRF(s,
TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE, s->s3->server_random,
SSL3_RANDOM_SIZE, s->s3->client_random, SSL3_RANDOM_SIZE,
NULL, 0, NULL, 0, s->session->master_key,
s->session->master_key_length, km, num);
return ret;
}
int tls1_change_cipher_state(SSL *s, int which)
{
unsigned char *p, *mac_secret;
unsigned char tmp1[EVP_MAX_KEY_LENGTH];
unsigned char tmp2[EVP_MAX_KEY_LENGTH];
unsigned char iv1[EVP_MAX_IV_LENGTH * 2];
unsigned char iv2[EVP_MAX_IV_LENGTH * 2];
unsigned char *ms, *key, *iv;
EVP_CIPHER_CTX *dd;
const EVP_CIPHER *c;
#ifndef OPENSSL_NO_COMP
const SSL_COMP *comp;
#endif
const EVP_MD *m;
int mac_type;
int *mac_secret_size;
EVP_MD_CTX *mac_ctx;
EVP_PKEY *mac_key;
int n, i, j, k, cl;
int reuse_dd = 0;
c = s->s3->tmp.new_sym_enc;
m = s->s3->tmp.new_hash;
mac_type = s->s3->tmp.new_mac_pkey_type;
#ifndef OPENSSL_NO_COMP
comp = s->s3->tmp.new_compression;
#endif
if (which & SSL3_CC_READ) {
if (s->tlsext_use_etm)
s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
else
s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_READ;
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_READ_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_READ_MAC_STREAM;
if (s->enc_read_ctx != NULL)
reuse_dd = 1;
else if ((s->enc_read_ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
else
/*
* make sure it's initialised in case we exit later with an error
*/
EVP_CIPHER_CTX_reset(s->enc_read_ctx);
dd = s->enc_read_ctx;
mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
if (mac_ctx == NULL)
goto err;
#ifndef OPENSSL_NO_COMP
COMP_CTX_free(s->expand);
s->expand = NULL;
if (comp != NULL) {
s->expand = COMP_CTX_new(comp->method);
if (s->expand == NULL) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
/*
* this is done by dtls1_reset_seq_numbers for DTLS
*/
if (!SSL_IS_DTLS(s))
RECORD_LAYER_reset_read_sequence(&s->rlayer);
mac_secret = &(s->s3->read_mac_secret[0]);
mac_secret_size = &(s->s3->read_mac_secret_size);
} else {
if (s->tlsext_use_etm)
s->s3->flags |= TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE;
else
s->s3->flags &= ~TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE;
if (s->s3->tmp.new_cipher->algorithm2 & TLS1_STREAM_MAC)
s->mac_flags |= SSL_MAC_FLAG_WRITE_MAC_STREAM;
else
s->mac_flags &= ~SSL_MAC_FLAG_WRITE_MAC_STREAM;
if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
reuse_dd = 1;
else if ((s->enc_write_ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
dd = s->enc_write_ctx;
if (SSL_IS_DTLS(s)) {
mac_ctx = EVP_MD_CTX_new();
if (mac_ctx == NULL)
goto err;
s->write_hash = mac_ctx;
} else {
mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
if (mac_ctx == NULL)
goto err;
}
#ifndef OPENSSL_NO_COMP
COMP_CTX_free(s->compress);
s->compress = NULL;
if (comp != NULL) {
s->compress = COMP_CTX_new(comp->method);
if (s->compress == NULL) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE,
SSL_R_COMPRESSION_LIBRARY_ERROR);
goto err2;
}
}
#endif
/*
* this is done by dtls1_reset_seq_numbers for DTLS
*/
if (!SSL_IS_DTLS(s))
RECORD_LAYER_reset_write_sequence(&s->rlayer);
mac_secret = &(s->s3->write_mac_secret[0]);
mac_secret_size = &(s->s3->write_mac_secret_size);
}
if (reuse_dd)
EVP_CIPHER_CTX_reset(dd);
p = s->s3->tmp.key_block;
i = *mac_secret_size = s->s3->tmp.new_mac_secret_size;
cl = EVP_CIPHER_key_length(c);
j = cl;
/* Was j=(exp)?5:EVP_CIPHER_key_length(c); */
/* If GCM/CCM mode only part of IV comes from PRF */
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
k = EVP_GCM_TLS_FIXED_IV_LEN;
else if (EVP_CIPHER_mode(c) == EVP_CIPH_CCM_MODE)
k = EVP_CCM_TLS_FIXED_IV_LEN;
else
k = EVP_CIPHER_iv_length(c);
if ((which == SSL3_CHANGE_CIPHER_CLIENT_WRITE) ||
(which == SSL3_CHANGE_CIPHER_SERVER_READ)) {
ms = &(p[0]);
n = i + i;
key = &(p[n]);
n += j + j;
iv = &(p[n]);
n += k + k;
} else {
n = i;
ms = &(p[n]);
n += i + j;
key = &(p[n]);
n += j + k;
iv = &(p[n]);
n += k;
}
if (n > s->s3->tmp.key_block_length) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
memcpy(mac_secret, ms, i);
if (!(EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER)) {
mac_key = EVP_PKEY_new_mac_key(mac_type, NULL,
mac_secret, *mac_secret_size);
if (mac_key == NULL
|| EVP_DigestSignInit(mac_ctx, NULL, m, NULL, mac_key) <= 0) {
EVP_PKEY_free(mac_key);
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
EVP_PKEY_free(mac_key);
}
#ifdef SSL_DEBUG
printf("which = %04X\nmac key=", which);
{
int z;
for (z = 0; z < i; z++)
printf("%02X%c", ms[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE) {
if (!EVP_CipherInit_ex(dd, c, NULL, key, NULL, (which & SSL3_CC_WRITE))
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_GCM_SET_IV_FIXED, k, iv)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
} else if (EVP_CIPHER_mode(c) == EVP_CIPH_CCM_MODE) {
int taglen;
if (s->s3->tmp.
new_cipher->algorithm_enc & (SSL_AES128CCM8 | SSL_AES256CCM8))
taglen = 8;
else
taglen = 16;
if (!EVP_CipherInit_ex(dd, c, NULL, NULL, NULL, (which & SSL3_CC_WRITE))
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_IVLEN, 12, NULL)
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_TAG, taglen, NULL)
|| !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_CCM_SET_IV_FIXED, k, iv)
|| !EVP_CipherInit_ex(dd, NULL, NULL, key, NULL, -1)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
} else {
if (!EVP_CipherInit_ex(dd, c, NULL, key, iv, (which & SSL3_CC_WRITE))) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
}
/* Needed for "composite" AEADs, such as RC4-HMAC-MD5 */
if ((EVP_CIPHER_flags(c) & EVP_CIPH_FLAG_AEAD_CIPHER) && *mac_secret_size
&& !EVP_CIPHER_CTX_ctrl(dd, EVP_CTRL_AEAD_SET_MAC_KEY,
*mac_secret_size, mac_secret)) {
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
goto err2;
}
#ifdef OPENSSL_SSL_TRACE_CRYPTO
if (s->msg_callback) {
int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
if (*mac_secret_size)
s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_MAC,
mac_secret, *mac_secret_size,
s, s->msg_callback_arg);
if (c->key_len)
s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
key, c->key_len, s, s->msg_callback_arg);
if (k) {
if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
wh |= TLS1_RT_CRYPTO_FIXED_IV;
else
wh |= TLS1_RT_CRYPTO_IV;
s->msg_callback(2, s->version, wh, iv, k, s, s->msg_callback_arg);
}
}
#endif
#ifdef SSL_DEBUG
printf("which = %04X\nkey=", which);
{
int z;
for (z = 0; z < EVP_CIPHER_key_length(c); z++)
printf("%02X%c", key[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\niv=");
{
int z;
for (z = 0; z < k; z++)
printf("%02X%c", iv[z], ((z + 1) % 16) ? ' ' : '\n');
}
printf("\n");
#endif
OPENSSL_cleanse(tmp1, sizeof(tmp1));
OPENSSL_cleanse(tmp2, sizeof(tmp1));
OPENSSL_cleanse(iv1, sizeof(iv1));
OPENSSL_cleanse(iv2, sizeof(iv2));
return (1);
err:
SSLerr(SSL_F_TLS1_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
err2:
OPENSSL_cleanse(tmp1, sizeof(tmp1));
OPENSSL_cleanse(tmp2, sizeof(tmp1));
OPENSSL_cleanse(iv1, sizeof(iv1));
OPENSSL_cleanse(iv2, sizeof(iv2));
return (0);
}
int tls1_setup_key_block(SSL *s)
{
unsigned char *p;
const EVP_CIPHER *c;
const EVP_MD *hash;
int num;
SSL_COMP *comp;
int mac_type = NID_undef, mac_secret_size = 0;
int ret = 0;
if (s->s3->tmp.key_block_length != 0)
return (1);
if (!ssl_cipher_get_evp(s->session, &c, &hash, &mac_type, &mac_secret_size,
&comp, s->tlsext_use_etm)) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
return (0);
}
s->s3->tmp.new_sym_enc = c;
s->s3->tmp.new_hash = hash;
s->s3->tmp.new_mac_pkey_type = mac_type;
s->s3->tmp.new_mac_secret_size = mac_secret_size;
num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c);
num *= 2;
ssl3_cleanup_key_block(s);
if ((p = OPENSSL_malloc(num)) == NULL) {
SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE);
goto err;
}
s->s3->tmp.key_block_length = num;
s->s3->tmp.key_block = p;
#ifdef SSL_DEBUG
printf("client random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->client_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("server random\n");
{
int z;
for (z = 0; z < SSL3_RANDOM_SIZE; z++)
printf("%02X%c", s->s3->server_random[z],
((z + 1) % 16) ? ' ' : '\n');
}
printf("master key\n");
{
int z;
for (z = 0; z < s->session->master_key_length; z++)
printf("%02X%c", s->session->master_key[z],
((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!tls1_generate_key_block(s, p, num))
goto err;
#ifdef SSL_DEBUG
printf("\nkey block\n");
{
int z;
for (z = 0; z < num; z++)
printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n');
}
#endif
if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)
&& s->method->version <= TLS1_VERSION) {
/*
* enable vulnerability countermeasure for CBC ciphers with known-IV
* problem (http://www.openssl.org/~bodo/tls-cbc.txt)
*/
s->s3->need_empty_fragments = 1;
if (s->session->cipher != NULL) {
if (s->session->cipher->algorithm_enc == SSL_eNULL)
s->s3->need_empty_fragments = 0;
#ifndef OPENSSL_NO_RC4
if (s->session->cipher->algorithm_enc == SSL_RC4)
s->s3->need_empty_fragments = 0;
#endif
}
}
ret = 1;
err:
return (ret);
}
int tls1_final_finish_mac(SSL *s, const char *str, int slen, unsigned char *out)
{
int hashlen;
unsigned char hash[EVP_MAX_MD_SIZE];
if (!ssl3_digest_cached_records(s, 0))
return 0;
hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
if (hashlen == 0)
return 0;
if (!tls1_PRF(s, str, slen, hash, hashlen, NULL, 0, NULL, 0, NULL, 0,
s->session->master_key, s->session->master_key_length,
out, TLS1_FINISH_MAC_LENGTH))
return 0;
OPENSSL_cleanse(hash, hashlen);
return TLS1_FINISH_MAC_LENGTH;
}
int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
int len)
{
if (s->session->flags & SSL_SESS_FLAG_EXTMS) {
unsigned char hash[EVP_MAX_MD_SIZE * 2];
int hashlen;
/*
* Digest cached records keeping record buffer (if present): this wont
* affect client auth because we're freezing the buffer at the same
* point (after client key exchange and before certificate verify)
*/
if (!ssl3_digest_cached_records(s, 1))
return -1;
hashlen = ssl_handshake_hash(s, hash, sizeof(hash));
#ifdef SSL_DEBUG
fprintf(stderr, "Handshake hashes:\n");
BIO_dump_fp(stderr, (char *)hash, hashlen);
#endif
tls1_PRF(s,
TLS_MD_EXTENDED_MASTER_SECRET_CONST,
TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE,
hash, hashlen,
NULL, 0,
NULL, 0,
NULL, 0, p, len, s->session->master_key,
SSL3_MASTER_SECRET_SIZE);
OPENSSL_cleanse(hash, hashlen);
} else {
tls1_PRF(s,
TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE,
s->s3->client_random, SSL3_RANDOM_SIZE,
NULL, 0,
s->s3->server_random, SSL3_RANDOM_SIZE,
NULL, 0, p, len, s->session->master_key,
SSL3_MASTER_SECRET_SIZE);
}
#ifdef SSL_DEBUG
fprintf(stderr, "Premaster Secret:\n");
BIO_dump_fp(stderr, (char *)p, len);
fprintf(stderr, "Client Random:\n");
BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
fprintf(stderr, "Server Random:\n");
BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
fprintf(stderr, "Master Secret:\n");
BIO_dump_fp(stderr, (char *)s->session->master_key,
SSL3_MASTER_SECRET_SIZE);
#endif
#ifdef OPENSSL_SSL_TRACE_CRYPTO
if (s->msg_callback) {
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
p, len, s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
s->s3->client_random, SSL3_RANDOM_SIZE,
s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
s->s3->server_random, SSL3_RANDOM_SIZE,
s, s->msg_callback_arg);
s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
s->session->master_key,
SSL3_MASTER_SECRET_SIZE, s, s->msg_callback_arg);
}
#endif
return (SSL3_MASTER_SECRET_SIZE);
}
int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
const char *label, size_t llen,
const unsigned char *context,
size_t contextlen, int use_context)
{
unsigned char *val = NULL;
size_t vallen = 0, currentvalpos;
int rv;
/*
* construct PRF arguments we construct the PRF argument ourself rather
* than passing separate values into the TLS PRF to ensure that the
* concatenation of values does not create a prohibited label.
*/
vallen = llen + SSL3_RANDOM_SIZE * 2;
if (use_context) {
vallen += 2 + contextlen;
}
val = OPENSSL_malloc(vallen);
if (val == NULL)
goto err2;
currentvalpos = 0;
memcpy(val + currentvalpos, (unsigned char *)label, llen);
currentvalpos += llen;
memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
currentvalpos += SSL3_RANDOM_SIZE;
if (use_context) {
val[currentvalpos] = (contextlen >> 8) & 0xff;
currentvalpos++;
val[currentvalpos] = contextlen & 0xff;
currentvalpos++;
if ((contextlen > 0) || (context != NULL)) {
memcpy(val + currentvalpos, context, contextlen);
}
}
/*
* disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
* label len) = 15, so size of val > max(prohibited label len) = 15 and
* the comparisons won't have buffer overflow
*/
if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
TLS_MD_SERVER_FINISH_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
TLS_MD_MASTER_SECRET_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_EXTENDED_MASTER_SECRET_CONST,
TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE) == 0)
goto err1;
if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0)
goto err1;
rv = tls1_PRF(s,
val, vallen,
NULL, 0,
NULL, 0,
NULL, 0,
NULL, 0,
s->session->master_key, s->session->master_key_length,
out, olen);
goto ret;
err1:
SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
rv = 0;
goto ret;
err2:
SSLerr(SSL_F_TLS1_EXPORT_KEYING_MATERIAL, ERR_R_MALLOC_FAILURE);
rv = 0;
ret:
OPENSSL_clear_free(val, vallen);
return (rv);
}
int tls1_alert_code(int code)
{
switch (code) {
case SSL_AD_CLOSE_NOTIFY:
return (SSL3_AD_CLOSE_NOTIFY);
case SSL_AD_UNEXPECTED_MESSAGE:
return (SSL3_AD_UNEXPECTED_MESSAGE);
case SSL_AD_BAD_RECORD_MAC:
return (SSL3_AD_BAD_RECORD_MAC);
case SSL_AD_DECRYPTION_FAILED:
return (TLS1_AD_DECRYPTION_FAILED);
case SSL_AD_RECORD_OVERFLOW:
return (TLS1_AD_RECORD_OVERFLOW);
case SSL_AD_DECOMPRESSION_FAILURE:
return (SSL3_AD_DECOMPRESSION_FAILURE);
case SSL_AD_HANDSHAKE_FAILURE:
return (SSL3_AD_HANDSHAKE_FAILURE);
case SSL_AD_NO_CERTIFICATE:
return (-1);
case SSL_AD_BAD_CERTIFICATE:
return (SSL3_AD_BAD_CERTIFICATE);
case SSL_AD_UNSUPPORTED_CERTIFICATE:
return (SSL3_AD_UNSUPPORTED_CERTIFICATE);
case SSL_AD_CERTIFICATE_REVOKED:
return (SSL3_AD_CERTIFICATE_REVOKED);
case SSL_AD_CERTIFICATE_EXPIRED:
return (SSL3_AD_CERTIFICATE_EXPIRED);
case SSL_AD_CERTIFICATE_UNKNOWN:
return (SSL3_AD_CERTIFICATE_UNKNOWN);
case SSL_AD_ILLEGAL_PARAMETER:
return (SSL3_AD_ILLEGAL_PARAMETER);
case SSL_AD_UNKNOWN_CA:
return (TLS1_AD_UNKNOWN_CA);
case SSL_AD_ACCESS_DENIED:
return (TLS1_AD_ACCESS_DENIED);
case SSL_AD_DECODE_ERROR:
return (TLS1_AD_DECODE_ERROR);
case SSL_AD_DECRYPT_ERROR:
return (TLS1_AD_DECRYPT_ERROR);
case SSL_AD_EXPORT_RESTRICTION:
return (TLS1_AD_EXPORT_RESTRICTION);
case SSL_AD_PROTOCOL_VERSION:
return (TLS1_AD_PROTOCOL_VERSION);
case SSL_AD_INSUFFICIENT_SECURITY:
return (TLS1_AD_INSUFFICIENT_SECURITY);
case SSL_AD_INTERNAL_ERROR:
return (TLS1_AD_INTERNAL_ERROR);
case SSL_AD_USER_CANCELLED:
return (TLS1_AD_USER_CANCELLED);
case SSL_AD_NO_RENEGOTIATION:
return (TLS1_AD_NO_RENEGOTIATION);
case SSL_AD_UNSUPPORTED_EXTENSION:
return (TLS1_AD_UNSUPPORTED_EXTENSION);
case SSL_AD_CERTIFICATE_UNOBTAINABLE:
return (TLS1_AD_CERTIFICATE_UNOBTAINABLE);
case SSL_AD_UNRECOGNIZED_NAME:
return (TLS1_AD_UNRECOGNIZED_NAME);
case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
return (TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
return (TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
case SSL_AD_UNKNOWN_PSK_IDENTITY:
return (TLS1_AD_UNKNOWN_PSK_IDENTITY);
case SSL_AD_INAPPROPRIATE_FALLBACK:
return (TLS1_AD_INAPPROPRIATE_FALLBACK);
case SSL_AD_NO_APPLICATION_PROTOCOL:
return (TLS1_AD_NO_APPLICATION_PROTOCOL);
default:
return (-1);
}
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3070_4 |
crossvul-cpp_data_bad_4728_0 | /*
* linux/kernel/fork.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
/*
* 'fork.c' contains the help-routines for the 'fork' system call
* (see also entry.S and others).
* Fork is rather simple, once you get the hang of it, but the memory
* management can be a bitch. See 'mm/memory.c': 'copy_page_range()'
*/
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/unistd.h>
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/completion.h>
#include <linux/personality.h>
#include <linux/mempolicy.h>
#include <linux/sem.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/iocontext.h>
#include <linux/key.h>
#include <linux/binfmts.h>
#include <linux/mman.h>
#include <linux/mmu_notifier.h>
#include <linux/fs.h>
#include <linux/nsproxy.h>
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/cgroup.h>
#include <linux/security.h>
#include <linux/hugetlb.h>
#include <linux/swap.h>
#include <linux/syscalls.h>
#include <linux/jiffies.h>
#include <linux/tracehook.h>
#include <linux/futex.h>
#include <linux/compat.h>
#include <linux/task_io_accounting_ops.h>
#include <linux/rcupdate.h>
#include <linux/ptrace.h>
#include <linux/mount.h>
#include <linux/audit.h>
#include <linux/memcontrol.h>
#include <linux/ftrace.h>
#include <linux/profile.h>
#include <linux/rmap.h>
#include <linux/ksm.h>
#include <linux/acct.h>
#include <linux/tsacct_kern.h>
#include <linux/cn_proc.h>
#include <linux/freezer.h>
#include <linux/delayacct.h>
#include <linux/taskstats_kern.h>
#include <linux/random.h>
#include <linux/tty.h>
#include <linux/proc_fs.h>
#include <linux/blkdev.h>
#include <linux/fs_struct.h>
#include <linux/magic.h>
#include <linux/perf_event.h>
#include <linux/posix-timers.h>
#include <linux/user-return-notifier.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <trace/events/sched.h>
/*
* Protected counters by write_lock_irq(&tasklist_lock)
*/
unsigned long total_forks; /* Handle normal Linux uptimes. */
int nr_threads; /* The idle threads do not count.. */
int max_threads; /* tunable limit on nr_threads */
DEFINE_PER_CPU(unsigned long, process_counts) = 0;
__cacheline_aligned DEFINE_RWLOCK(tasklist_lock); /* outer */
#ifdef CONFIG_PROVE_RCU
int lockdep_tasklist_lock_is_held(void)
{
return lockdep_is_held(&tasklist_lock);
}
EXPORT_SYMBOL_GPL(lockdep_tasklist_lock_is_held);
#endif /* #ifdef CONFIG_PROVE_RCU */
int nr_processes(void)
{
int cpu;
int total = 0;
for_each_possible_cpu(cpu)
total += per_cpu(process_counts, cpu);
return total;
}
#ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
# define alloc_task_struct() kmem_cache_alloc(task_struct_cachep, GFP_KERNEL)
# define free_task_struct(tsk) kmem_cache_free(task_struct_cachep, (tsk))
static struct kmem_cache *task_struct_cachep;
#endif
#ifndef __HAVE_ARCH_THREAD_INFO_ALLOCATOR
static inline struct thread_info *alloc_thread_info(struct task_struct *tsk)
{
#ifdef CONFIG_DEBUG_STACK_USAGE
gfp_t mask = GFP_KERNEL | __GFP_ZERO;
#else
gfp_t mask = GFP_KERNEL;
#endif
return (struct thread_info *)__get_free_pages(mask, THREAD_SIZE_ORDER);
}
static inline void free_thread_info(struct thread_info *ti)
{
free_pages((unsigned long)ti, THREAD_SIZE_ORDER);
}
#endif
/* SLAB cache for signal_struct structures (tsk->signal) */
static struct kmem_cache *signal_cachep;
/* SLAB cache for sighand_struct structures (tsk->sighand) */
struct kmem_cache *sighand_cachep;
/* SLAB cache for files_struct structures (tsk->files) */
struct kmem_cache *files_cachep;
/* SLAB cache for fs_struct structures (tsk->fs) */
struct kmem_cache *fs_cachep;
/* SLAB cache for vm_area_struct structures */
struct kmem_cache *vm_area_cachep;
/* SLAB cache for mm_struct structures (tsk->mm) */
static struct kmem_cache *mm_cachep;
static void account_kernel_stack(struct thread_info *ti, int account)
{
struct zone *zone = page_zone(virt_to_page(ti));
mod_zone_page_state(zone, NR_KERNEL_STACK, account);
}
void free_task(struct task_struct *tsk)
{
prop_local_destroy_single(&tsk->dirties);
account_kernel_stack(tsk->stack, -1);
free_thread_info(tsk->stack);
rt_mutex_debug_task_free(tsk);
ftrace_graph_exit_task(tsk);
free_task_struct(tsk);
}
EXPORT_SYMBOL(free_task);
static inline void free_signal_struct(struct signal_struct *sig)
{
taskstats_tgid_free(sig);
kmem_cache_free(signal_cachep, sig);
}
static inline void put_signal_struct(struct signal_struct *sig)
{
if (atomic_dec_and_test(&sig->sigcnt))
free_signal_struct(sig);
}
void __put_task_struct(struct task_struct *tsk)
{
WARN_ON(!tsk->exit_state);
WARN_ON(atomic_read(&tsk->usage));
WARN_ON(tsk == current);
exit_creds(tsk);
delayacct_tsk_free(tsk);
put_signal_struct(tsk->signal);
if (!profile_handoff_task(tsk))
free_task(tsk);
}
/*
* macro override instead of weak attribute alias, to workaround
* gcc 4.1.0 and 4.1.1 bugs with weak attribute and empty functions.
*/
#ifndef arch_task_cache_init
#define arch_task_cache_init()
#endif
void __init fork_init(unsigned long mempages)
{
#ifndef __HAVE_ARCH_TASK_STRUCT_ALLOCATOR
#ifndef ARCH_MIN_TASKALIGN
#define ARCH_MIN_TASKALIGN L1_CACHE_BYTES
#endif
/* create a slab on which task_structs can be allocated */
task_struct_cachep =
kmem_cache_create("task_struct", sizeof(struct task_struct),
ARCH_MIN_TASKALIGN, SLAB_PANIC | SLAB_NOTRACK, NULL);
#endif
/* do the arch specific task caches init */
arch_task_cache_init();
/*
* The default maximum number of threads is set to a safe
* value: the thread structures can take up at most half
* of memory.
*/
max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);
/*
* we need to allow at least 20 threads to boot a system
*/
if(max_threads < 20)
max_threads = 20;
init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
init_task.signal->rlim[RLIMIT_SIGPENDING] =
init_task.signal->rlim[RLIMIT_NPROC];
}
int __attribute__((weak)) arch_dup_task_struct(struct task_struct *dst,
struct task_struct *src)
{
*dst = *src;
return 0;
}
static struct task_struct *dup_task_struct(struct task_struct *orig)
{
struct task_struct *tsk;
struct thread_info *ti;
unsigned long *stackend;
int err;
prepare_to_copy(orig);
tsk = alloc_task_struct();
if (!tsk)
return NULL;
ti = alloc_thread_info(tsk);
if (!ti) {
free_task_struct(tsk);
return NULL;
}
err = arch_dup_task_struct(tsk, orig);
if (err)
goto out;
tsk->stack = ti;
err = prop_local_init_single(&tsk->dirties);
if (err)
goto out;
setup_thread_stack(tsk, orig);
clear_user_return_notifier(tsk);
stackend = end_of_stack(tsk);
*stackend = STACK_END_MAGIC; /* for overflow detection */
#ifdef CONFIG_CC_STACKPROTECTOR
tsk->stack_canary = get_random_int();
#endif
/* One for us, one for whoever does the "release_task()" (usually parent) */
atomic_set(&tsk->usage,2);
atomic_set(&tsk->fs_excl, 0);
#ifdef CONFIG_BLK_DEV_IO_TRACE
tsk->btrace_seq = 0;
#endif
tsk->splice_pipe = NULL;
account_kernel_stack(ti, 1);
return tsk;
out:
free_thread_info(ti);
free_task_struct(tsk);
return NULL;
}
#ifdef CONFIG_MMU
static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm)
{
struct vm_area_struct *mpnt, *tmp, **pprev;
struct rb_node **rb_link, *rb_parent;
int retval;
unsigned long charge;
struct mempolicy *pol;
down_write(&oldmm->mmap_sem);
flush_cache_dup_mm(oldmm);
/*
* Not linked in yet - no deadlock potential:
*/
down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING);
mm->locked_vm = 0;
mm->mmap = NULL;
mm->mmap_cache = NULL;
mm->free_area_cache = oldmm->mmap_base;
mm->cached_hole_size = ~0UL;
mm->map_count = 0;
cpumask_clear(mm_cpumask(mm));
mm->mm_rb = RB_ROOT;
rb_link = &mm->mm_rb.rb_node;
rb_parent = NULL;
pprev = &mm->mmap;
retval = ksm_fork(mm, oldmm);
if (retval)
goto out;
for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) {
struct file *file;
if (mpnt->vm_flags & VM_DONTCOPY) {
long pages = vma_pages(mpnt);
mm->total_vm -= pages;
vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file,
-pages);
continue;
}
charge = 0;
if (mpnt->vm_flags & VM_ACCOUNT) {
unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT;
if (security_vm_enough_memory(len))
goto fail_nomem;
charge = len;
}
tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
if (!tmp)
goto fail_nomem;
*tmp = *mpnt;
INIT_LIST_HEAD(&tmp->anon_vma_chain);
pol = mpol_dup(vma_policy(mpnt));
retval = PTR_ERR(pol);
if (IS_ERR(pol))
goto fail_nomem_policy;
vma_set_policy(tmp, pol);
if (anon_vma_fork(tmp, mpnt))
goto fail_nomem_anon_vma_fork;
tmp->vm_flags &= ~VM_LOCKED;
tmp->vm_mm = mm;
tmp->vm_next = NULL;
file = tmp->vm_file;
if (file) {
struct inode *inode = file->f_path.dentry->d_inode;
struct address_space *mapping = file->f_mapping;
get_file(file);
if (tmp->vm_flags & VM_DENYWRITE)
atomic_dec(&inode->i_writecount);
spin_lock(&mapping->i_mmap_lock);
if (tmp->vm_flags & VM_SHARED)
mapping->i_mmap_writable++;
tmp->vm_truncate_count = mpnt->vm_truncate_count;
flush_dcache_mmap_lock(mapping);
/* insert tmp into the share list, just after mpnt */
vma_prio_tree_add(tmp, mpnt);
flush_dcache_mmap_unlock(mapping);
spin_unlock(&mapping->i_mmap_lock);
}
/*
* Clear hugetlb-related page reserves for children. This only
* affects MAP_PRIVATE mappings. Faults generated by the child
* are not guaranteed to succeed, even if read-only
*/
if (is_vm_hugetlb_page(tmp))
reset_vma_resv_huge_pages(tmp);
/*
* Link in the new vma and copy the page table entries.
*/
*pprev = tmp;
pprev = &tmp->vm_next;
__vma_link_rb(mm, tmp, rb_link, rb_parent);
rb_link = &tmp->vm_rb.rb_right;
rb_parent = &tmp->vm_rb;
mm->map_count++;
retval = copy_page_range(mm, oldmm, mpnt);
if (tmp->vm_ops && tmp->vm_ops->open)
tmp->vm_ops->open(tmp);
if (retval)
goto out;
}
/* a new mm has just been created */
arch_dup_mmap(oldmm, mm);
retval = 0;
out:
up_write(&mm->mmap_sem);
flush_tlb_mm(oldmm);
up_write(&oldmm->mmap_sem);
return retval;
fail_nomem_anon_vma_fork:
mpol_put(pol);
fail_nomem_policy:
kmem_cache_free(vm_area_cachep, tmp);
fail_nomem:
retval = -ENOMEM;
vm_unacct_memory(charge);
goto out;
}
static inline int mm_alloc_pgd(struct mm_struct * mm)
{
mm->pgd = pgd_alloc(mm);
if (unlikely(!mm->pgd))
return -ENOMEM;
return 0;
}
static inline void mm_free_pgd(struct mm_struct * mm)
{
pgd_free(mm, mm->pgd);
}
#else
#define dup_mmap(mm, oldmm) (0)
#define mm_alloc_pgd(mm) (0)
#define mm_free_pgd(mm)
#endif /* CONFIG_MMU */
__cacheline_aligned_in_smp DEFINE_SPINLOCK(mmlist_lock);
#define allocate_mm() (kmem_cache_alloc(mm_cachep, GFP_KERNEL))
#define free_mm(mm) (kmem_cache_free(mm_cachep, (mm)))
static unsigned long default_dump_filter = MMF_DUMP_FILTER_DEFAULT;
static int __init coredump_filter_setup(char *s)
{
default_dump_filter =
(simple_strtoul(s, NULL, 0) << MMF_DUMP_FILTER_SHIFT) &
MMF_DUMP_FILTER_MASK;
return 1;
}
__setup("coredump_filter=", coredump_filter_setup);
#include <linux/init_task.h>
static void mm_init_aio(struct mm_struct *mm)
{
#ifdef CONFIG_AIO
spin_lock_init(&mm->ioctx_lock);
INIT_HLIST_HEAD(&mm->ioctx_list);
#endif
}
static struct mm_struct * mm_init(struct mm_struct * mm, struct task_struct *p)
{
atomic_set(&mm->mm_users, 1);
atomic_set(&mm->mm_count, 1);
init_rwsem(&mm->mmap_sem);
INIT_LIST_HEAD(&mm->mmlist);
mm->flags = (current->mm) ?
(current->mm->flags & MMF_INIT_MASK) : default_dump_filter;
mm->core_state = NULL;
mm->nr_ptes = 0;
memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
spin_lock_init(&mm->page_table_lock);
mm->free_area_cache = TASK_UNMAPPED_BASE;
mm->cached_hole_size = ~0UL;
mm_init_aio(mm);
mm_init_owner(mm, p);
if (likely(!mm_alloc_pgd(mm))) {
mm->def_flags = 0;
mmu_notifier_mm_init(mm);
return mm;
}
free_mm(mm);
return NULL;
}
/*
* Allocate and initialize an mm_struct.
*/
struct mm_struct * mm_alloc(void)
{
struct mm_struct * mm;
mm = allocate_mm();
if (mm) {
memset(mm, 0, sizeof(*mm));
mm = mm_init(mm, current);
}
return mm;
}
/*
* Called when the last reference to the mm
* is dropped: either by a lazy thread or by
* mmput. Free the page directory and the mm.
*/
void __mmdrop(struct mm_struct *mm)
{
BUG_ON(mm == &init_mm);
mm_free_pgd(mm);
destroy_context(mm);
mmu_notifier_mm_destroy(mm);
free_mm(mm);
}
EXPORT_SYMBOL_GPL(__mmdrop);
/*
* Decrement the use count and release all resources for an mm.
*/
void mmput(struct mm_struct *mm)
{
might_sleep();
if (atomic_dec_and_test(&mm->mm_users)) {
exit_aio(mm);
ksm_exit(mm);
exit_mmap(mm);
set_mm_exe_file(mm, NULL);
if (!list_empty(&mm->mmlist)) {
spin_lock(&mmlist_lock);
list_del(&mm->mmlist);
spin_unlock(&mmlist_lock);
}
put_swap_token(mm);
if (mm->binfmt)
module_put(mm->binfmt->module);
mmdrop(mm);
}
}
EXPORT_SYMBOL_GPL(mmput);
/**
* get_task_mm - acquire a reference to the task's mm
*
* Returns %NULL if the task has no mm. Checks PF_KTHREAD (meaning
* this kernel workthread has transiently adopted a user mm with use_mm,
* to do its AIO) is not set and if so returns a reference to it, after
* bumping up the use count. User must release the mm via mmput()
* after use. Typically used by /proc and ptrace.
*/
struct mm_struct *get_task_mm(struct task_struct *task)
{
struct mm_struct *mm;
task_lock(task);
mm = task->mm;
if (mm) {
if (task->flags & PF_KTHREAD)
mm = NULL;
else
atomic_inc(&mm->mm_users);
}
task_unlock(task);
return mm;
}
EXPORT_SYMBOL_GPL(get_task_mm);
/* Please note the differences between mmput and mm_release.
* mmput is called whenever we stop holding onto a mm_struct,
* error success whatever.
*
* mm_release is called after a mm_struct has been removed
* from the current process.
*
* This difference is important for error handling, when we
* only half set up a mm_struct for a new process and need to restore
* the old one. Because we mmput the new mm_struct before
* restoring the old one. . .
* Eric Biederman 10 January 1998
*/
void mm_release(struct task_struct *tsk, struct mm_struct *mm)
{
struct completion *vfork_done = tsk->vfork_done;
/* Get rid of any futexes when releasing the mm */
#ifdef CONFIG_FUTEX
if (unlikely(tsk->robust_list)) {
exit_robust_list(tsk);
tsk->robust_list = NULL;
}
#ifdef CONFIG_COMPAT
if (unlikely(tsk->compat_robust_list)) {
compat_exit_robust_list(tsk);
tsk->compat_robust_list = NULL;
}
#endif
if (unlikely(!list_empty(&tsk->pi_state_list)))
exit_pi_state_list(tsk);
#endif
/* Get rid of any cached register state */
deactivate_mm(tsk, mm);
/* notify parent sleeping on vfork() */
if (vfork_done) {
tsk->vfork_done = NULL;
complete(vfork_done);
}
/*
* If we're exiting normally, clear a user-space tid field if
* requested. We leave this alone when dying by signal, to leave
* the value intact in a core dump, and to save the unnecessary
* trouble otherwise. Userland only wants this done for a sys_exit.
*/
if (tsk->clear_child_tid) {
if (!(tsk->flags & PF_SIGNALED) &&
atomic_read(&mm->mm_users) > 1) {
/*
* We don't check the error code - if userspace has
* not set up a proper pointer then tough luck.
*/
put_user(0, tsk->clear_child_tid);
sys_futex(tsk->clear_child_tid, FUTEX_WAKE,
1, NULL, NULL, 0);
}
tsk->clear_child_tid = NULL;
}
}
/*
* Allocate a new mm structure and copy contents from the
* mm structure of the passed in task structure.
*/
struct mm_struct *dup_mm(struct task_struct *tsk)
{
struct mm_struct *mm, *oldmm = current->mm;
int err;
if (!oldmm)
return NULL;
mm = allocate_mm();
if (!mm)
goto fail_nomem;
memcpy(mm, oldmm, sizeof(*mm));
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
if (!mm_init(mm, tsk))
goto fail_nomem;
if (init_new_context(tsk, mm))
goto fail_nocontext;
dup_mm_exe_file(oldmm, mm);
err = dup_mmap(mm, oldmm);
if (err)
goto free_pt;
mm->hiwater_rss = get_mm_rss(mm);
mm->hiwater_vm = mm->total_vm;
if (mm->binfmt && !try_module_get(mm->binfmt->module))
goto free_pt;
return mm;
free_pt:
/* don't put binfmt in mmput, we haven't got module yet */
mm->binfmt = NULL;
mmput(mm);
fail_nomem:
return NULL;
fail_nocontext:
/*
* If init_new_context() failed, we cannot use mmput() to free the mm
* because it calls destroy_context()
*/
mm_free_pgd(mm);
free_mm(mm);
return NULL;
}
static int copy_mm(unsigned long clone_flags, struct task_struct * tsk)
{
struct mm_struct * mm, *oldmm;
int retval;
tsk->min_flt = tsk->maj_flt = 0;
tsk->nvcsw = tsk->nivcsw = 0;
#ifdef CONFIG_DETECT_HUNG_TASK
tsk->last_switch_count = tsk->nvcsw + tsk->nivcsw;
#endif
tsk->mm = NULL;
tsk->active_mm = NULL;
/*
* Are we cloning a kernel thread?
*
* We need to steal a active VM for that..
*/
oldmm = current->mm;
if (!oldmm)
return 0;
if (clone_flags & CLONE_VM) {
atomic_inc(&oldmm->mm_users);
mm = oldmm;
goto good_mm;
}
retval = -ENOMEM;
mm = dup_mm(tsk);
if (!mm)
goto fail_nomem;
good_mm:
/* Initializing for Swap token stuff */
mm->token_priority = 0;
mm->last_interval = 0;
tsk->mm = mm;
tsk->active_mm = mm;
return 0;
fail_nomem:
return retval;
}
static int copy_fs(unsigned long clone_flags, struct task_struct *tsk)
{
struct fs_struct *fs = current->fs;
if (clone_flags & CLONE_FS) {
/* tsk->fs is already what we want */
write_lock(&fs->lock);
if (fs->in_exec) {
write_unlock(&fs->lock);
return -EAGAIN;
}
fs->users++;
write_unlock(&fs->lock);
return 0;
}
tsk->fs = copy_fs_struct(fs);
if (!tsk->fs)
return -ENOMEM;
return 0;
}
static int copy_files(unsigned long clone_flags, struct task_struct * tsk)
{
struct files_struct *oldf, *newf;
int error = 0;
/*
* A background process may not have any files ...
*/
oldf = current->files;
if (!oldf)
goto out;
if (clone_flags & CLONE_FILES) {
atomic_inc(&oldf->count);
goto out;
}
newf = dup_fd(oldf, &error);
if (!newf)
goto out;
tsk->files = newf;
error = 0;
out:
return error;
}
static int copy_io(unsigned long clone_flags, struct task_struct *tsk)
{
#ifdef CONFIG_BLOCK
struct io_context *ioc = current->io_context;
if (!ioc)
return 0;
/*
* Share io context with parent, if CLONE_IO is set
*/
if (clone_flags & CLONE_IO) {
tsk->io_context = ioc_task_link(ioc);
if (unlikely(!tsk->io_context))
return -ENOMEM;
} else if (ioprio_valid(ioc->ioprio)) {
tsk->io_context = alloc_io_context(GFP_KERNEL, -1);
if (unlikely(!tsk->io_context))
return -ENOMEM;
tsk->io_context->ioprio = ioc->ioprio;
}
#endif
return 0;
}
static int copy_sighand(unsigned long clone_flags, struct task_struct *tsk)
{
struct sighand_struct *sig;
if (clone_flags & CLONE_SIGHAND) {
atomic_inc(¤t->sighand->count);
return 0;
}
sig = kmem_cache_alloc(sighand_cachep, GFP_KERNEL);
rcu_assign_pointer(tsk->sighand, sig);
if (!sig)
return -ENOMEM;
atomic_set(&sig->count, 1);
memcpy(sig->action, current->sighand->action, sizeof(sig->action));
return 0;
}
void __cleanup_sighand(struct sighand_struct *sighand)
{
if (atomic_dec_and_test(&sighand->count))
kmem_cache_free(sighand_cachep, sighand);
}
/*
* Initialize POSIX timer handling for a thread group.
*/
static void posix_cpu_timers_init_group(struct signal_struct *sig)
{
unsigned long cpu_limit;
/* Thread group counters. */
thread_group_cputime_init(sig);
cpu_limit = ACCESS_ONCE(sig->rlim[RLIMIT_CPU].rlim_cur);
if (cpu_limit != RLIM_INFINITY) {
sig->cputime_expires.prof_exp = secs_to_cputime(cpu_limit);
sig->cputimer.running = 1;
}
/* The timer lists. */
INIT_LIST_HEAD(&sig->cpu_timers[0]);
INIT_LIST_HEAD(&sig->cpu_timers[1]);
INIT_LIST_HEAD(&sig->cpu_timers[2]);
}
static int copy_signal(unsigned long clone_flags, struct task_struct *tsk)
{
struct signal_struct *sig;
if (clone_flags & CLONE_THREAD)
return 0;
sig = kmem_cache_zalloc(signal_cachep, GFP_KERNEL);
tsk->signal = sig;
if (!sig)
return -ENOMEM;
sig->nr_threads = 1;
atomic_set(&sig->live, 1);
atomic_set(&sig->sigcnt, 1);
init_waitqueue_head(&sig->wait_chldexit);
if (clone_flags & CLONE_NEWPID)
sig->flags |= SIGNAL_UNKILLABLE;
sig->curr_target = tsk;
init_sigpending(&sig->shared_pending);
INIT_LIST_HEAD(&sig->posix_timers);
hrtimer_init(&sig->real_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
sig->real_timer.function = it_real_fn;
task_lock(current->group_leader);
memcpy(sig->rlim, current->signal->rlim, sizeof sig->rlim);
task_unlock(current->group_leader);
posix_cpu_timers_init_group(sig);
tty_audit_fork(sig);
sig->oom_adj = current->signal->oom_adj;
return 0;
}
static void copy_flags(unsigned long clone_flags, struct task_struct *p)
{
unsigned long new_flags = p->flags;
new_flags &= ~PF_SUPERPRIV;
new_flags |= PF_FORKNOEXEC;
new_flags |= PF_STARTING;
p->flags = new_flags;
clear_freeze_flag(p);
}
SYSCALL_DEFINE1(set_tid_address, int __user *, tidptr)
{
current->clear_child_tid = tidptr;
return task_pid_vnr(current);
}
static void rt_mutex_init_task(struct task_struct *p)
{
raw_spin_lock_init(&p->pi_lock);
#ifdef CONFIG_RT_MUTEXES
plist_head_init_raw(&p->pi_waiters, &p->pi_lock);
p->pi_blocked_on = NULL;
#endif
}
#ifdef CONFIG_MM_OWNER
void mm_init_owner(struct mm_struct *mm, struct task_struct *p)
{
mm->owner = p;
}
#endif /* CONFIG_MM_OWNER */
/*
* Initialize POSIX timer handling for a single task.
*/
static void posix_cpu_timers_init(struct task_struct *tsk)
{
tsk->cputime_expires.prof_exp = cputime_zero;
tsk->cputime_expires.virt_exp = cputime_zero;
tsk->cputime_expires.sched_exp = 0;
INIT_LIST_HEAD(&tsk->cpu_timers[0]);
INIT_LIST_HEAD(&tsk->cpu_timers[1]);
INIT_LIST_HEAD(&tsk->cpu_timers[2]);
}
/*
* This creates a new process as a copy of the old one,
* but does not actually start it yet.
*
* It copies the registers, and all the appropriate
* parts of the process environment (as per the clone
* flags). The actual kick-off is left to the caller.
*/
static struct task_struct *copy_process(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *child_tidptr,
struct pid *pid,
int trace)
{
int retval;
struct task_struct *p;
int cgroup_callbacks_done = 0;
if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS))
return ERR_PTR(-EINVAL);
/*
* Thread groups must share signals as well, and detached threads
* can only be started up within the thread group.
*/
if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND))
return ERR_PTR(-EINVAL);
/*
* Shared signal handlers imply shared VM. By way of the above,
* thread groups also imply shared VM. Blocking this case allows
* for various simplifications in other code.
*/
if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM))
return ERR_PTR(-EINVAL);
/*
* Siblings of global init remain as zombies on exit since they are
* not reaped by their parent (swapper). To solve this and to avoid
* multi-rooted process trees, prevent global and container-inits
* from creating siblings.
*/
if ((clone_flags & CLONE_PARENT) &&
current->signal->flags & SIGNAL_UNKILLABLE)
return ERR_PTR(-EINVAL);
retval = security_task_create(clone_flags);
if (retval)
goto fork_out;
retval = -ENOMEM;
p = dup_task_struct(current);
if (!p)
goto fork_out;
ftrace_graph_init_task(p);
rt_mutex_init_task(p);
#ifdef CONFIG_PROVE_LOCKING
DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled);
DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled);
#endif
retval = -EAGAIN;
if (atomic_read(&p->real_cred->user->processes) >=
task_rlimit(p, RLIMIT_NPROC)) {
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) &&
p->real_cred->user != INIT_USER)
goto bad_fork_free;
}
retval = copy_creds(p, clone_flags);
if (retval < 0)
goto bad_fork_free;
/*
* If multiple threads are within copy_process(), then this check
* triggers too late. This doesn't hurt, the check is only there
* to stop root fork bombs.
*/
retval = -EAGAIN;
if (nr_threads >= max_threads)
goto bad_fork_cleanup_count;
if (!try_module_get(task_thread_info(p)->exec_domain->module))
goto bad_fork_cleanup_count;
p->did_exec = 0;
delayacct_tsk_init(p); /* Must remain after dup_task_struct() */
copy_flags(clone_flags, p);
INIT_LIST_HEAD(&p->children);
INIT_LIST_HEAD(&p->sibling);
rcu_copy_process(p);
p->vfork_done = NULL;
spin_lock_init(&p->alloc_lock);
init_sigpending(&p->pending);
p->utime = cputime_zero;
p->stime = cputime_zero;
p->gtime = cputime_zero;
p->utimescaled = cputime_zero;
p->stimescaled = cputime_zero;
#ifndef CONFIG_VIRT_CPU_ACCOUNTING
p->prev_utime = cputime_zero;
p->prev_stime = cputime_zero;
#endif
#if defined(SPLIT_RSS_COUNTING)
memset(&p->rss_stat, 0, sizeof(p->rss_stat));
#endif
p->default_timer_slack_ns = current->timer_slack_ns;
task_io_accounting_init(&p->ioac);
acct_clear_integrals(p);
posix_cpu_timers_init(p);
p->lock_depth = -1; /* -1 = no lock */
do_posix_clock_monotonic_gettime(&p->start_time);
p->real_start_time = p->start_time;
monotonic_to_bootbased(&p->real_start_time);
p->io_context = NULL;
p->audit_context = NULL;
cgroup_fork(p);
#ifdef CONFIG_NUMA
p->mempolicy = mpol_dup(p->mempolicy);
if (IS_ERR(p->mempolicy)) {
retval = PTR_ERR(p->mempolicy);
p->mempolicy = NULL;
goto bad_fork_cleanup_cgroup;
}
mpol_fix_fork_child_flag(p);
#endif
#ifdef CONFIG_CPUSETS
p->cpuset_mem_spread_rotor = node_random(p->mems_allowed);
p->cpuset_slab_spread_rotor = node_random(p->mems_allowed);
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
p->irq_events = 0;
#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
p->hardirqs_enabled = 1;
#else
p->hardirqs_enabled = 0;
#endif
p->hardirq_enable_ip = 0;
p->hardirq_enable_event = 0;
p->hardirq_disable_ip = _THIS_IP_;
p->hardirq_disable_event = 0;
p->softirqs_enabled = 1;
p->softirq_enable_ip = _THIS_IP_;
p->softirq_enable_event = 0;
p->softirq_disable_ip = 0;
p->softirq_disable_event = 0;
p->hardirq_context = 0;
p->softirq_context = 0;
#endif
#ifdef CONFIG_LOCKDEP
p->lockdep_depth = 0; /* no locks held yet */
p->curr_chain_key = 0;
p->lockdep_recursion = 0;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
p->blocked_on = NULL; /* not blocked yet */
#endif
#ifdef CONFIG_CGROUP_MEM_RES_CTLR
p->memcg_batch.do_batch = 0;
p->memcg_batch.memcg = NULL;
#endif
/* Perform scheduler related setup. Assign this task to a CPU. */
sched_fork(p, clone_flags);
retval = perf_event_init_task(p);
if (retval)
goto bad_fork_cleanup_policy;
if ((retval = audit_alloc(p)))
goto bad_fork_cleanup_policy;
/* copy all the process information */
if ((retval = copy_semundo(clone_flags, p)))
goto bad_fork_cleanup_audit;
if ((retval = copy_files(clone_flags, p)))
goto bad_fork_cleanup_semundo;
if ((retval = copy_fs(clone_flags, p)))
goto bad_fork_cleanup_files;
if ((retval = copy_sighand(clone_flags, p)))
goto bad_fork_cleanup_fs;
if ((retval = copy_signal(clone_flags, p)))
goto bad_fork_cleanup_sighand;
if ((retval = copy_mm(clone_flags, p)))
goto bad_fork_cleanup_signal;
if ((retval = copy_namespaces(clone_flags, p)))
goto bad_fork_cleanup_mm;
if ((retval = copy_io(clone_flags, p)))
goto bad_fork_cleanup_namespaces;
retval = copy_thread(clone_flags, stack_start, stack_size, p, regs);
if (retval)
goto bad_fork_cleanup_io;
if (pid != &init_struct_pid) {
retval = -ENOMEM;
pid = alloc_pid(p->nsproxy->pid_ns);
if (!pid)
goto bad_fork_cleanup_io;
if (clone_flags & CLONE_NEWPID) {
retval = pid_ns_prepare_proc(p->nsproxy->pid_ns);
if (retval < 0)
goto bad_fork_free_pid;
}
}
p->pid = pid_nr(pid);
p->tgid = p->pid;
if (clone_flags & CLONE_THREAD)
p->tgid = current->tgid;
if (current->nsproxy != p->nsproxy) {
retval = ns_cgroup_clone(p, pid);
if (retval)
goto bad_fork_free_pid;
}
p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL;
/*
* Clear TID on mm_release()?
*/
p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr: NULL;
#ifdef CONFIG_FUTEX
p->robust_list = NULL;
#ifdef CONFIG_COMPAT
p->compat_robust_list = NULL;
#endif
INIT_LIST_HEAD(&p->pi_state_list);
p->pi_state_cache = NULL;
#endif
/*
* sigaltstack should be cleared when sharing the same VM
*/
if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM)
p->sas_ss_sp = p->sas_ss_size = 0;
/*
* Syscall tracing and stepping should be turned off in the
* child regardless of CLONE_PTRACE.
*/
user_disable_single_step(p);
clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE);
#ifdef TIF_SYSCALL_EMU
clear_tsk_thread_flag(p, TIF_SYSCALL_EMU);
#endif
clear_all_latency_tracing(p);
/* ok, now we should be set up.. */
p->exit_signal = (clone_flags & CLONE_THREAD) ? -1 : (clone_flags & CSIGNAL);
p->pdeath_signal = 0;
p->exit_state = 0;
/*
* Ok, make it visible to the rest of the system.
* We dont wake it up yet.
*/
p->group_leader = p;
INIT_LIST_HEAD(&p->thread_group);
/* Now that the task is set up, run cgroup callbacks if
* necessary. We need to run them before the task is visible
* on the tasklist. */
cgroup_fork_callbacks(p);
cgroup_callbacks_done = 1;
/* Need tasklist lock for parent etc handling! */
write_lock_irq(&tasklist_lock);
/* CLONE_PARENT re-uses the old parent */
if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) {
p->real_parent = current->real_parent;
p->parent_exec_id = current->parent_exec_id;
} else {
p->real_parent = current;
p->parent_exec_id = current->self_exec_id;
}
spin_lock(¤t->sighand->siglock);
/*
* Process group and session signals need to be delivered to just the
* parent before the fork or both the parent and the child after the
* fork. Restart if a signal comes in before we add the new process to
* it's process group.
* A fatal signal pending means that current will exit, so the new
* thread can't slip out of an OOM kill (or normal SIGKILL).
*/
recalc_sigpending();
if (signal_pending(current)) {
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
retval = -ERESTARTNOINTR;
goto bad_fork_free_pid;
}
if (clone_flags & CLONE_THREAD) {
current->signal->nr_threads++;
atomic_inc(¤t->signal->live);
atomic_inc(¤t->signal->sigcnt);
p->group_leader = current->group_leader;
list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group);
}
if (likely(p->pid)) {
tracehook_finish_clone(p, clone_flags, trace);
if (thread_group_leader(p)) {
if (clone_flags & CLONE_NEWPID)
p->nsproxy->pid_ns->child_reaper = p;
p->signal->leader_pid = pid;
p->signal->tty = tty_kref_get(current->signal->tty);
attach_pid(p, PIDTYPE_PGID, task_pgrp(current));
attach_pid(p, PIDTYPE_SID, task_session(current));
list_add_tail(&p->sibling, &p->real_parent->children);
list_add_tail_rcu(&p->tasks, &init_task.tasks);
__get_cpu_var(process_counts)++;
}
attach_pid(p, PIDTYPE_PID, pid);
nr_threads++;
}
total_forks++;
spin_unlock(¤t->sighand->siglock);
write_unlock_irq(&tasklist_lock);
proc_fork_connector(p);
cgroup_post_fork(p);
perf_event_fork(p);
return p;
bad_fork_free_pid:
if (pid != &init_struct_pid)
free_pid(pid);
bad_fork_cleanup_io:
if (p->io_context)
exit_io_context(p);
bad_fork_cleanup_namespaces:
exit_task_namespaces(p);
bad_fork_cleanup_mm:
if (p->mm)
mmput(p->mm);
bad_fork_cleanup_signal:
if (!(clone_flags & CLONE_THREAD))
free_signal_struct(p->signal);
bad_fork_cleanup_sighand:
__cleanup_sighand(p->sighand);
bad_fork_cleanup_fs:
exit_fs(p); /* blocking */
bad_fork_cleanup_files:
exit_files(p); /* blocking */
bad_fork_cleanup_semundo:
exit_sem(p);
bad_fork_cleanup_audit:
audit_free(p);
bad_fork_cleanup_policy:
perf_event_free_task(p);
#ifdef CONFIG_NUMA
mpol_put(p->mempolicy);
bad_fork_cleanup_cgroup:
#endif
cgroup_exit(p, cgroup_callbacks_done);
delayacct_tsk_free(p);
module_put(task_thread_info(p)->exec_domain->module);
bad_fork_cleanup_count:
atomic_dec(&p->cred->user->processes);
exit_creds(p);
bad_fork_free:
free_task(p);
fork_out:
return ERR_PTR(retval);
}
noinline struct pt_regs * __cpuinit __attribute__((weak)) idle_regs(struct pt_regs *regs)
{
memset(regs, 0, sizeof(struct pt_regs));
return regs;
}
struct task_struct * __cpuinit fork_idle(int cpu)
{
struct task_struct *task;
struct pt_regs regs;
task = copy_process(CLONE_VM, 0, idle_regs(®s), 0, NULL,
&init_struct_pid, 0);
if (!IS_ERR(task))
init_idle(task, cpu);
return task;
}
/*
* Ok, this is the main fork-routine.
*
* It copies the process, and if successful kick-starts
* it and waits for it to finish using the VM if required.
*/
long do_fork(unsigned long clone_flags,
unsigned long stack_start,
struct pt_regs *regs,
unsigned long stack_size,
int __user *parent_tidptr,
int __user *child_tidptr)
{
struct task_struct *p;
int trace = 0;
long nr;
/*
* Do some preliminary argument and permissions checking before we
* actually start allocating stuff
*/
if (clone_flags & CLONE_NEWUSER) {
if (clone_flags & CLONE_THREAD)
return -EINVAL;
/* hopefully this check will go away when userns support is
* complete
*/
if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SETUID) ||
!capable(CAP_SETGID))
return -EPERM;
}
/*
* We hope to recycle these flags after 2.6.26
*/
if (unlikely(clone_flags & CLONE_STOPPED)) {
static int __read_mostly count = 100;
if (count > 0 && printk_ratelimit()) {
char comm[TASK_COMM_LEN];
count--;
printk(KERN_INFO "fork(): process `%s' used deprecated "
"clone flags 0x%lx\n",
get_task_comm(comm, current),
clone_flags & CLONE_STOPPED);
}
}
/*
* When called from kernel_thread, don't do user tracing stuff.
*/
if (likely(user_mode(regs)))
trace = tracehook_prepare_clone(clone_flags);
p = copy_process(clone_flags, stack_start, regs, stack_size,
child_tidptr, NULL, trace);
/*
* Do this prior waking up the new thread - the thread pointer
* might get invalid after that point, if the thread exits quickly.
*/
if (!IS_ERR(p)) {
struct completion vfork;
trace_sched_process_fork(current, p);
nr = task_pid_vnr(p);
if (clone_flags & CLONE_PARENT_SETTID)
put_user(nr, parent_tidptr);
if (clone_flags & CLONE_VFORK) {
p->vfork_done = &vfork;
init_completion(&vfork);
}
audit_finish_fork(p);
tracehook_report_clone(regs, clone_flags, nr, p);
/*
* We set PF_STARTING at creation in case tracing wants to
* use this to distinguish a fully live task from one that
* hasn't gotten to tracehook_report_clone() yet. Now we
* clear it and set the child going.
*/
p->flags &= ~PF_STARTING;
if (unlikely(clone_flags & CLONE_STOPPED)) {
/*
* We'll start up with an immediate SIGSTOP.
*/
sigaddset(&p->pending.signal, SIGSTOP);
set_tsk_thread_flag(p, TIF_SIGPENDING);
__set_task_state(p, TASK_STOPPED);
} else {
wake_up_new_task(p, clone_flags);
}
tracehook_report_clone_complete(trace, regs,
clone_flags, nr, p);
if (clone_flags & CLONE_VFORK) {
freezer_do_not_count();
wait_for_completion(&vfork);
freezer_count();
tracehook_report_vfork_done(p, nr);
}
} else {
nr = PTR_ERR(p);
}
return nr;
}
#ifndef ARCH_MIN_MMSTRUCT_ALIGN
#define ARCH_MIN_MMSTRUCT_ALIGN 0
#endif
static void sighand_ctor(void *data)
{
struct sighand_struct *sighand = data;
spin_lock_init(&sighand->siglock);
init_waitqueue_head(&sighand->signalfd_wqh);
}
void __init proc_caches_init(void)
{
sighand_cachep = kmem_cache_create("sighand_cache",
sizeof(struct sighand_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_DESTROY_BY_RCU|
SLAB_NOTRACK, sighand_ctor);
signal_cachep = kmem_cache_create("signal_cache",
sizeof(struct signal_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
files_cachep = kmem_cache_create("files_cache",
sizeof(struct files_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
fs_cachep = kmem_cache_create("fs_cache",
sizeof(struct fs_struct), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
mm_cachep = kmem_cache_create("mm_struct",
sizeof(struct mm_struct), ARCH_MIN_MMSTRUCT_ALIGN,
SLAB_HWCACHE_ALIGN|SLAB_PANIC|SLAB_NOTRACK, NULL);
vm_area_cachep = KMEM_CACHE(vm_area_struct, SLAB_PANIC);
mmap_init();
}
/*
* Check constraints on flags passed to the unshare system call and
* force unsharing of additional process context as appropriate.
*/
static void check_unshare_flags(unsigned long *flags_ptr)
{
/*
* If unsharing a thread from a thread group, must also
* unshare vm.
*/
if (*flags_ptr & CLONE_THREAD)
*flags_ptr |= CLONE_VM;
/*
* If unsharing vm, must also unshare signal handlers.
*/
if (*flags_ptr & CLONE_VM)
*flags_ptr |= CLONE_SIGHAND;
/*
* If unsharing namespace, must also unshare filesystem information.
*/
if (*flags_ptr & CLONE_NEWNS)
*flags_ptr |= CLONE_FS;
}
/*
* Unsharing of tasks created with CLONE_THREAD is not supported yet
*/
static int unshare_thread(unsigned long unshare_flags)
{
if (unshare_flags & CLONE_THREAD)
return -EINVAL;
return 0;
}
/*
* Unshare the filesystem structure if it is being shared
*/
static int unshare_fs(unsigned long unshare_flags, struct fs_struct **new_fsp)
{
struct fs_struct *fs = current->fs;
if (!(unshare_flags & CLONE_FS) || !fs)
return 0;
/* don't need lock here; in the worst case we'll do useless copy */
if (fs->users == 1)
return 0;
*new_fsp = copy_fs_struct(fs);
if (!*new_fsp)
return -ENOMEM;
return 0;
}
/*
* Unsharing of sighand is not supported yet
*/
static int unshare_sighand(unsigned long unshare_flags, struct sighand_struct **new_sighp)
{
struct sighand_struct *sigh = current->sighand;
if ((unshare_flags & CLONE_SIGHAND) && atomic_read(&sigh->count) > 1)
return -EINVAL;
else
return 0;
}
/*
* Unshare vm if it is being shared
*/
static int unshare_vm(unsigned long unshare_flags, struct mm_struct **new_mmp)
{
struct mm_struct *mm = current->mm;
if ((unshare_flags & CLONE_VM) &&
(mm && atomic_read(&mm->mm_users) > 1)) {
return -EINVAL;
}
return 0;
}
/*
* Unshare file descriptor table if it is being shared
*/
static int unshare_fd(unsigned long unshare_flags, struct files_struct **new_fdp)
{
struct files_struct *fd = current->files;
int error = 0;
if ((unshare_flags & CLONE_FILES) &&
(fd && atomic_read(&fd->count) > 1)) {
*new_fdp = dup_fd(fd, &error);
if (!*new_fdp)
return error;
}
return 0;
}
/*
* unshare allows a process to 'unshare' part of the process
* context which was originally shared using clone. copy_*
* functions used by do_fork() cannot be used here directly
* because they modify an inactive task_struct that is being
* constructed. Here we are modifying the current, active,
* task_struct.
*/
SYSCALL_DEFINE1(unshare, unsigned long, unshare_flags)
{
int err = 0;
struct fs_struct *fs, *new_fs = NULL;
struct sighand_struct *new_sigh = NULL;
struct mm_struct *mm, *new_mm = NULL, *active_mm = NULL;
struct files_struct *fd, *new_fd = NULL;
struct nsproxy *new_nsproxy = NULL;
int do_sysvsem = 0;
check_unshare_flags(&unshare_flags);
/* Return -EINVAL for all unsupported flags */
err = -EINVAL;
if (unshare_flags & ~(CLONE_THREAD|CLONE_FS|CLONE_NEWNS|CLONE_SIGHAND|
CLONE_VM|CLONE_FILES|CLONE_SYSVSEM|
CLONE_NEWUTS|CLONE_NEWIPC|CLONE_NEWNET))
goto bad_unshare_out;
/*
* CLONE_NEWIPC must also detach from the undolist: after switching
* to a new ipc namespace, the semaphore arrays from the old
* namespace are unreachable.
*/
if (unshare_flags & (CLONE_NEWIPC|CLONE_SYSVSEM))
do_sysvsem = 1;
if ((err = unshare_thread(unshare_flags)))
goto bad_unshare_out;
if ((err = unshare_fs(unshare_flags, &new_fs)))
goto bad_unshare_cleanup_thread;
if ((err = unshare_sighand(unshare_flags, &new_sigh)))
goto bad_unshare_cleanup_fs;
if ((err = unshare_vm(unshare_flags, &new_mm)))
goto bad_unshare_cleanup_sigh;
if ((err = unshare_fd(unshare_flags, &new_fd)))
goto bad_unshare_cleanup_vm;
if ((err = unshare_nsproxy_namespaces(unshare_flags, &new_nsproxy,
new_fs)))
goto bad_unshare_cleanup_fd;
if (new_fs || new_mm || new_fd || do_sysvsem || new_nsproxy) {
if (do_sysvsem) {
/*
* CLONE_SYSVSEM is equivalent to sys_exit().
*/
exit_sem(current);
}
if (new_nsproxy) {
switch_task_namespaces(current, new_nsproxy);
new_nsproxy = NULL;
}
task_lock(current);
if (new_fs) {
fs = current->fs;
write_lock(&fs->lock);
current->fs = new_fs;
if (--fs->users)
new_fs = NULL;
else
new_fs = fs;
write_unlock(&fs->lock);
}
if (new_mm) {
mm = current->mm;
active_mm = current->active_mm;
current->mm = new_mm;
current->active_mm = new_mm;
activate_mm(active_mm, new_mm);
new_mm = mm;
}
if (new_fd) {
fd = current->files;
current->files = new_fd;
new_fd = fd;
}
task_unlock(current);
}
if (new_nsproxy)
put_nsproxy(new_nsproxy);
bad_unshare_cleanup_fd:
if (new_fd)
put_files_struct(new_fd);
bad_unshare_cleanup_vm:
if (new_mm)
mmput(new_mm);
bad_unshare_cleanup_sigh:
if (new_sigh)
if (atomic_dec_and_test(&new_sigh->count))
kmem_cache_free(sighand_cachep, new_sigh);
bad_unshare_cleanup_fs:
if (new_fs)
free_fs_struct(new_fs);
bad_unshare_cleanup_thread:
bad_unshare_out:
return err;
}
/*
* Helper to unshare the files of the current task.
* We don't want to expose copy_files internals to
* the exec layer of the kernel.
*/
int unshare_files(struct files_struct **displaced)
{
struct task_struct *task = current;
struct files_struct *copy = NULL;
int error;
error = unshare_fd(CLONE_FILES, ©);
if (error || !copy) {
*displaced = NULL;
return error;
}
*displaced = task->files;
task_lock(task);
task->files = copy;
task_unlock(task);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4728_0 |
crossvul-cpp_data_good_3547_1 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Copyright (C) Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk)
* Copyright (C) Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk)
* Copyright (C) Terry Dawson VK2KTJ (terry@animats.net)
* Copyright (C) Tomi Manninen OH2BNS (oh2bns@sral.fi)
*/
#include <linux/capability.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/spinlock.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/stat.h>
#include <net/net_namespace.h>
#include <net/ax25.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <net/rose.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <net/tcp_states.h>
#include <net/ip.h>
#include <net/arp.h>
static int rose_ndevs = 10;
int sysctl_rose_restart_request_timeout = ROSE_DEFAULT_T0;
int sysctl_rose_call_request_timeout = ROSE_DEFAULT_T1;
int sysctl_rose_reset_request_timeout = ROSE_DEFAULT_T2;
int sysctl_rose_clear_request_timeout = ROSE_DEFAULT_T3;
int sysctl_rose_no_activity_timeout = ROSE_DEFAULT_IDLE;
int sysctl_rose_ack_hold_back_timeout = ROSE_DEFAULT_HB;
int sysctl_rose_routing_control = ROSE_DEFAULT_ROUTING;
int sysctl_rose_link_fail_timeout = ROSE_DEFAULT_FAIL_TIMEOUT;
int sysctl_rose_maximum_vcs = ROSE_DEFAULT_MAXVC;
int sysctl_rose_window_size = ROSE_DEFAULT_WINDOW_SIZE;
static HLIST_HEAD(rose_list);
static DEFINE_SPINLOCK(rose_list_lock);
static const struct proto_ops rose_proto_ops;
ax25_address rose_callsign;
/*
* ROSE network devices are virtual network devices encapsulating ROSE
* frames into AX.25 which will be sent through an AX.25 device, so form a
* special "super class" of normal net devices; split their locks off into a
* separate class since they always nest.
*/
static struct lock_class_key rose_netdev_xmit_lock_key;
static struct lock_class_key rose_netdev_addr_lock_key;
static void rose_set_lockdep_one(struct net_device *dev,
struct netdev_queue *txq,
void *_unused)
{
lockdep_set_class(&txq->_xmit_lock, &rose_netdev_xmit_lock_key);
}
static void rose_set_lockdep_key(struct net_device *dev)
{
lockdep_set_class(&dev->addr_list_lock, &rose_netdev_addr_lock_key);
netdev_for_each_tx_queue(dev, rose_set_lockdep_one, NULL);
}
/*
* Convert a ROSE address into text.
*/
char *rose2asc(char *buf, const rose_address *addr)
{
if (addr->rose_addr[0] == 0x00 && addr->rose_addr[1] == 0x00 &&
addr->rose_addr[2] == 0x00 && addr->rose_addr[3] == 0x00 &&
addr->rose_addr[4] == 0x00) {
strcpy(buf, "*");
} else {
sprintf(buf, "%02X%02X%02X%02X%02X", addr->rose_addr[0] & 0xFF,
addr->rose_addr[1] & 0xFF,
addr->rose_addr[2] & 0xFF,
addr->rose_addr[3] & 0xFF,
addr->rose_addr[4] & 0xFF);
}
return buf;
}
/*
* Compare two ROSE addresses, 0 == equal.
*/
int rosecmp(rose_address *addr1, rose_address *addr2)
{
int i;
for (i = 0; i < 5; i++)
if (addr1->rose_addr[i] != addr2->rose_addr[i])
return 1;
return 0;
}
/*
* Compare two ROSE addresses for only mask digits, 0 == equal.
*/
int rosecmpm(rose_address *addr1, rose_address *addr2, unsigned short mask)
{
unsigned int i, j;
if (mask > 10)
return 1;
for (i = 0; i < mask; i++) {
j = i / 2;
if ((i % 2) != 0) {
if ((addr1->rose_addr[j] & 0x0F) != (addr2->rose_addr[j] & 0x0F))
return 1;
} else {
if ((addr1->rose_addr[j] & 0xF0) != (addr2->rose_addr[j] & 0xF0))
return 1;
}
}
return 0;
}
/*
* Socket removal during an interrupt is now safe.
*/
static void rose_remove_socket(struct sock *sk)
{
spin_lock_bh(&rose_list_lock);
sk_del_node_init(sk);
spin_unlock_bh(&rose_list_lock);
}
/*
* Kill all bound sockets on a broken link layer connection to a
* particular neighbour.
*/
void rose_kill_by_neigh(struct rose_neigh *neigh)
{
struct sock *s;
struct hlist_node *node;
spin_lock_bh(&rose_list_lock);
sk_for_each(s, node, &rose_list) {
struct rose_sock *rose = rose_sk(s);
if (rose->neighbour == neigh) {
rose_disconnect(s, ENETUNREACH, ROSE_OUT_OF_ORDER, 0);
rose->neighbour->use--;
rose->neighbour = NULL;
}
}
spin_unlock_bh(&rose_list_lock);
}
/*
* Kill all bound sockets on a dropped device.
*/
static void rose_kill_by_device(struct net_device *dev)
{
struct sock *s;
struct hlist_node *node;
spin_lock_bh(&rose_list_lock);
sk_for_each(s, node, &rose_list) {
struct rose_sock *rose = rose_sk(s);
if (rose->device == dev) {
rose_disconnect(s, ENETUNREACH, ROSE_OUT_OF_ORDER, 0);
rose->neighbour->use--;
rose->device = NULL;
}
}
spin_unlock_bh(&rose_list_lock);
}
/*
* Handle device status changes.
*/
static int rose_device_event(struct notifier_block *this, unsigned long event,
void *ptr)
{
struct net_device *dev = (struct net_device *)ptr;
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (event != NETDEV_DOWN)
return NOTIFY_DONE;
switch (dev->type) {
case ARPHRD_ROSE:
rose_kill_by_device(dev);
break;
case ARPHRD_AX25:
rose_link_device_down(dev);
rose_rt_device_down(dev);
break;
}
return NOTIFY_DONE;
}
/*
* Add a socket to the bound sockets list.
*/
static void rose_insert_socket(struct sock *sk)
{
spin_lock_bh(&rose_list_lock);
sk_add_node(sk, &rose_list);
spin_unlock_bh(&rose_list_lock);
}
/*
* Find a socket that wants to accept the Call Request we just
* received.
*/
static struct sock *rose_find_listener(rose_address *addr, ax25_address *call)
{
struct sock *s;
struct hlist_node *node;
spin_lock_bh(&rose_list_lock);
sk_for_each(s, node, &rose_list) {
struct rose_sock *rose = rose_sk(s);
if (!rosecmp(&rose->source_addr, addr) &&
!ax25cmp(&rose->source_call, call) &&
!rose->source_ndigis && s->sk_state == TCP_LISTEN)
goto found;
}
sk_for_each(s, node, &rose_list) {
struct rose_sock *rose = rose_sk(s);
if (!rosecmp(&rose->source_addr, addr) &&
!ax25cmp(&rose->source_call, &null_ax25_address) &&
s->sk_state == TCP_LISTEN)
goto found;
}
s = NULL;
found:
spin_unlock_bh(&rose_list_lock);
return s;
}
/*
* Find a connected ROSE socket given my LCI and device.
*/
struct sock *rose_find_socket(unsigned int lci, struct rose_neigh *neigh)
{
struct sock *s;
struct hlist_node *node;
spin_lock_bh(&rose_list_lock);
sk_for_each(s, node, &rose_list) {
struct rose_sock *rose = rose_sk(s);
if (rose->lci == lci && rose->neighbour == neigh)
goto found;
}
s = NULL;
found:
spin_unlock_bh(&rose_list_lock);
return s;
}
/*
* Find a unique LCI for a given device.
*/
unsigned int rose_new_lci(struct rose_neigh *neigh)
{
int lci;
if (neigh->dce_mode) {
for (lci = 1; lci <= sysctl_rose_maximum_vcs; lci++)
if (rose_find_socket(lci, neigh) == NULL && rose_route_free_lci(lci, neigh) == NULL)
return lci;
} else {
for (lci = sysctl_rose_maximum_vcs; lci > 0; lci--)
if (rose_find_socket(lci, neigh) == NULL && rose_route_free_lci(lci, neigh) == NULL)
return lci;
}
return 0;
}
/*
* Deferred destroy.
*/
void rose_destroy_socket(struct sock *);
/*
* Handler for deferred kills.
*/
static void rose_destroy_timer(unsigned long data)
{
rose_destroy_socket((struct sock *)data);
}
/*
* This is called from user mode and the timers. Thus it protects itself
* against interrupt users but doesn't worry about being called during
* work. Once it is removed from the queue no interrupt or bottom half
* will touch it and we are (fairly 8-) ) safe.
*/
void rose_destroy_socket(struct sock *sk)
{
struct sk_buff *skb;
rose_remove_socket(sk);
rose_stop_heartbeat(sk);
rose_stop_idletimer(sk);
rose_stop_timer(sk);
rose_clear_queues(sk); /* Flush the queues */
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
if (skb->sk != sk) { /* A pending connection */
/* Queue the unaccepted socket for death */
sock_set_flag(skb->sk, SOCK_DEAD);
rose_start_heartbeat(skb->sk);
rose_sk(skb->sk)->state = ROSE_STATE_0;
}
kfree_skb(skb);
}
if (sk_has_allocations(sk)) {
/* Defer: outstanding buffers */
setup_timer(&sk->sk_timer, rose_destroy_timer,
(unsigned long)sk);
sk->sk_timer.expires = jiffies + 10 * HZ;
add_timer(&sk->sk_timer);
} else
sock_put(sk);
}
/*
* Handling for system calls applied via the various interfaces to a
* ROSE socket object.
*/
static int rose_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
int opt;
if (level != SOL_ROSE)
return -ENOPROTOOPT;
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(opt, (int __user *)optval))
return -EFAULT;
switch (optname) {
case ROSE_DEFER:
rose->defer = opt ? 1 : 0;
return 0;
case ROSE_T1:
if (opt < 1)
return -EINVAL;
rose->t1 = opt * HZ;
return 0;
case ROSE_T2:
if (opt < 1)
return -EINVAL;
rose->t2 = opt * HZ;
return 0;
case ROSE_T3:
if (opt < 1)
return -EINVAL;
rose->t3 = opt * HZ;
return 0;
case ROSE_HOLDBACK:
if (opt < 1)
return -EINVAL;
rose->hb = opt * HZ;
return 0;
case ROSE_IDLE:
if (opt < 0)
return -EINVAL;
rose->idle = opt * 60 * HZ;
return 0;
case ROSE_QBITINCL:
rose->qbitincl = opt ? 1 : 0;
return 0;
default:
return -ENOPROTOOPT;
}
}
static int rose_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
int val = 0;
int len;
if (level != SOL_ROSE)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case ROSE_DEFER:
val = rose->defer;
break;
case ROSE_T1:
val = rose->t1 / HZ;
break;
case ROSE_T2:
val = rose->t2 / HZ;
break;
case ROSE_T3:
val = rose->t3 / HZ;
break;
case ROSE_HOLDBACK:
val = rose->hb / HZ;
break;
case ROSE_IDLE:
val = rose->idle / (60 * HZ);
break;
case ROSE_QBITINCL:
val = rose->qbitincl;
break;
default:
return -ENOPROTOOPT;
}
len = min_t(unsigned int, len, sizeof(int));
if (put_user(len, optlen))
return -EFAULT;
return copy_to_user(optval, &val, len) ? -EFAULT : 0;
}
static int rose_listen(struct socket *sock, int backlog)
{
struct sock *sk = sock->sk;
if (sk->sk_state != TCP_LISTEN) {
struct rose_sock *rose = rose_sk(sk);
rose->dest_ndigis = 0;
memset(&rose->dest_addr, 0, ROSE_ADDR_LEN);
memset(&rose->dest_call, 0, AX25_ADDR_LEN);
memset(rose->dest_digis, 0, AX25_ADDR_LEN * ROSE_MAX_DIGIS);
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
return 0;
}
return -EOPNOTSUPP;
}
static struct proto rose_proto = {
.name = "ROSE",
.owner = THIS_MODULE,
.obj_size = sizeof(struct rose_sock),
};
static int rose_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct rose_sock *rose;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
if (sock->type != SOCK_SEQPACKET || protocol != 0)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_ROSE, GFP_ATOMIC, &rose_proto);
if (sk == NULL)
return -ENOMEM;
rose = rose_sk(sk);
sock_init_data(sock, sk);
skb_queue_head_init(&rose->ack_queue);
#ifdef M_BIT
skb_queue_head_init(&rose->frag_queue);
rose->fraglen = 0;
#endif
sock->ops = &rose_proto_ops;
sk->sk_protocol = protocol;
init_timer(&rose->timer);
init_timer(&rose->idletimer);
rose->t1 = msecs_to_jiffies(sysctl_rose_call_request_timeout);
rose->t2 = msecs_to_jiffies(sysctl_rose_reset_request_timeout);
rose->t3 = msecs_to_jiffies(sysctl_rose_clear_request_timeout);
rose->hb = msecs_to_jiffies(sysctl_rose_ack_hold_back_timeout);
rose->idle = msecs_to_jiffies(sysctl_rose_no_activity_timeout);
rose->state = ROSE_STATE_0;
return 0;
}
static struct sock *rose_make_new(struct sock *osk)
{
struct sock *sk;
struct rose_sock *rose, *orose;
if (osk->sk_type != SOCK_SEQPACKET)
return NULL;
sk = sk_alloc(sock_net(osk), PF_ROSE, GFP_ATOMIC, &rose_proto);
if (sk == NULL)
return NULL;
rose = rose_sk(sk);
sock_init_data(NULL, sk);
skb_queue_head_init(&rose->ack_queue);
#ifdef M_BIT
skb_queue_head_init(&rose->frag_queue);
rose->fraglen = 0;
#endif
sk->sk_type = osk->sk_type;
sk->sk_priority = osk->sk_priority;
sk->sk_protocol = osk->sk_protocol;
sk->sk_rcvbuf = osk->sk_rcvbuf;
sk->sk_sndbuf = osk->sk_sndbuf;
sk->sk_state = TCP_ESTABLISHED;
sock_copy_flags(sk, osk);
init_timer(&rose->timer);
init_timer(&rose->idletimer);
orose = rose_sk(osk);
rose->t1 = orose->t1;
rose->t2 = orose->t2;
rose->t3 = orose->t3;
rose->hb = orose->hb;
rose->idle = orose->idle;
rose->defer = orose->defer;
rose->device = orose->device;
rose->qbitincl = orose->qbitincl;
return sk;
}
static int rose_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct rose_sock *rose;
if (sk == NULL) return 0;
sock_hold(sk);
sock_orphan(sk);
lock_sock(sk);
rose = rose_sk(sk);
switch (rose->state) {
case ROSE_STATE_0:
release_sock(sk);
rose_disconnect(sk, 0, -1, -1);
lock_sock(sk);
rose_destroy_socket(sk);
break;
case ROSE_STATE_2:
rose->neighbour->use--;
release_sock(sk);
rose_disconnect(sk, 0, -1, -1);
lock_sock(sk);
rose_destroy_socket(sk);
break;
case ROSE_STATE_1:
case ROSE_STATE_3:
case ROSE_STATE_4:
case ROSE_STATE_5:
rose_clear_queues(sk);
rose_stop_idletimer(sk);
rose_write_internal(sk, ROSE_CLEAR_REQUEST);
rose_start_t3timer(sk);
rose->state = ROSE_STATE_2;
sk->sk_state = TCP_CLOSE;
sk->sk_shutdown |= SEND_SHUTDOWN;
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DEAD);
sock_set_flag(sk, SOCK_DESTROY);
break;
default:
break;
}
sock->sk = NULL;
release_sock(sk);
sock_put(sk);
return 0;
}
static int rose_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
struct sockaddr_rose *addr = (struct sockaddr_rose *)uaddr;
struct net_device *dev;
ax25_address *source;
ax25_uid_assoc *user;
int n;
if (!sock_flag(sk, SOCK_ZAPPED))
return -EINVAL;
if (addr_len != sizeof(struct sockaddr_rose) && addr_len != sizeof(struct full_sockaddr_rose))
return -EINVAL;
if (addr->srose_family != AF_ROSE)
return -EINVAL;
if (addr_len == sizeof(struct sockaddr_rose) && addr->srose_ndigis > 1)
return -EINVAL;
if ((unsigned int) addr->srose_ndigis > ROSE_MAX_DIGIS)
return -EINVAL;
if ((dev = rose_dev_get(&addr->srose_addr)) == NULL) {
SOCK_DEBUG(sk, "ROSE: bind failed: invalid address\n");
return -EADDRNOTAVAIL;
}
source = &addr->srose_call;
user = ax25_findbyuid(current_euid());
if (user) {
rose->source_call = user->call;
ax25_uid_put(user);
} else {
if (ax25_uid_policy && !capable(CAP_NET_BIND_SERVICE))
return -EACCES;
rose->source_call = *source;
}
rose->source_addr = addr->srose_addr;
rose->device = dev;
rose->source_ndigis = addr->srose_ndigis;
if (addr_len == sizeof(struct full_sockaddr_rose)) {
struct full_sockaddr_rose *full_addr = (struct full_sockaddr_rose *)uaddr;
for (n = 0 ; n < addr->srose_ndigis ; n++)
rose->source_digis[n] = full_addr->srose_digis[n];
} else {
if (rose->source_ndigis == 1) {
rose->source_digis[0] = addr->srose_digi;
}
}
rose_insert_socket(sk);
sock_reset_flag(sk, SOCK_ZAPPED);
SOCK_DEBUG(sk, "ROSE: socket is bound\n");
return 0;
}
static int rose_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
struct sockaddr_rose *addr = (struct sockaddr_rose *)uaddr;
unsigned char cause, diagnostic;
struct net_device *dev;
ax25_uid_assoc *user;
int n, err = 0;
if (addr_len != sizeof(struct sockaddr_rose) && addr_len != sizeof(struct full_sockaddr_rose))
return -EINVAL;
if (addr->srose_family != AF_ROSE)
return -EINVAL;
if (addr_len == sizeof(struct sockaddr_rose) && addr->srose_ndigis > 1)
return -EINVAL;
if ((unsigned int) addr->srose_ndigis > ROSE_MAX_DIGIS)
return -EINVAL;
/* Source + Destination digis should not exceed ROSE_MAX_DIGIS */
if ((rose->source_ndigis + addr->srose_ndigis) > ROSE_MAX_DIGIS)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) {
/* Connect completed during a ERESTARTSYS event */
sock->state = SS_CONNECTED;
goto out_release;
}
if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) {
sock->state = SS_UNCONNECTED;
err = -ECONNREFUSED;
goto out_release;
}
if (sk->sk_state == TCP_ESTABLISHED) {
/* No reconnect on a seqpacket socket */
err = -EISCONN;
goto out_release;
}
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
rose->neighbour = rose_get_neigh(&addr->srose_addr, &cause,
&diagnostic, 0);
if (!rose->neighbour) {
err = -ENETUNREACH;
goto out_release;
}
rose->lci = rose_new_lci(rose->neighbour);
if (!rose->lci) {
err = -ENETUNREACH;
goto out_release;
}
if (sock_flag(sk, SOCK_ZAPPED)) { /* Must bind first - autobinding in this may or may not work */
sock_reset_flag(sk, SOCK_ZAPPED);
if ((dev = rose_dev_first()) == NULL) {
err = -ENETUNREACH;
goto out_release;
}
user = ax25_findbyuid(current_euid());
if (!user) {
err = -EINVAL;
goto out_release;
}
memcpy(&rose->source_addr, dev->dev_addr, ROSE_ADDR_LEN);
rose->source_call = user->call;
rose->device = dev;
ax25_uid_put(user);
rose_insert_socket(sk); /* Finish the bind */
}
rose->dest_addr = addr->srose_addr;
rose->dest_call = addr->srose_call;
rose->rand = ((long)rose & 0xFFFF) + rose->lci;
rose->dest_ndigis = addr->srose_ndigis;
if (addr_len == sizeof(struct full_sockaddr_rose)) {
struct full_sockaddr_rose *full_addr = (struct full_sockaddr_rose *)uaddr;
for (n = 0 ; n < addr->srose_ndigis ; n++)
rose->dest_digis[n] = full_addr->srose_digis[n];
} else {
if (rose->dest_ndigis == 1) {
rose->dest_digis[0] = addr->srose_digi;
}
}
/* Move to connecting socket, start sending Connect Requests */
sock->state = SS_CONNECTING;
sk->sk_state = TCP_SYN_SENT;
rose->state = ROSE_STATE_1;
rose->neighbour->use++;
rose_write_internal(sk, ROSE_CALL_REQUEST);
rose_start_heartbeat(sk);
rose_start_t1timer(sk);
/* Now the loop */
if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) {
err = -EINPROGRESS;
goto out_release;
}
/*
* A Connect Ack with Choke or timeout or failed routing will go to
* closed.
*/
if (sk->sk_state == TCP_SYN_SENT) {
DEFINE_WAIT(wait);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
if (sk->sk_state != TCP_SYN_SENT)
break;
if (!signal_pending(current)) {
release_sock(sk);
schedule();
lock_sock(sk);
continue;
}
err = -ERESTARTSYS;
break;
}
finish_wait(sk_sleep(sk), &wait);
if (err)
goto out_release;
}
if (sk->sk_state != TCP_ESTABLISHED) {
sock->state = SS_UNCONNECTED;
err = sock_error(sk); /* Always set at this point */
goto out_release;
}
sock->state = SS_CONNECTED;
out_release:
release_sock(sk);
return err;
}
static int rose_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sk_buff *skb;
struct sock *newsk;
DEFINE_WAIT(wait);
struct sock *sk;
int err = 0;
if ((sk = sock->sk) == NULL)
return -EINVAL;
lock_sock(sk);
if (sk->sk_type != SOCK_SEQPACKET) {
err = -EOPNOTSUPP;
goto out_release;
}
if (sk->sk_state != TCP_LISTEN) {
err = -EINVAL;
goto out_release;
}
/*
* The write queue this time is holding sockets ready to use
* hooked into the SABM we saved
*/
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
skb = skb_dequeue(&sk->sk_receive_queue);
if (skb)
break;
if (flags & O_NONBLOCK) {
err = -EWOULDBLOCK;
break;
}
if (!signal_pending(current)) {
release_sock(sk);
schedule();
lock_sock(sk);
continue;
}
err = -ERESTARTSYS;
break;
}
finish_wait(sk_sleep(sk), &wait);
if (err)
goto out_release;
newsk = skb->sk;
sock_graft(newsk, newsock);
/* Now attach up the new socket */
skb->sk = NULL;
kfree_skb(skb);
sk->sk_ack_backlog--;
out_release:
release_sock(sk);
return err;
}
static int rose_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct full_sockaddr_rose *srose = (struct full_sockaddr_rose *)uaddr;
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
int n;
memset(srose, 0, sizeof(*srose));
if (peer != 0) {
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
srose->srose_family = AF_ROSE;
srose->srose_addr = rose->dest_addr;
srose->srose_call = rose->dest_call;
srose->srose_ndigis = rose->dest_ndigis;
for (n = 0; n < rose->dest_ndigis; n++)
srose->srose_digis[n] = rose->dest_digis[n];
} else {
srose->srose_family = AF_ROSE;
srose->srose_addr = rose->source_addr;
srose->srose_call = rose->source_call;
srose->srose_ndigis = rose->source_ndigis;
for (n = 0; n < rose->source_ndigis; n++)
srose->srose_digis[n] = rose->source_digis[n];
}
*uaddr_len = sizeof(struct full_sockaddr_rose);
return 0;
}
int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci)
{
struct sock *sk;
struct sock *make;
struct rose_sock *make_rose;
struct rose_facilities_struct facilities;
int n;
skb->sk = NULL; /* Initially we don't know who it's for */
/*
* skb->data points to the rose frame start
*/
memset(&facilities, 0x00, sizeof(struct rose_facilities_struct));
if (!rose_parse_facilities(skb->data + ROSE_CALL_REQ_FACILITIES_OFF,
skb->len - ROSE_CALL_REQ_FACILITIES_OFF,
&facilities)) {
rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76);
return 0;
}
sk = rose_find_listener(&facilities.source_addr, &facilities.source_call);
/*
* We can't accept the Call Request.
*/
if (sk == NULL || sk_acceptq_is_full(sk) ||
(make = rose_make_new(sk)) == NULL) {
rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120);
return 0;
}
skb->sk = make;
make->sk_state = TCP_ESTABLISHED;
make_rose = rose_sk(make);
make_rose->lci = lci;
make_rose->dest_addr = facilities.dest_addr;
make_rose->dest_call = facilities.dest_call;
make_rose->dest_ndigis = facilities.dest_ndigis;
for (n = 0 ; n < facilities.dest_ndigis ; n++)
make_rose->dest_digis[n] = facilities.dest_digis[n];
make_rose->source_addr = facilities.source_addr;
make_rose->source_call = facilities.source_call;
make_rose->source_ndigis = facilities.source_ndigis;
for (n = 0 ; n < facilities.source_ndigis ; n++)
make_rose->source_digis[n]= facilities.source_digis[n];
make_rose->neighbour = neigh;
make_rose->device = dev;
make_rose->facilities = facilities;
make_rose->neighbour->use++;
if (rose_sk(sk)->defer) {
make_rose->state = ROSE_STATE_5;
} else {
rose_write_internal(make, ROSE_CALL_ACCEPTED);
make_rose->state = ROSE_STATE_3;
rose_start_idletimer(make);
}
make_rose->condition = 0x00;
make_rose->vs = 0;
make_rose->va = 0;
make_rose->vr = 0;
make_rose->vl = 0;
sk->sk_ack_backlog++;
rose_insert_socket(make);
skb_queue_head(&sk->sk_receive_queue, skb);
rose_start_heartbeat(make);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_data_ready(sk, skb->len);
return 1;
}
static int rose_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
struct sockaddr_rose *usrose = (struct sockaddr_rose *)msg->msg_name;
int err;
struct full_sockaddr_rose srose;
struct sk_buff *skb;
unsigned char *asmptr;
int n, size, qbit = 0;
if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT))
return -EINVAL;
if (sock_flag(sk, SOCK_ZAPPED))
return -EADDRNOTAVAIL;
if (sk->sk_shutdown & SEND_SHUTDOWN) {
send_sig(SIGPIPE, current, 0);
return -EPIPE;
}
if (rose->neighbour == NULL || rose->device == NULL)
return -ENETUNREACH;
if (usrose != NULL) {
if (msg->msg_namelen != sizeof(struct sockaddr_rose) && msg->msg_namelen != sizeof(struct full_sockaddr_rose))
return -EINVAL;
memset(&srose, 0, sizeof(struct full_sockaddr_rose));
memcpy(&srose, usrose, msg->msg_namelen);
if (rosecmp(&rose->dest_addr, &srose.srose_addr) != 0 ||
ax25cmp(&rose->dest_call, &srose.srose_call) != 0)
return -EISCONN;
if (srose.srose_ndigis != rose->dest_ndigis)
return -EISCONN;
if (srose.srose_ndigis == rose->dest_ndigis) {
for (n = 0 ; n < srose.srose_ndigis ; n++)
if (ax25cmp(&rose->dest_digis[n],
&srose.srose_digis[n]))
return -EISCONN;
}
if (srose.srose_family != AF_ROSE)
return -EINVAL;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
srose.srose_family = AF_ROSE;
srose.srose_addr = rose->dest_addr;
srose.srose_call = rose->dest_call;
srose.srose_ndigis = rose->dest_ndigis;
for (n = 0 ; n < rose->dest_ndigis ; n++)
srose.srose_digis[n] = rose->dest_digis[n];
}
SOCK_DEBUG(sk, "ROSE: sendto: Addresses built.\n");
/* Build a packet */
SOCK_DEBUG(sk, "ROSE: sendto: building packet.\n");
/* Sanity check the packet size */
if (len > 65535)
return -EMSGSIZE;
size = len + AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN;
if ((skb = sock_alloc_send_skb(sk, size, msg->msg_flags & MSG_DONTWAIT, &err)) == NULL)
return err;
skb_reserve(skb, AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN);
/*
* Put the data on the end
*/
SOCK_DEBUG(sk, "ROSE: Appending user data\n");
skb_reset_transport_header(skb);
skb_put(skb, len);
err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len);
if (err) {
kfree_skb(skb);
return err;
}
/*
* If the Q BIT Include socket option is in force, the first
* byte of the user data is the logical value of the Q Bit.
*/
if (rose->qbitincl) {
qbit = skb->data[0];
skb_pull(skb, 1);
}
/*
* Push down the ROSE header
*/
asmptr = skb_push(skb, ROSE_MIN_LEN);
SOCK_DEBUG(sk, "ROSE: Building Network Header.\n");
/* Build a ROSE Network header */
asmptr[0] = ((rose->lci >> 8) & 0x0F) | ROSE_GFI;
asmptr[1] = (rose->lci >> 0) & 0xFF;
asmptr[2] = ROSE_DATA;
if (qbit)
asmptr[0] |= ROSE_Q_BIT;
SOCK_DEBUG(sk, "ROSE: Built header.\n");
SOCK_DEBUG(sk, "ROSE: Transmitting buffer\n");
if (sk->sk_state != TCP_ESTABLISHED) {
kfree_skb(skb);
return -ENOTCONN;
}
#ifdef M_BIT
#define ROSE_PACLEN (256-ROSE_MIN_LEN)
if (skb->len - ROSE_MIN_LEN > ROSE_PACLEN) {
unsigned char header[ROSE_MIN_LEN];
struct sk_buff *skbn;
int frontlen;
int lg;
/* Save a copy of the Header */
skb_copy_from_linear_data(skb, header, ROSE_MIN_LEN);
skb_pull(skb, ROSE_MIN_LEN);
frontlen = skb_headroom(skb);
while (skb->len > 0) {
if ((skbn = sock_alloc_send_skb(sk, frontlen + ROSE_PACLEN, 0, &err)) == NULL) {
kfree_skb(skb);
return err;
}
skbn->sk = sk;
skbn->free = 1;
skbn->arp = 1;
skb_reserve(skbn, frontlen);
lg = (ROSE_PACLEN > skb->len) ? skb->len : ROSE_PACLEN;
/* Copy the user data */
skb_copy_from_linear_data(skb, skb_put(skbn, lg), lg);
skb_pull(skb, lg);
/* Duplicate the Header */
skb_push(skbn, ROSE_MIN_LEN);
skb_copy_to_linear_data(skbn, header, ROSE_MIN_LEN);
if (skb->len > 0)
skbn->data[2] |= M_BIT;
skb_queue_tail(&sk->sk_write_queue, skbn); /* Throw it on the queue */
}
skb->free = 1;
kfree_skb(skb);
} else {
skb_queue_tail(&sk->sk_write_queue, skb); /* Throw it on the queue */
}
#else
skb_queue_tail(&sk->sk_write_queue, skb); /* Shove it onto the queue */
#endif
rose_kick(sk);
return len;
}
static int rose_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
struct sockaddr_rose *srose = (struct sockaddr_rose *)msg->msg_name;
size_t copied;
unsigned char *asmptr;
struct sk_buff *skb;
int n, er, qbit;
/*
* This works for seqpacket too. The receiver has ordered the queue for
* us! We do one quick check first though
*/
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
/* Now we can treat all alike */
if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL)
return er;
qbit = (skb->data[0] & ROSE_Q_BIT) == ROSE_Q_BIT;
skb_pull(skb, ROSE_MIN_LEN);
if (rose->qbitincl) {
asmptr = skb_push(skb, 1);
*asmptr = qbit;
}
skb_reset_transport_header(skb);
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (srose != NULL) {
srose->srose_family = AF_ROSE;
srose->srose_addr = rose->dest_addr;
srose->srose_call = rose->dest_call;
srose->srose_ndigis = rose->dest_ndigis;
if (msg->msg_namelen >= sizeof(struct full_sockaddr_rose)) {
struct full_sockaddr_rose *full_srose = (struct full_sockaddr_rose *)msg->msg_name;
for (n = 0 ; n < rose->dest_ndigis ; n++)
full_srose->srose_digis[n] = rose->dest_digis[n];
msg->msg_namelen = sizeof(struct full_sockaddr_rose);
} else {
if (rose->dest_ndigis >= 1) {
srose->srose_ndigis = 1;
srose->srose_digi = rose->dest_digis[0];
}
msg->msg_namelen = sizeof(struct sockaddr_rose);
}
}
skb_free_datagram(sk, skb);
return copied;
}
static int rose_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
struct rose_sock *rose = rose_sk(sk);
void __user *argp = (void __user *)arg;
switch (cmd) {
case TIOCOUTQ: {
long amount;
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
return put_user(amount, (unsigned int __user *) argp);
}
case TIOCINQ: {
struct sk_buff *skb;
long amount = 0L;
/* These two are safe on a single CPU system as only user tasks fiddle here */
if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL)
amount = skb->len;
return put_user(amount, (unsigned int __user *) argp);
}
case SIOCGSTAMP:
return sock_get_timestamp(sk, (struct timeval __user *) argp);
case SIOCGSTAMPNS:
return sock_get_timestampns(sk, (struct timespec __user *) argp);
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFMETRIC:
case SIOCSIFMETRIC:
return -EINVAL;
case SIOCADDRT:
case SIOCDELRT:
case SIOCRSCLRRT:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
return rose_rt_ioctl(cmd, argp);
case SIOCRSGCAUSE: {
struct rose_cause_struct rose_cause;
rose_cause.cause = rose->cause;
rose_cause.diagnostic = rose->diagnostic;
return copy_to_user(argp, &rose_cause, sizeof(struct rose_cause_struct)) ? -EFAULT : 0;
}
case SIOCRSSCAUSE: {
struct rose_cause_struct rose_cause;
if (copy_from_user(&rose_cause, argp, sizeof(struct rose_cause_struct)))
return -EFAULT;
rose->cause = rose_cause.cause;
rose->diagnostic = rose_cause.diagnostic;
return 0;
}
case SIOCRSSL2CALL:
if (!capable(CAP_NET_ADMIN)) return -EPERM;
if (ax25cmp(&rose_callsign, &null_ax25_address) != 0)
ax25_listen_release(&rose_callsign, NULL);
if (copy_from_user(&rose_callsign, argp, sizeof(ax25_address)))
return -EFAULT;
if (ax25cmp(&rose_callsign, &null_ax25_address) != 0)
return ax25_listen_register(&rose_callsign, NULL);
return 0;
case SIOCRSGL2CALL:
return copy_to_user(argp, &rose_callsign, sizeof(ax25_address)) ? -EFAULT : 0;
case SIOCRSACCEPT:
if (rose->state == ROSE_STATE_5) {
rose_write_internal(sk, ROSE_CALL_ACCEPTED);
rose_start_idletimer(sk);
rose->condition = 0x00;
rose->vs = 0;
rose->va = 0;
rose->vr = 0;
rose->vl = 0;
rose->state = ROSE_STATE_3;
}
return 0;
default:
return -ENOIOCTLCMD;
}
return 0;
}
#ifdef CONFIG_PROC_FS
static void *rose_info_start(struct seq_file *seq, loff_t *pos)
__acquires(rose_list_lock)
{
spin_lock_bh(&rose_list_lock);
return seq_hlist_start_head(&rose_list, *pos);
}
static void *rose_info_next(struct seq_file *seq, void *v, loff_t *pos)
{
return seq_hlist_next(v, &rose_list, pos);
}
static void rose_info_stop(struct seq_file *seq, void *v)
__releases(rose_list_lock)
{
spin_unlock_bh(&rose_list_lock);
}
static int rose_info_show(struct seq_file *seq, void *v)
{
char buf[11], rsbuf[11];
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"dest_addr dest_call src_addr src_call dev lci neigh st vs vr va t t1 t2 t3 hb idle Snd-Q Rcv-Q inode\n");
else {
struct sock *s = sk_entry(v);
struct rose_sock *rose = rose_sk(s);
const char *devname, *callsign;
const struct net_device *dev = rose->device;
if (!dev)
devname = "???";
else
devname = dev->name;
seq_printf(seq, "%-10s %-9s ",
rose2asc(rsbuf, &rose->dest_addr),
ax2asc(buf, &rose->dest_call));
if (ax25cmp(&rose->source_call, &null_ax25_address) == 0)
callsign = "??????-?";
else
callsign = ax2asc(buf, &rose->source_call);
seq_printf(seq,
"%-10s %-9s %-5s %3.3X %05d %d %d %d %d %3lu %3lu %3lu %3lu %3lu %3lu/%03lu %5d %5d %ld\n",
rose2asc(rsbuf, &rose->source_addr),
callsign,
devname,
rose->lci & 0x0FFF,
(rose->neighbour) ? rose->neighbour->number : 0,
rose->state,
rose->vs,
rose->vr,
rose->va,
ax25_display_timer(&rose->timer) / HZ,
rose->t1 / HZ,
rose->t2 / HZ,
rose->t3 / HZ,
rose->hb / HZ,
ax25_display_timer(&rose->idletimer) / (60 * HZ),
rose->idle / (60 * HZ),
sk_wmem_alloc_get(s),
sk_rmem_alloc_get(s),
s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L);
}
return 0;
}
static const struct seq_operations rose_info_seqops = {
.start = rose_info_start,
.next = rose_info_next,
.stop = rose_info_stop,
.show = rose_info_show,
};
static int rose_info_open(struct inode *inode, struct file *file)
{
return seq_open(file, &rose_info_seqops);
}
static const struct file_operations rose_info_fops = {
.owner = THIS_MODULE,
.open = rose_info_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
#endif /* CONFIG_PROC_FS */
static const struct net_proto_family rose_family_ops = {
.family = PF_ROSE,
.create = rose_create,
.owner = THIS_MODULE,
};
static const struct proto_ops rose_proto_ops = {
.family = PF_ROSE,
.owner = THIS_MODULE,
.release = rose_release,
.bind = rose_bind,
.connect = rose_connect,
.socketpair = sock_no_socketpair,
.accept = rose_accept,
.getname = rose_getname,
.poll = datagram_poll,
.ioctl = rose_ioctl,
.listen = rose_listen,
.shutdown = sock_no_shutdown,
.setsockopt = rose_setsockopt,
.getsockopt = rose_getsockopt,
.sendmsg = rose_sendmsg,
.recvmsg = rose_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static struct notifier_block rose_dev_notifier = {
.notifier_call = rose_device_event,
};
static struct net_device **dev_rose;
static struct ax25_protocol rose_pid = {
.pid = AX25_P_ROSE,
.func = rose_route_frame
};
static struct ax25_linkfail rose_linkfail_notifier = {
.func = rose_link_failed
};
static int __init rose_proto_init(void)
{
int i;
int rc;
if (rose_ndevs > 0x7FFFFFFF/sizeof(struct net_device *)) {
printk(KERN_ERR "ROSE: rose_proto_init - rose_ndevs parameter to large\n");
rc = -EINVAL;
goto out;
}
rc = proto_register(&rose_proto, 0);
if (rc != 0)
goto out;
rose_callsign = null_ax25_address;
dev_rose = kzalloc(rose_ndevs * sizeof(struct net_device *), GFP_KERNEL);
if (dev_rose == NULL) {
printk(KERN_ERR "ROSE: rose_proto_init - unable to allocate device structure\n");
rc = -ENOMEM;
goto out_proto_unregister;
}
for (i = 0; i < rose_ndevs; i++) {
struct net_device *dev;
char name[IFNAMSIZ];
sprintf(name, "rose%d", i);
dev = alloc_netdev(0, name, rose_setup);
if (!dev) {
printk(KERN_ERR "ROSE: rose_proto_init - unable to allocate memory\n");
rc = -ENOMEM;
goto fail;
}
rc = register_netdev(dev);
if (rc) {
printk(KERN_ERR "ROSE: netdevice registration failed\n");
free_netdev(dev);
goto fail;
}
rose_set_lockdep_key(dev);
dev_rose[i] = dev;
}
sock_register(&rose_family_ops);
register_netdevice_notifier(&rose_dev_notifier);
ax25_register_pid(&rose_pid);
ax25_linkfail_register(&rose_linkfail_notifier);
#ifdef CONFIG_SYSCTL
rose_register_sysctl();
#endif
rose_loopback_init();
rose_add_loopback_neigh();
proc_net_fops_create(&init_net, "rose", S_IRUGO, &rose_info_fops);
proc_net_fops_create(&init_net, "rose_neigh", S_IRUGO, &rose_neigh_fops);
proc_net_fops_create(&init_net, "rose_nodes", S_IRUGO, &rose_nodes_fops);
proc_net_fops_create(&init_net, "rose_routes", S_IRUGO, &rose_routes_fops);
out:
return rc;
fail:
while (--i >= 0) {
unregister_netdev(dev_rose[i]);
free_netdev(dev_rose[i]);
}
kfree(dev_rose);
out_proto_unregister:
proto_unregister(&rose_proto);
goto out;
}
module_init(rose_proto_init);
module_param(rose_ndevs, int, 0);
MODULE_PARM_DESC(rose_ndevs, "number of ROSE devices");
MODULE_AUTHOR("Jonathan Naylor G4KLX <g4klx@g4klx.demon.co.uk>");
MODULE_DESCRIPTION("The amateur radio ROSE network layer protocol");
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_ROSE);
static void __exit rose_exit(void)
{
int i;
proc_net_remove(&init_net, "rose");
proc_net_remove(&init_net, "rose_neigh");
proc_net_remove(&init_net, "rose_nodes");
proc_net_remove(&init_net, "rose_routes");
rose_loopback_clear();
rose_rt_free();
ax25_protocol_release(AX25_P_ROSE);
ax25_linkfail_release(&rose_linkfail_notifier);
if (ax25cmp(&rose_callsign, &null_ax25_address) != 0)
ax25_listen_release(&rose_callsign, NULL);
#ifdef CONFIG_SYSCTL
rose_unregister_sysctl();
#endif
unregister_netdevice_notifier(&rose_dev_notifier);
sock_unregister(PF_ROSE);
for (i = 0; i < rose_ndevs; i++) {
struct net_device *dev = dev_rose[i];
if (dev) {
unregister_netdev(dev);
free_netdev(dev);
}
}
kfree(dev_rose);
proto_unregister(&rose_proto);
}
module_exit(rose_exit);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3547_1 |
crossvul-cpp_data_good_5845_19 | /*****************************************************************************
* Linux PPP over L2TP (PPPoX/PPPoL2TP) Sockets
*
* PPPoX --- Generic PPP encapsulation socket family
* PPPoL2TP --- PPP over L2TP (RFC 2661)
*
* Version: 2.0.0
*
* Authors: James Chapman (jchapman@katalix.com)
*
* Based on original work by Martijn van Oosterhout <kleptog@svana.org>
*
* License:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
/* This driver handles only L2TP data frames; control frames are handled by a
* userspace application.
*
* To send data in an L2TP session, userspace opens a PPPoL2TP socket and
* attaches it to a bound UDP socket with local tunnel_id / session_id and
* peer tunnel_id / session_id set. Data can then be sent or received using
* regular socket sendmsg() / recvmsg() calls. Kernel parameters of the socket
* can be read or modified using ioctl() or [gs]etsockopt() calls.
*
* When a PPPoL2TP socket is connected with local and peer session_id values
* zero, the socket is treated as a special tunnel management socket.
*
* Here's example userspace code to create a socket for sending/receiving data
* over an L2TP session:-
*
* struct sockaddr_pppol2tp sax;
* int fd;
* int session_fd;
*
* fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP);
*
* sax.sa_family = AF_PPPOX;
* sax.sa_protocol = PX_PROTO_OL2TP;
* sax.pppol2tp.fd = tunnel_fd; // bound UDP socket
* sax.pppol2tp.addr.sin_addr.s_addr = addr->sin_addr.s_addr;
* sax.pppol2tp.addr.sin_port = addr->sin_port;
* sax.pppol2tp.addr.sin_family = AF_INET;
* sax.pppol2tp.s_tunnel = tunnel_id;
* sax.pppol2tp.s_session = session_id;
* sax.pppol2tp.d_tunnel = peer_tunnel_id;
* sax.pppol2tp.d_session = peer_session_id;
*
* session_fd = connect(fd, (struct sockaddr *)&sax, sizeof(sax));
*
* A pppd plugin that allows PPP traffic to be carried over L2TP using
* this driver is available from the OpenL2TP project at
* http://openl2tp.sourceforge.net.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/jiffies.h>
#include <linux/netdevice.h>
#include <linux/net.h>
#include <linux/inetdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/if_pppox.h>
#include <linux/if_pppol2tp.h>
#include <net/sock.h>
#include <linux/ppp_channel.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/file.h>
#include <linux/hash.h>
#include <linux/sort.h>
#include <linux/proc_fs.h>
#include <linux/l2tp.h>
#include <linux/nsproxy.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/dst.h>
#include <net/ip.h>
#include <net/udp.h>
#include <net/xfrm.h>
#include <net/inet_common.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include "l2tp_core.h"
#define PPPOL2TP_DRV_VERSION "V2.0"
/* Space for UDP, L2TP and PPP headers */
#define PPPOL2TP_HEADER_OVERHEAD 40
/* Number of bytes to build transmit L2TP headers.
* Unfortunately the size is different depending on whether sequence numbers
* are enabled.
*/
#define PPPOL2TP_L2TP_HDR_SIZE_SEQ 10
#define PPPOL2TP_L2TP_HDR_SIZE_NOSEQ 6
/* Private data of each session. This data lives at the end of struct
* l2tp_session, referenced via session->priv[].
*/
struct pppol2tp_session {
int owner; /* pid that opened the socket */
struct sock *sock; /* Pointer to the session
* PPPoX socket */
struct sock *tunnel_sock; /* Pointer to the tunnel UDP
* socket */
int flags; /* accessed by PPPIOCGFLAGS.
* Unused. */
};
static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb);
static const struct ppp_channel_ops pppol2tp_chan_ops = {
.start_xmit = pppol2tp_xmit,
};
static const struct proto_ops pppol2tp_ops;
/* Helpers to obtain tunnel/session contexts from sockets.
*/
static inline struct l2tp_session *pppol2tp_sock_to_session(struct sock *sk)
{
struct l2tp_session *session;
if (sk == NULL)
return NULL;
sock_hold(sk);
session = (struct l2tp_session *)(sk->sk_user_data);
if (session == NULL) {
sock_put(sk);
goto out;
}
BUG_ON(session->magic != L2TP_SESSION_MAGIC);
out:
return session;
}
/*****************************************************************************
* Receive data handling
*****************************************************************************/
static int pppol2tp_recv_payload_hook(struct sk_buff *skb)
{
/* Skip PPP header, if present. In testing, Microsoft L2TP clients
* don't send the PPP header (PPP header compression enabled), but
* other clients can include the header. So we cope with both cases
* here. The PPP header is always FF03 when using L2TP.
*
* Note that skb->data[] isn't dereferenced from a u16 ptr here since
* the field may be unaligned.
*/
if (!pskb_may_pull(skb, 2))
return 1;
if ((skb->data[0] == 0xff) && (skb->data[1] == 0x03))
skb_pull(skb, 2);
return 0;
}
/* Receive message. This is the recvmsg for the PPPoL2TP socket.
*/
static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
int err;
struct sk_buff *skb;
struct sock *sk = sock->sk;
err = -EIO;
if (sk->sk_state & PPPOX_BOUND)
goto end;
err = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
goto end;
if (len > skb->len)
len = skb->len;
else if (len < skb->len)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);
if (likely(err == 0))
err = len;
kfree_skb(skb);
end:
return err;
}
static void pppol2tp_recv(struct l2tp_session *session, struct sk_buff *skb, int data_len)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct sock *sk = NULL;
/* If the socket is bound, send it in to PPP's input queue. Otherwise
* queue it on the session socket.
*/
sk = ps->sock;
if (sk == NULL)
goto no_sock;
if (sk->sk_state & PPPOX_BOUND) {
struct pppox_sock *po;
l2tp_dbg(session, PPPOL2TP_MSG_DATA,
"%s: recv %d byte data frame, passing to ppp\n",
session->name, data_len);
/* We need to forget all info related to the L2TP packet
* gathered in the skb as we are going to reuse the same
* skb for the inner packet.
* Namely we need to:
* - reset xfrm (IPSec) information as it applies to
* the outer L2TP packet and not to the inner one
* - release the dst to force a route lookup on the inner
* IP packet since skb->dst currently points to the dst
* of the UDP tunnel
* - reset netfilter information as it doesn't apply
* to the inner packet either
*/
secpath_reset(skb);
skb_dst_drop(skb);
nf_reset(skb);
po = pppox_sk(sk);
ppp_input(&po->chan, skb);
} else {
l2tp_info(session, PPPOL2TP_MSG_DATA, "%s: socket not bound\n",
session->name);
/* Not bound. Nothing we can do, so discard. */
atomic_long_inc(&session->stats.rx_errors);
kfree_skb(skb);
}
return;
no_sock:
l2tp_info(session, PPPOL2TP_MSG_DATA, "%s: no socket\n", session->name);
kfree_skb(skb);
}
static void pppol2tp_session_sock_hold(struct l2tp_session *session)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
if (ps->sock)
sock_hold(ps->sock);
}
static void pppol2tp_session_sock_put(struct l2tp_session *session)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
if (ps->sock)
sock_put(ps->sock);
}
/************************************************************************
* Transmit handling
***********************************************************************/
/* This is the sendmsg for the PPPoL2TP pppol2tp_session socket. We come here
* when a user application does a sendmsg() on the session socket. L2TP and
* PPP headers must be inserted into the user's data.
*/
static int pppol2tp_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t total_len)
{
static const unsigned char ppph[2] = { 0xff, 0x03 };
struct sock *sk = sock->sk;
struct sk_buff *skb;
int error;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int uhlen;
error = -ENOTCONN;
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto error;
/* Get session and tunnel contexts */
error = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto error;
ps = l2tp_session_priv(session);
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto error_put_sess;
uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
/* Allocate a socket buffer */
error = -ENOMEM;
skb = sock_wmalloc(sk, NET_SKB_PAD + sizeof(struct iphdr) +
uhlen + session->hdr_len +
sizeof(ppph) + total_len,
0, GFP_KERNEL);
if (!skb)
goto error_put_sess_tun;
/* Reserve space for headers. */
skb_reserve(skb, NET_SKB_PAD);
skb_reset_network_header(skb);
skb_reserve(skb, sizeof(struct iphdr));
skb_reset_transport_header(skb);
skb_reserve(skb, uhlen);
/* Add PPP header */
skb->data[0] = ppph[0];
skb->data[1] = ppph[1];
skb_put(skb, 2);
/* Copy user data into skb */
error = memcpy_fromiovec(skb_put(skb, total_len), m->msg_iov,
total_len);
if (error < 0) {
kfree_skb(skb);
goto error_put_sess_tun;
}
local_bh_disable();
l2tp_xmit_skb(session, skb, session->hdr_len);
local_bh_enable();
sock_put(ps->tunnel_sock);
sock_put(sk);
return total_len;
error_put_sess_tun:
sock_put(ps->tunnel_sock);
error_put_sess:
sock_put(sk);
error:
return error;
}
/* Transmit function called by generic PPP driver. Sends PPP frame
* over PPPoL2TP socket.
*
* This is almost the same as pppol2tp_sendmsg(), but rather than
* being called with a msghdr from userspace, it is called with a skb
* from the kernel.
*
* The supplied skb from ppp doesn't have enough headroom for the
* insertion of L2TP, UDP and IP headers so we need to allocate more
* headroom in the skb. This will create a cloned skb. But we must be
* careful in the error case because the caller will expect to free
* the skb it supplied, not our cloned skb. So we take care to always
* leave the original skb unfreed if we return an error.
*/
static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb)
{
static const u8 ppph[2] = { 0xff, 0x03 };
struct sock *sk = (struct sock *) chan->private;
struct sock *sk_tun;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int uhlen, headroom;
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto abort;
/* Get session and tunnel contexts from the socket */
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto abort;
ps = l2tp_session_priv(session);
sk_tun = ps->tunnel_sock;
if (sk_tun == NULL)
goto abort_put_sess;
tunnel = l2tp_sock_to_tunnel(sk_tun);
if (tunnel == NULL)
goto abort_put_sess;
uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
headroom = NET_SKB_PAD +
sizeof(struct iphdr) + /* IP header */
uhlen + /* UDP header (if L2TP_ENCAPTYPE_UDP) */
session->hdr_len + /* L2TP header */
sizeof(ppph); /* PPP header */
if (skb_cow_head(skb, headroom))
goto abort_put_sess_tun;
/* Setup PPP header */
__skb_push(skb, sizeof(ppph));
skb->data[0] = ppph[0];
skb->data[1] = ppph[1];
local_bh_disable();
l2tp_xmit_skb(session, skb, session->hdr_len);
local_bh_enable();
sock_put(sk_tun);
sock_put(sk);
return 1;
abort_put_sess_tun:
sock_put(sk_tun);
abort_put_sess:
sock_put(sk);
abort:
/* Free the original skb */
kfree_skb(skb);
return 1;
}
/*****************************************************************************
* Session (and tunnel control) socket create/destroy.
*****************************************************************************/
/* Called by l2tp_core when a session socket is being closed.
*/
static void pppol2tp_session_close(struct l2tp_session *session)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct sock *sk = ps->sock;
struct socket *sock = sk->sk_socket;
BUG_ON(session->magic != L2TP_SESSION_MAGIC);
if (sock) {
inet_shutdown(sock, 2);
/* Don't let the session go away before our socket does */
l2tp_session_inc_refcount(session);
}
return;
}
/* Really kill the session socket. (Called from sock_put() if
* refcnt == 0.)
*/
static void pppol2tp_session_destruct(struct sock *sk)
{
struct l2tp_session *session = sk->sk_user_data;
if (session) {
sk->sk_user_data = NULL;
BUG_ON(session->magic != L2TP_SESSION_MAGIC);
l2tp_session_dec_refcount(session);
}
return;
}
/* Called when the PPPoX socket (session) is closed.
*/
static int pppol2tp_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
int error;
if (!sk)
return 0;
error = -EBADF;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD) != 0)
goto error;
pppox_unbind_sock(sk);
/* Signal the death of the socket. */
sk->sk_state = PPPOX_DEAD;
sock_orphan(sk);
sock->sk = NULL;
session = pppol2tp_sock_to_session(sk);
/* Purge any queued data */
if (session != NULL) {
__l2tp_session_unhash(session);
l2tp_session_queue_purge(session);
sock_put(sk);
}
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
release_sock(sk);
/* This will delete the session context via
* pppol2tp_session_destruct() if the socket's refcnt drops to
* zero.
*/
sock_put(sk);
return 0;
error:
release_sock(sk);
return error;
}
static struct proto pppol2tp_sk_proto = {
.name = "PPPOL2TP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct pppox_sock),
};
static int pppol2tp_backlog_recv(struct sock *sk, struct sk_buff *skb)
{
int rc;
rc = l2tp_udp_encap_recv(sk, skb);
if (rc)
kfree_skb(skb);
return NET_RX_SUCCESS;
}
/* socket() handler. Initialize a new struct sock.
*/
static int pppol2tp_create(struct net *net, struct socket *sock)
{
int error = -ENOMEM;
struct sock *sk;
sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pppol2tp_sk_proto);
if (!sk)
goto out;
sock_init_data(sock, sk);
sock->state = SS_UNCONNECTED;
sock->ops = &pppol2tp_ops;
sk->sk_backlog_rcv = pppol2tp_backlog_recv;
sk->sk_protocol = PX_PROTO_OL2TP;
sk->sk_family = PF_PPPOX;
sk->sk_state = PPPOX_NONE;
sk->sk_type = SOCK_STREAM;
sk->sk_destruct = pppol2tp_session_destruct;
error = 0;
out:
return error;
}
#if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE)
static void pppol2tp_show(struct seq_file *m, void *arg)
{
struct l2tp_session *session = arg;
struct pppol2tp_session *ps = l2tp_session_priv(session);
if (ps) {
struct pppox_sock *po = pppox_sk(ps->sock);
if (po)
seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan));
}
}
#endif
/* connect() handler. Attach a PPPoX socket to a tunnel UDP socket
*/
static int pppol2tp_connect(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_pppol2tp *sp = (struct sockaddr_pppol2tp *) uservaddr;
struct pppox_sock *po = pppox_sk(sk);
struct l2tp_session *session = NULL;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
struct dst_entry *dst;
struct l2tp_session_cfg cfg = { 0, };
int error = 0;
u32 tunnel_id, peer_tunnel_id;
u32 session_id, peer_session_id;
int ver = 2;
int fd;
lock_sock(sk);
error = -EINVAL;
if (sp->sa_protocol != PX_PROTO_OL2TP)
goto end;
/* Check for already bound sockets */
error = -EBUSY;
if (sk->sk_state & PPPOX_CONNECTED)
goto end;
/* We don't supporting rebinding anyway */
error = -EALREADY;
if (sk->sk_user_data)
goto end; /* socket is already attached */
/* Get params from socket address. Handle L2TPv2 and L2TPv3.
* This is nasty because there are different sockaddr_pppol2tp
* structs for L2TPv2, L2TPv3, over IPv4 and IPv6. We use
* the sockaddr size to determine which structure the caller
* is using.
*/
peer_tunnel_id = 0;
if (sockaddr_len == sizeof(struct sockaddr_pppol2tp)) {
fd = sp->pppol2tp.fd;
tunnel_id = sp->pppol2tp.s_tunnel;
peer_tunnel_id = sp->pppol2tp.d_tunnel;
session_id = sp->pppol2tp.s_session;
peer_session_id = sp->pppol2tp.d_session;
} else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpv3)) {
struct sockaddr_pppol2tpv3 *sp3 =
(struct sockaddr_pppol2tpv3 *) sp;
ver = 3;
fd = sp3->pppol2tp.fd;
tunnel_id = sp3->pppol2tp.s_tunnel;
peer_tunnel_id = sp3->pppol2tp.d_tunnel;
session_id = sp3->pppol2tp.s_session;
peer_session_id = sp3->pppol2tp.d_session;
} else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpin6)) {
struct sockaddr_pppol2tpin6 *sp6 =
(struct sockaddr_pppol2tpin6 *) sp;
fd = sp6->pppol2tp.fd;
tunnel_id = sp6->pppol2tp.s_tunnel;
peer_tunnel_id = sp6->pppol2tp.d_tunnel;
session_id = sp6->pppol2tp.s_session;
peer_session_id = sp6->pppol2tp.d_session;
} else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpv3in6)) {
struct sockaddr_pppol2tpv3in6 *sp6 =
(struct sockaddr_pppol2tpv3in6 *) sp;
ver = 3;
fd = sp6->pppol2tp.fd;
tunnel_id = sp6->pppol2tp.s_tunnel;
peer_tunnel_id = sp6->pppol2tp.d_tunnel;
session_id = sp6->pppol2tp.s_session;
peer_session_id = sp6->pppol2tp.d_session;
} else {
error = -EINVAL;
goto end; /* bad socket address */
}
/* Don't bind if tunnel_id is 0 */
error = -EINVAL;
if (tunnel_id == 0)
goto end;
tunnel = l2tp_tunnel_find(sock_net(sk), tunnel_id);
/* Special case: create tunnel context if session_id and
* peer_session_id is 0. Otherwise look up tunnel using supplied
* tunnel id.
*/
if ((session_id == 0) && (peer_session_id == 0)) {
if (tunnel == NULL) {
struct l2tp_tunnel_cfg tcfg = {
.encap = L2TP_ENCAPTYPE_UDP,
.debug = 0,
};
error = l2tp_tunnel_create(sock_net(sk), fd, ver, tunnel_id, peer_tunnel_id, &tcfg, &tunnel);
if (error < 0)
goto end;
}
} else {
/* Error if we can't find the tunnel */
error = -ENOENT;
if (tunnel == NULL)
goto end;
/* Error if socket is not prepped */
if (tunnel->sock == NULL)
goto end;
}
if (tunnel->recv_payload_hook == NULL)
tunnel->recv_payload_hook = pppol2tp_recv_payload_hook;
if (tunnel->peer_tunnel_id == 0)
tunnel->peer_tunnel_id = peer_tunnel_id;
/* Create session if it doesn't already exist. We handle the
* case where a session was previously created by the netlink
* interface by checking that the session doesn't already have
* a socket and its tunnel socket are what we expect. If any
* of those checks fail, return EEXIST to the caller.
*/
session = l2tp_session_find(sock_net(sk), tunnel, session_id);
if (session == NULL) {
/* Default MTU must allow space for UDP/L2TP/PPP
* headers.
*/
cfg.mtu = cfg.mru = 1500 - PPPOL2TP_HEADER_OVERHEAD;
/* Allocate and initialize a new session context. */
session = l2tp_session_create(sizeof(struct pppol2tp_session),
tunnel, session_id,
peer_session_id, &cfg);
if (session == NULL) {
error = -ENOMEM;
goto end;
}
} else {
ps = l2tp_session_priv(session);
error = -EEXIST;
if (ps->sock != NULL)
goto end;
/* consistency checks */
if (ps->tunnel_sock != tunnel->sock)
goto end;
}
/* Associate session with its PPPoL2TP socket */
ps = l2tp_session_priv(session);
ps->owner = current->pid;
ps->sock = sk;
ps->tunnel_sock = tunnel->sock;
session->recv_skb = pppol2tp_recv;
session->session_close = pppol2tp_session_close;
#if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE)
session->show = pppol2tp_show;
#endif
/* We need to know each time a skb is dropped from the reorder
* queue.
*/
session->ref = pppol2tp_session_sock_hold;
session->deref = pppol2tp_session_sock_put;
/* If PMTU discovery was enabled, use the MTU that was discovered */
dst = sk_dst_get(sk);
if (dst != NULL) {
u32 pmtu = dst_mtu(__sk_dst_get(sk));
if (pmtu != 0)
session->mtu = session->mru = pmtu -
PPPOL2TP_HEADER_OVERHEAD;
dst_release(dst);
}
/* Special case: if source & dest session_id == 0x0000, this
* socket is being created to manage the tunnel. Just set up
* the internal context for use by ioctl() and sockopt()
* handlers.
*/
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
error = 0;
goto out_no_ppp;
}
/* The only header we need to worry about is the L2TP
* header. This size is different depending on whether
* sequence numbers are enabled for the data channel.
*/
po->chan.hdrlen = PPPOL2TP_L2TP_HDR_SIZE_NOSEQ;
po->chan.private = sk;
po->chan.ops = &pppol2tp_chan_ops;
po->chan.mtu = session->mtu;
error = ppp_register_net_channel(sock_net(sk), &po->chan);
if (error)
goto end;
out_no_ppp:
/* This is how we get the session context from the socket. */
sk->sk_user_data = session;
sk->sk_state = PPPOX_CONNECTED;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: created\n",
session->name);
end:
release_sock(sk);
return error;
}
#ifdef CONFIG_L2TP_V3
/* Called when creating sessions via the netlink interface.
*/
static int pppol2tp_session_create(struct net *net, u32 tunnel_id, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)
{
int error;
struct l2tp_tunnel *tunnel;
struct l2tp_session *session;
struct pppol2tp_session *ps;
tunnel = l2tp_tunnel_find(net, tunnel_id);
/* Error if we can't find the tunnel */
error = -ENOENT;
if (tunnel == NULL)
goto out;
/* Error if tunnel socket is not prepped */
if (tunnel->sock == NULL)
goto out;
/* Check that this session doesn't already exist */
error = -EEXIST;
session = l2tp_session_find(net, tunnel, session_id);
if (session != NULL)
goto out;
/* Default MTU values. */
if (cfg->mtu == 0)
cfg->mtu = 1500 - PPPOL2TP_HEADER_OVERHEAD;
if (cfg->mru == 0)
cfg->mru = cfg->mtu;
/* Allocate and initialize a new session context. */
error = -ENOMEM;
session = l2tp_session_create(sizeof(struct pppol2tp_session),
tunnel, session_id,
peer_session_id, cfg);
if (session == NULL)
goto out;
ps = l2tp_session_priv(session);
ps->tunnel_sock = tunnel->sock;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: created\n",
session->name);
error = 0;
out:
return error;
}
#endif /* CONFIG_L2TP_V3 */
/* getname() support.
*/
static int pppol2tp_getname(struct socket *sock, struct sockaddr *uaddr,
int *usockaddr_len, int peer)
{
int len = 0;
int error = 0;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct sock *sk = sock->sk;
struct inet_sock *inet;
struct pppol2tp_session *pls;
error = -ENOTCONN;
if (sk == NULL)
goto end;
if (sk->sk_state != PPPOX_CONNECTED)
goto end;
error = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
pls = l2tp_session_priv(session);
tunnel = l2tp_sock_to_tunnel(pls->tunnel_sock);
if (tunnel == NULL) {
error = -EBADF;
goto end_put_sess;
}
inet = inet_sk(tunnel->sock);
if ((tunnel->version == 2) && (tunnel->sock->sk_family == AF_INET)) {
struct sockaddr_pppol2tp sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin_family = AF_INET;
sp.pppol2tp.addr.sin_port = inet->inet_dport;
sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr;
memcpy(uaddr, &sp, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if ((tunnel->version == 2) &&
(tunnel->sock->sk_family == AF_INET6)) {
struct sockaddr_pppol2tpin6 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin6_family = AF_INET6;
sp.pppol2tp.addr.sin6_port = inet->inet_dport;
memcpy(&sp.pppol2tp.addr.sin6_addr, &tunnel->sock->sk_v6_daddr,
sizeof(tunnel->sock->sk_v6_daddr));
memcpy(uaddr, &sp, len);
} else if ((tunnel->version == 3) &&
(tunnel->sock->sk_family == AF_INET6)) {
struct sockaddr_pppol2tpv3in6 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin6_family = AF_INET6;
sp.pppol2tp.addr.sin6_port = inet->inet_dport;
memcpy(&sp.pppol2tp.addr.sin6_addr, &tunnel->sock->sk_v6_daddr,
sizeof(tunnel->sock->sk_v6_daddr));
memcpy(uaddr, &sp, len);
#endif
} else if (tunnel->version == 3) {
struct sockaddr_pppol2tpv3 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin_family = AF_INET;
sp.pppol2tp.addr.sin_port = inet->inet_dport;
sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr;
memcpy(uaddr, &sp, len);
}
*usockaddr_len = len;
sock_put(pls->tunnel_sock);
end_put_sess:
sock_put(sk);
error = 0;
end:
return error;
}
/****************************************************************************
* ioctl() handlers.
*
* The PPPoX socket is created for L2TP sessions: tunnels have their own UDP
* sockets. However, in order to control kernel tunnel features, we allow
* userspace to create a special "tunnel" PPPoX socket which is used for
* control only. Tunnel PPPoX sockets have session_id == 0 and simply allow
* the user application to issue L2TP setsockopt(), getsockopt() and ioctl()
* calls.
****************************************************************************/
static void pppol2tp_copy_stats(struct pppol2tp_ioc_stats *dest,
struct l2tp_stats *stats)
{
dest->tx_packets = atomic_long_read(&stats->tx_packets);
dest->tx_bytes = atomic_long_read(&stats->tx_bytes);
dest->tx_errors = atomic_long_read(&stats->tx_errors);
dest->rx_packets = atomic_long_read(&stats->rx_packets);
dest->rx_bytes = atomic_long_read(&stats->rx_bytes);
dest->rx_seq_discards = atomic_long_read(&stats->rx_seq_discards);
dest->rx_oos_packets = atomic_long_read(&stats->rx_oos_packets);
dest->rx_errors = atomic_long_read(&stats->rx_errors);
}
/* Session ioctl helper.
*/
static int pppol2tp_session_ioctl(struct l2tp_session *session,
unsigned int cmd, unsigned long arg)
{
struct ifreq ifr;
int err = 0;
struct sock *sk;
int val = (int) arg;
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct l2tp_tunnel *tunnel = session->tunnel;
struct pppol2tp_ioc_stats stats;
l2tp_dbg(session, PPPOL2TP_MSG_CONTROL,
"%s: pppol2tp_session_ioctl(cmd=%#x, arg=%#lx)\n",
session->name, cmd, arg);
sk = ps->sock;
sock_hold(sk);
switch (cmd) {
case SIOCGIFMTU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (copy_from_user(&ifr, (void __user *) arg, sizeof(struct ifreq)))
break;
ifr.ifr_mtu = session->mtu;
if (copy_to_user((void __user *) arg, &ifr, sizeof(struct ifreq)))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get mtu=%d\n",
session->name, session->mtu);
err = 0;
break;
case SIOCSIFMTU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (copy_from_user(&ifr, (void __user *) arg, sizeof(struct ifreq)))
break;
session->mtu = ifr.ifr_mtu;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set mtu=%d\n",
session->name, session->mtu);
err = 0;
break;
case PPPIOCGMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (put_user(session->mru, (int __user *) arg))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get mru=%d\n",
session->name, session->mru);
err = 0;
break;
case PPPIOCSMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (get_user(val, (int __user *) arg))
break;
session->mru = val;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set mru=%d\n",
session->name, session->mru);
err = 0;
break;
case PPPIOCGFLAGS:
err = -EFAULT;
if (put_user(ps->flags, (int __user *) arg))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get flags=%d\n",
session->name, ps->flags);
err = 0;
break;
case PPPIOCSFLAGS:
err = -EFAULT;
if (get_user(val, (int __user *) arg))
break;
ps->flags = val;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set flags=%d\n",
session->name, ps->flags);
err = 0;
break;
case PPPIOCGL2TPSTATS:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
memset(&stats, 0, sizeof(stats));
stats.tunnel_id = tunnel->tunnel_id;
stats.session_id = session->session_id;
pppol2tp_copy_stats(&stats, &session->stats);
if (copy_to_user((void __user *) arg, &stats,
sizeof(stats)))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get L2TP stats\n",
session->name);
err = 0;
break;
default:
err = -ENOSYS;
break;
}
sock_put(sk);
return err;
}
/* Tunnel ioctl helper.
*
* Note the special handling for PPPIOCGL2TPSTATS below. If the ioctl data
* specifies a session_id, the session ioctl handler is called. This allows an
* application to retrieve session stats via a tunnel socket.
*/
static int pppol2tp_tunnel_ioctl(struct l2tp_tunnel *tunnel,
unsigned int cmd, unsigned long arg)
{
int err = 0;
struct sock *sk;
struct pppol2tp_ioc_stats stats;
l2tp_dbg(tunnel, PPPOL2TP_MSG_CONTROL,
"%s: pppol2tp_tunnel_ioctl(cmd=%#x, arg=%#lx)\n",
tunnel->name, cmd, arg);
sk = tunnel->sock;
sock_hold(sk);
switch (cmd) {
case PPPIOCGL2TPSTATS:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
if (copy_from_user(&stats, (void __user *) arg,
sizeof(stats))) {
err = -EFAULT;
break;
}
if (stats.session_id != 0) {
/* resend to session ioctl handler */
struct l2tp_session *session =
l2tp_session_find(sock_net(sk), tunnel, stats.session_id);
if (session != NULL)
err = pppol2tp_session_ioctl(session, cmd, arg);
else
err = -EBADR;
break;
}
#ifdef CONFIG_XFRM
stats.using_ipsec = (sk->sk_policy[0] || sk->sk_policy[1]) ? 1 : 0;
#endif
pppol2tp_copy_stats(&stats, &tunnel->stats);
if (copy_to_user((void __user *) arg, &stats, sizeof(stats))) {
err = -EFAULT;
break;
}
l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: get L2TP stats\n",
tunnel->name);
err = 0;
break;
default:
err = -ENOSYS;
break;
}
sock_put(sk);
return err;
}
/* Main ioctl() handler.
* Dispatch to tunnel or session helpers depending on the socket.
*/
static int pppol2tp_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int err;
if (!sk)
return 0;
err = -EBADF;
if (sock_flag(sk, SOCK_DEAD) != 0)
goto end;
err = -ENOTCONN;
if ((sk->sk_user_data == NULL) ||
(!(sk->sk_state & (PPPOX_CONNECTED | PPPOX_BOUND))))
goto end;
/* Get session context from the socket */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
/* Special case: if session's session_id is zero, treat ioctl as a
* tunnel ioctl
*/
ps = l2tp_session_priv(session);
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
err = -EBADF;
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto end_put_sess;
err = pppol2tp_tunnel_ioctl(tunnel, cmd, arg);
sock_put(ps->tunnel_sock);
goto end_put_sess;
}
err = pppol2tp_session_ioctl(session, cmd, arg);
end_put_sess:
sock_put(sk);
end:
return err;
}
/*****************************************************************************
* setsockopt() / getsockopt() support.
*
* The PPPoX socket is created for L2TP sessions: tunnels have their own UDP
* sockets. In order to control kernel tunnel features, we allow userspace to
* create a special "tunnel" PPPoX socket which is used for control only.
* Tunnel PPPoX sockets have session_id == 0 and simply allow the user
* application to issue L2TP setsockopt(), getsockopt() and ioctl() calls.
*****************************************************************************/
/* Tunnel setsockopt() helper.
*/
static int pppol2tp_tunnel_setsockopt(struct sock *sk,
struct l2tp_tunnel *tunnel,
int optname, int val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_DEBUG:
tunnel->debug = val;
l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: set debug=%x\n",
tunnel->name, tunnel->debug);
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Session setsockopt helper.
*/
static int pppol2tp_session_setsockopt(struct sock *sk,
struct l2tp_session *session,
int optname, int val)
{
int err = 0;
struct pppol2tp_session *ps = l2tp_session_priv(session);
switch (optname) {
case PPPOL2TP_SO_RECVSEQ:
if ((val != 0) && (val != 1)) {
err = -EINVAL;
break;
}
session->recv_seq = val ? -1 : 0;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set recv_seq=%d\n",
session->name, session->recv_seq);
break;
case PPPOL2TP_SO_SENDSEQ:
if ((val != 0) && (val != 1)) {
err = -EINVAL;
break;
}
session->send_seq = val ? -1 : 0;
{
struct sock *ssk = ps->sock;
struct pppox_sock *po = pppox_sk(ssk);
po->chan.hdrlen = val ? PPPOL2TP_L2TP_HDR_SIZE_SEQ :
PPPOL2TP_L2TP_HDR_SIZE_NOSEQ;
}
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set send_seq=%d\n",
session->name, session->send_seq);
break;
case PPPOL2TP_SO_LNSMODE:
if ((val != 0) && (val != 1)) {
err = -EINVAL;
break;
}
session->lns_mode = val ? -1 : 0;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set lns_mode=%d\n",
session->name, session->lns_mode);
break;
case PPPOL2TP_SO_DEBUG:
session->debug = val;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set debug=%x\n",
session->name, session->debug);
break;
case PPPOL2TP_SO_REORDERTO:
session->reorder_timeout = msecs_to_jiffies(val);
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set reorder_timeout=%d\n",
session->name, session->reorder_timeout);
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Main setsockopt() entry point.
* Does API checks, then calls either the tunnel or session setsockopt
* handler, according to whether the PPPoL2TP socket is a for a regular
* session or the special tunnel type.
*/
static int pppol2tp_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int val;
int err;
if (level != SOL_PPPOL2TP)
return udp_prot.setsockopt(sk, level, optname, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
err = -ENOTCONN;
if (sk->sk_user_data == NULL)
goto end;
/* Get session context from the socket */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
/* Special case: if session_id == 0x0000, treat as operation on tunnel
*/
ps = l2tp_session_priv(session);
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
err = -EBADF;
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto end_put_sess;
err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val);
sock_put(ps->tunnel_sock);
} else
err = pppol2tp_session_setsockopt(sk, session, optname, val);
err = 0;
end_put_sess:
sock_put(sk);
end:
return err;
}
/* Tunnel getsockopt helper. Called with sock locked.
*/
static int pppol2tp_tunnel_getsockopt(struct sock *sk,
struct l2tp_tunnel *tunnel,
int optname, int *val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_DEBUG:
*val = tunnel->debug;
l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: get debug=%x\n",
tunnel->name, tunnel->debug);
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Session getsockopt helper. Called with sock locked.
*/
static int pppol2tp_session_getsockopt(struct sock *sk,
struct l2tp_session *session,
int optname, int *val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_RECVSEQ:
*val = session->recv_seq;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get recv_seq=%d\n", session->name, *val);
break;
case PPPOL2TP_SO_SENDSEQ:
*val = session->send_seq;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get send_seq=%d\n", session->name, *val);
break;
case PPPOL2TP_SO_LNSMODE:
*val = session->lns_mode;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get lns_mode=%d\n", session->name, *val);
break;
case PPPOL2TP_SO_DEBUG:
*val = session->debug;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get debug=%d\n",
session->name, *val);
break;
case PPPOL2TP_SO_REORDERTO:
*val = (int) jiffies_to_msecs(session->reorder_timeout);
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get reorder_timeout=%d\n", session->name, *val);
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
/* Main getsockopt() entry point.
* Does API checks, then calls either the tunnel or session getsockopt
* handler, according to whether the PPPoX socket is a for a regular session
* or the special tunnel type.
*/
static int pppol2tp_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
int val, len;
int err;
struct pppol2tp_session *ps;
if (level != SOL_PPPOL2TP)
return udp_prot.getsockopt(sk, level, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
if (len < 0)
return -EINVAL;
err = -ENOTCONN;
if (sk->sk_user_data == NULL)
goto end;
/* Get the session context */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
/* Special case: if session_id == 0x0000, treat as operation on tunnel */
ps = l2tp_session_priv(session);
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
err = -EBADF;
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto end_put_sess;
err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val);
sock_put(ps->tunnel_sock);
} else
err = pppol2tp_session_getsockopt(sk, session, optname, &val);
err = -EFAULT;
if (put_user(len, optlen))
goto end_put_sess;
if (copy_to_user((void __user *) optval, &val, len))
goto end_put_sess;
err = 0;
end_put_sess:
sock_put(sk);
end:
return err;
}
/*****************************************************************************
* /proc filesystem for debug
* Since the original pppol2tp driver provided /proc/net/pppol2tp for
* L2TPv2, we dump only L2TPv2 tunnels and sessions here.
*****************************************************************************/
static unsigned int pppol2tp_net_id;
#ifdef CONFIG_PROC_FS
struct pppol2tp_seq_data {
struct seq_net_private p;
int tunnel_idx; /* current tunnel */
int session_idx; /* index of session within current tunnel */
struct l2tp_tunnel *tunnel;
struct l2tp_session *session; /* NULL means get next tunnel */
};
static void pppol2tp_next_tunnel(struct net *net, struct pppol2tp_seq_data *pd)
{
for (;;) {
pd->tunnel = l2tp_tunnel_find_nth(net, pd->tunnel_idx);
pd->tunnel_idx++;
if (pd->tunnel == NULL)
break;
/* Ignore L2TPv3 tunnels */
if (pd->tunnel->version < 3)
break;
}
}
static void pppol2tp_next_session(struct net *net, struct pppol2tp_seq_data *pd)
{
pd->session = l2tp_session_find_nth(pd->tunnel, pd->session_idx);
pd->session_idx++;
if (pd->session == NULL) {
pd->session_idx = 0;
pppol2tp_next_tunnel(net, pd);
}
}
static void *pppol2tp_seq_start(struct seq_file *m, loff_t *offs)
{
struct pppol2tp_seq_data *pd = SEQ_START_TOKEN;
loff_t pos = *offs;
struct net *net;
if (!pos)
goto out;
BUG_ON(m->private == NULL);
pd = m->private;
net = seq_file_net(m);
if (pd->tunnel == NULL)
pppol2tp_next_tunnel(net, pd);
else
pppol2tp_next_session(net, pd);
/* NULL tunnel and session indicates end of list */
if ((pd->tunnel == NULL) && (pd->session == NULL))
pd = NULL;
out:
return pd;
}
static void *pppol2tp_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return NULL;
}
static void pppol2tp_seq_stop(struct seq_file *p, void *v)
{
/* nothing to do */
}
static void pppol2tp_seq_tunnel_show(struct seq_file *m, void *v)
{
struct l2tp_tunnel *tunnel = v;
seq_printf(m, "\nTUNNEL '%s', %c %d\n",
tunnel->name,
(tunnel == tunnel->sock->sk_user_data) ? 'Y' : 'N',
atomic_read(&tunnel->ref_count) - 1);
seq_printf(m, " %08x %ld/%ld/%ld %ld/%ld/%ld\n",
tunnel->debug,
atomic_long_read(&tunnel->stats.tx_packets),
atomic_long_read(&tunnel->stats.tx_bytes),
atomic_long_read(&tunnel->stats.tx_errors),
atomic_long_read(&tunnel->stats.rx_packets),
atomic_long_read(&tunnel->stats.rx_bytes),
atomic_long_read(&tunnel->stats.rx_errors));
}
static void pppol2tp_seq_session_show(struct seq_file *m, void *v)
{
struct l2tp_session *session = v;
struct l2tp_tunnel *tunnel = session->tunnel;
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct pppox_sock *po = pppox_sk(ps->sock);
u32 ip = 0;
u16 port = 0;
if (tunnel->sock) {
struct inet_sock *inet = inet_sk(tunnel->sock);
ip = ntohl(inet->inet_saddr);
port = ntohs(inet->inet_sport);
}
seq_printf(m, " SESSION '%s' %08X/%d %04X/%04X -> "
"%04X/%04X %d %c\n",
session->name, ip, port,
tunnel->tunnel_id,
session->session_id,
tunnel->peer_tunnel_id,
session->peer_session_id,
ps->sock->sk_state,
(session == ps->sock->sk_user_data) ?
'Y' : 'N');
seq_printf(m, " %d/%d/%c/%c/%s %08x %u\n",
session->mtu, session->mru,
session->recv_seq ? 'R' : '-',
session->send_seq ? 'S' : '-',
session->lns_mode ? "LNS" : "LAC",
session->debug,
jiffies_to_msecs(session->reorder_timeout));
seq_printf(m, " %hu/%hu %ld/%ld/%ld %ld/%ld/%ld\n",
session->nr, session->ns,
atomic_long_read(&session->stats.tx_packets),
atomic_long_read(&session->stats.tx_bytes),
atomic_long_read(&session->stats.tx_errors),
atomic_long_read(&session->stats.rx_packets),
atomic_long_read(&session->stats.rx_bytes),
atomic_long_read(&session->stats.rx_errors));
if (po)
seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan));
}
static int pppol2tp_seq_show(struct seq_file *m, void *v)
{
struct pppol2tp_seq_data *pd = v;
/* display header on line 1 */
if (v == SEQ_START_TOKEN) {
seq_puts(m, "PPPoL2TP driver info, " PPPOL2TP_DRV_VERSION "\n");
seq_puts(m, "TUNNEL name, user-data-ok session-count\n");
seq_puts(m, " debug tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
seq_puts(m, " SESSION name, addr/port src-tid/sid "
"dest-tid/sid state user-data-ok\n");
seq_puts(m, " mtu/mru/rcvseq/sendseq/lns debug reorderto\n");
seq_puts(m, " nr/ns tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
goto out;
}
/* Show the tunnel or session context.
*/
if (pd->session == NULL)
pppol2tp_seq_tunnel_show(m, pd->tunnel);
else
pppol2tp_seq_session_show(m, pd->session);
out:
return 0;
}
static const struct seq_operations pppol2tp_seq_ops = {
.start = pppol2tp_seq_start,
.next = pppol2tp_seq_next,
.stop = pppol2tp_seq_stop,
.show = pppol2tp_seq_show,
};
/* Called when our /proc file is opened. We allocate data for use when
* iterating our tunnel / session contexts and store it in the private
* data of the seq_file.
*/
static int pppol2tp_proc_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pppol2tp_seq_ops,
sizeof(struct pppol2tp_seq_data));
}
static const struct file_operations pppol2tp_proc_fops = {
.owner = THIS_MODULE,
.open = pppol2tp_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif /* CONFIG_PROC_FS */
/*****************************************************************************
* Network namespace
*****************************************************************************/
static __net_init int pppol2tp_init_net(struct net *net)
{
struct proc_dir_entry *pde;
int err = 0;
pde = proc_create("pppol2tp", S_IRUGO, net->proc_net,
&pppol2tp_proc_fops);
if (!pde) {
err = -ENOMEM;
goto out;
}
out:
return err;
}
static __net_exit void pppol2tp_exit_net(struct net *net)
{
remove_proc_entry("pppol2tp", net->proc_net);
}
static struct pernet_operations pppol2tp_net_ops = {
.init = pppol2tp_init_net,
.exit = pppol2tp_exit_net,
.id = &pppol2tp_net_id,
};
/*****************************************************************************
* Init and cleanup
*****************************************************************************/
static const struct proto_ops pppol2tp_ops = {
.family = AF_PPPOX,
.owner = THIS_MODULE,
.release = pppol2tp_release,
.bind = sock_no_bind,
.connect = pppol2tp_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = pppol2tp_getname,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = pppol2tp_setsockopt,
.getsockopt = pppol2tp_getsockopt,
.sendmsg = pppol2tp_sendmsg,
.recvmsg = pppol2tp_recvmsg,
.mmap = sock_no_mmap,
.ioctl = pppox_ioctl,
};
static const struct pppox_proto pppol2tp_proto = {
.create = pppol2tp_create,
.ioctl = pppol2tp_ioctl,
.owner = THIS_MODULE,
};
#ifdef CONFIG_L2TP_V3
static const struct l2tp_nl_cmd_ops pppol2tp_nl_cmd_ops = {
.session_create = pppol2tp_session_create,
.session_delete = l2tp_session_delete,
};
#endif /* CONFIG_L2TP_V3 */
static int __init pppol2tp_init(void)
{
int err;
err = register_pernet_device(&pppol2tp_net_ops);
if (err)
goto out;
err = proto_register(&pppol2tp_sk_proto, 0);
if (err)
goto out_unregister_pppol2tp_pernet;
err = register_pppox_proto(PX_PROTO_OL2TP, &pppol2tp_proto);
if (err)
goto out_unregister_pppol2tp_proto;
#ifdef CONFIG_L2TP_V3
err = l2tp_nl_register_ops(L2TP_PWTYPE_PPP, &pppol2tp_nl_cmd_ops);
if (err)
goto out_unregister_pppox;
#endif
pr_info("PPPoL2TP kernel driver, %s\n", PPPOL2TP_DRV_VERSION);
out:
return err;
#ifdef CONFIG_L2TP_V3
out_unregister_pppox:
unregister_pppox_proto(PX_PROTO_OL2TP);
#endif
out_unregister_pppol2tp_proto:
proto_unregister(&pppol2tp_sk_proto);
out_unregister_pppol2tp_pernet:
unregister_pernet_device(&pppol2tp_net_ops);
goto out;
}
static void __exit pppol2tp_exit(void)
{
#ifdef CONFIG_L2TP_V3
l2tp_nl_unregister_ops(L2TP_PWTYPE_PPP);
#endif
unregister_pppox_proto(PX_PROTO_OL2TP);
proto_unregister(&pppol2tp_sk_proto);
unregister_pernet_device(&pppol2tp_net_ops);
}
module_init(pppol2tp_init);
module_exit(pppol2tp_exit);
MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
MODULE_DESCRIPTION("PPP over L2TP over UDP");
MODULE_LICENSE("GPL");
MODULE_VERSION(PPPOL2TP_DRV_VERSION);
MODULE_ALIAS("pppox-proto-" __stringify(PX_PROTO_OL2TP));
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_19 |
crossvul-cpp_data_bad_2891_1 | /* Key type used to cache DNS lookups made by the kernel
*
* See Documentation/networking/dns_resolver.txt
*
* Copyright (c) 2007 Igor Mammedov
* Author(s): Igor Mammedov (niallain@gmail.com)
* Steve French (sfrench@us.ibm.com)
* Wang Lei (wang840925@gmail.com)
* David Howells (dhowells@redhat.com)
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/keyctl.h>
#include <linux/err.h>
#include <linux/seq_file.h>
#include <keys/dns_resolver-type.h>
#include <keys/user-type.h>
#include "internal.h"
MODULE_DESCRIPTION("DNS Resolver");
MODULE_AUTHOR("Wang Lei");
MODULE_LICENSE("GPL");
unsigned int dns_resolver_debug;
module_param_named(debug, dns_resolver_debug, uint, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(debug, "DNS Resolver debugging mask");
const struct cred *dns_resolver_cache;
#define DNS_ERRORNO_OPTION "dnserror"
/*
* Preparse instantiation data for a dns_resolver key.
*
* The data must be a NUL-terminated string, with the NUL char accounted in
* datalen.
*
* If the data contains a '#' characters, then we take the clause after each
* one to be an option of the form 'key=value'. The actual data of interest is
* the string leading up to the first '#'. For instance:
*
* "ip1,ip2,...#foo=bar"
*/
static int
dns_resolver_preparse(struct key_preparsed_payload *prep)
{
struct user_key_payload *upayload;
unsigned long derrno;
int ret;
int datalen = prep->datalen, result_len = 0;
const char *data = prep->data, *end, *opt;
kenter("'%*.*s',%u", datalen, datalen, data, datalen);
if (datalen <= 1 || !data || data[datalen - 1] != '\0')
return -EINVAL;
datalen--;
/* deal with any options embedded in the data */
end = data + datalen;
opt = memchr(data, '#', datalen);
if (!opt) {
/* no options: the entire data is the result */
kdebug("no options");
result_len = datalen;
} else {
const char *next_opt;
result_len = opt - data;
opt++;
kdebug("options: '%s'", opt);
do {
const char *eq;
int opt_len, opt_nlen, opt_vlen, tmp;
next_opt = memchr(opt, '#', end - opt) ?: end;
opt_len = next_opt - opt;
if (!opt_len) {
printk(KERN_WARNING
"Empty option to dns_resolver key\n");
return -EINVAL;
}
eq = memchr(opt, '=', opt_len) ?: end;
opt_nlen = eq - opt;
eq++;
opt_vlen = next_opt - eq; /* will be -1 if no value */
tmp = opt_vlen >= 0 ? opt_vlen : 0;
kdebug("option '%*.*s' val '%*.*s'",
opt_nlen, opt_nlen, opt, tmp, tmp, eq);
/* see if it's an error number representing a DNS error
* that's to be recorded as the result in this key */
if (opt_nlen == sizeof(DNS_ERRORNO_OPTION) - 1 &&
memcmp(opt, DNS_ERRORNO_OPTION, opt_nlen) == 0) {
kdebug("dns error number option");
if (opt_vlen <= 0)
goto bad_option_value;
ret = kstrtoul(eq, 10, &derrno);
if (ret < 0)
goto bad_option_value;
if (derrno < 1 || derrno > 511)
goto bad_option_value;
kdebug("dns error no. = %lu", derrno);
prep->payload.data[dns_key_error] = ERR_PTR(-derrno);
continue;
}
bad_option_value:
printk(KERN_WARNING
"Option '%*.*s' to dns_resolver key:"
" bad/missing value\n",
opt_nlen, opt_nlen, opt);
return -EINVAL;
} while (opt = next_opt + 1, opt < end);
}
/* don't cache the result if we're caching an error saying there's no
* result */
if (prep->payload.data[dns_key_error]) {
kleave(" = 0 [h_error %ld]", PTR_ERR(prep->payload.data[dns_key_error]));
return 0;
}
kdebug("store result");
prep->quotalen = result_len;
upayload = kmalloc(sizeof(*upayload) + result_len + 1, GFP_KERNEL);
if (!upayload) {
kleave(" = -ENOMEM");
return -ENOMEM;
}
upayload->datalen = result_len;
memcpy(upayload->data, data, result_len);
upayload->data[result_len] = '\0';
prep->payload.data[dns_key_data] = upayload;
kleave(" = 0");
return 0;
}
/*
* Clean up the preparse data
*/
static void dns_resolver_free_preparse(struct key_preparsed_payload *prep)
{
pr_devel("==>%s()\n", __func__);
kfree(prep->payload.data[dns_key_data]);
}
/*
* The description is of the form "[<type>:]<domain_name>"
*
* The domain name may be a simple name or an absolute domain name (which
* should end with a period). The domain name is case-independent.
*/
static bool dns_resolver_cmp(const struct key *key,
const struct key_match_data *match_data)
{
int slen, dlen, ret = 0;
const char *src = key->description, *dsp = match_data->raw_data;
kenter("%s,%s", src, dsp);
if (!src || !dsp)
goto no_match;
if (strcasecmp(src, dsp) == 0)
goto matched;
slen = strlen(src);
dlen = strlen(dsp);
if (slen <= 0 || dlen <= 0)
goto no_match;
if (src[slen - 1] == '.')
slen--;
if (dsp[dlen - 1] == '.')
dlen--;
if (slen != dlen || strncasecmp(src, dsp, slen) != 0)
goto no_match;
matched:
ret = 1;
no_match:
kleave(" = %d", ret);
return ret;
}
/*
* Preparse the match criterion.
*/
static int dns_resolver_match_preparse(struct key_match_data *match_data)
{
match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
match_data->cmp = dns_resolver_cmp;
return 0;
}
/*
* Describe a DNS key
*/
static void dns_resolver_describe(const struct key *key, struct seq_file *m)
{
seq_puts(m, key->description);
if (key_is_instantiated(key)) {
int err = PTR_ERR(key->payload.data[dns_key_error]);
if (err)
seq_printf(m, ": %d", err);
else
seq_printf(m, ": %u", key->datalen);
}
}
/*
* read the DNS data
* - the key's semaphore is read-locked
*/
static long dns_resolver_read(const struct key *key,
char __user *buffer, size_t buflen)
{
int err = PTR_ERR(key->payload.data[dns_key_error]);
if (err)
return err;
return user_read(key, buffer, buflen);
}
struct key_type key_type_dns_resolver = {
.name = "dns_resolver",
.preparse = dns_resolver_preparse,
.free_preparse = dns_resolver_free_preparse,
.instantiate = generic_key_instantiate,
.match_preparse = dns_resolver_match_preparse,
.revoke = user_revoke,
.destroy = user_destroy,
.describe = dns_resolver_describe,
.read = dns_resolver_read,
};
static int __init init_dns_resolver(void)
{
struct cred *cred;
struct key *keyring;
int ret;
/* create an override credential set with a special thread keyring in
* which DNS requests are cached
*
* this is used to prevent malicious redirections from being installed
* with add_key().
*/
cred = prepare_kernel_cred(NULL);
if (!cred)
return -ENOMEM;
keyring = keyring_alloc(".dns_resolver",
GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, cred,
(KEY_POS_ALL & ~KEY_POS_SETATTR) |
KEY_USR_VIEW | KEY_USR_READ,
KEY_ALLOC_NOT_IN_QUOTA, NULL, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto failed_put_cred;
}
ret = register_key_type(&key_type_dns_resolver);
if (ret < 0)
goto failed_put_key;
/* instruct request_key() to use this special keyring as a cache for
* the results it looks up */
set_bit(KEY_FLAG_ROOT_CAN_CLEAR, &keyring->flags);
cred->thread_keyring = keyring;
cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING;
dns_resolver_cache = cred;
kdebug("DNS resolver keyring: %d\n", key_serial(keyring));
return 0;
failed_put_key:
key_put(keyring);
failed_put_cred:
put_cred(cred);
return ret;
}
static void __exit exit_dns_resolver(void)
{
key_revoke(dns_resolver_cache->thread_keyring);
unregister_key_type(&key_type_dns_resolver);
put_cred(dns_resolver_cache);
}
module_init(init_dns_resolver)
module_exit(exit_dns_resolver)
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_2891_1 |
crossvul-cpp_data_bad_5845_19 | /*****************************************************************************
* Linux PPP over L2TP (PPPoX/PPPoL2TP) Sockets
*
* PPPoX --- Generic PPP encapsulation socket family
* PPPoL2TP --- PPP over L2TP (RFC 2661)
*
* Version: 2.0.0
*
* Authors: James Chapman (jchapman@katalix.com)
*
* Based on original work by Martijn van Oosterhout <kleptog@svana.org>
*
* License:
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
/* This driver handles only L2TP data frames; control frames are handled by a
* userspace application.
*
* To send data in an L2TP session, userspace opens a PPPoL2TP socket and
* attaches it to a bound UDP socket with local tunnel_id / session_id and
* peer tunnel_id / session_id set. Data can then be sent or received using
* regular socket sendmsg() / recvmsg() calls. Kernel parameters of the socket
* can be read or modified using ioctl() or [gs]etsockopt() calls.
*
* When a PPPoL2TP socket is connected with local and peer session_id values
* zero, the socket is treated as a special tunnel management socket.
*
* Here's example userspace code to create a socket for sending/receiving data
* over an L2TP session:-
*
* struct sockaddr_pppol2tp sax;
* int fd;
* int session_fd;
*
* fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP);
*
* sax.sa_family = AF_PPPOX;
* sax.sa_protocol = PX_PROTO_OL2TP;
* sax.pppol2tp.fd = tunnel_fd; // bound UDP socket
* sax.pppol2tp.addr.sin_addr.s_addr = addr->sin_addr.s_addr;
* sax.pppol2tp.addr.sin_port = addr->sin_port;
* sax.pppol2tp.addr.sin_family = AF_INET;
* sax.pppol2tp.s_tunnel = tunnel_id;
* sax.pppol2tp.s_session = session_id;
* sax.pppol2tp.d_tunnel = peer_tunnel_id;
* sax.pppol2tp.d_session = peer_session_id;
*
* session_fd = connect(fd, (struct sockaddr *)&sax, sizeof(sax));
*
* A pppd plugin that allows PPP traffic to be carried over L2TP using
* this driver is available from the OpenL2TP project at
* http://openl2tp.sourceforge.net.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/uaccess.h>
#include <linux/kernel.h>
#include <linux/spinlock.h>
#include <linux/kthread.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/jiffies.h>
#include <linux/netdevice.h>
#include <linux/net.h>
#include <linux/inetdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <linux/if_pppox.h>
#include <linux/if_pppol2tp.h>
#include <net/sock.h>
#include <linux/ppp_channel.h>
#include <linux/ppp_defs.h>
#include <linux/ppp-ioctl.h>
#include <linux/file.h>
#include <linux/hash.h>
#include <linux/sort.h>
#include <linux/proc_fs.h>
#include <linux/l2tp.h>
#include <linux/nsproxy.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/dst.h>
#include <net/ip.h>
#include <net/udp.h>
#include <net/xfrm.h>
#include <net/inet_common.h>
#include <asm/byteorder.h>
#include <linux/atomic.h>
#include "l2tp_core.h"
#define PPPOL2TP_DRV_VERSION "V2.0"
/* Space for UDP, L2TP and PPP headers */
#define PPPOL2TP_HEADER_OVERHEAD 40
/* Number of bytes to build transmit L2TP headers.
* Unfortunately the size is different depending on whether sequence numbers
* are enabled.
*/
#define PPPOL2TP_L2TP_HDR_SIZE_SEQ 10
#define PPPOL2TP_L2TP_HDR_SIZE_NOSEQ 6
/* Private data of each session. This data lives at the end of struct
* l2tp_session, referenced via session->priv[].
*/
struct pppol2tp_session {
int owner; /* pid that opened the socket */
struct sock *sock; /* Pointer to the session
* PPPoX socket */
struct sock *tunnel_sock; /* Pointer to the tunnel UDP
* socket */
int flags; /* accessed by PPPIOCGFLAGS.
* Unused. */
};
static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb);
static const struct ppp_channel_ops pppol2tp_chan_ops = {
.start_xmit = pppol2tp_xmit,
};
static const struct proto_ops pppol2tp_ops;
/* Helpers to obtain tunnel/session contexts from sockets.
*/
static inline struct l2tp_session *pppol2tp_sock_to_session(struct sock *sk)
{
struct l2tp_session *session;
if (sk == NULL)
return NULL;
sock_hold(sk);
session = (struct l2tp_session *)(sk->sk_user_data);
if (session == NULL) {
sock_put(sk);
goto out;
}
BUG_ON(session->magic != L2TP_SESSION_MAGIC);
out:
return session;
}
/*****************************************************************************
* Receive data handling
*****************************************************************************/
static int pppol2tp_recv_payload_hook(struct sk_buff *skb)
{
/* Skip PPP header, if present. In testing, Microsoft L2TP clients
* don't send the PPP header (PPP header compression enabled), but
* other clients can include the header. So we cope with both cases
* here. The PPP header is always FF03 when using L2TP.
*
* Note that skb->data[] isn't dereferenced from a u16 ptr here since
* the field may be unaligned.
*/
if (!pskb_may_pull(skb, 2))
return 1;
if ((skb->data[0] == 0xff) && (skb->data[1] == 0x03))
skb_pull(skb, 2);
return 0;
}
/* Receive message. This is the recvmsg for the PPPoL2TP socket.
*/
static int pppol2tp_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
int err;
struct sk_buff *skb;
struct sock *sk = sock->sk;
err = -EIO;
if (sk->sk_state & PPPOX_BOUND)
goto end;
msg->msg_namelen = 0;
err = 0;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &err);
if (!skb)
goto end;
if (len > skb->len)
len = skb->len;
else if (len < skb->len)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, len);
if (likely(err == 0))
err = len;
kfree_skb(skb);
end:
return err;
}
static void pppol2tp_recv(struct l2tp_session *session, struct sk_buff *skb, int data_len)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct sock *sk = NULL;
/* If the socket is bound, send it in to PPP's input queue. Otherwise
* queue it on the session socket.
*/
sk = ps->sock;
if (sk == NULL)
goto no_sock;
if (sk->sk_state & PPPOX_BOUND) {
struct pppox_sock *po;
l2tp_dbg(session, PPPOL2TP_MSG_DATA,
"%s: recv %d byte data frame, passing to ppp\n",
session->name, data_len);
/* We need to forget all info related to the L2TP packet
* gathered in the skb as we are going to reuse the same
* skb for the inner packet.
* Namely we need to:
* - reset xfrm (IPSec) information as it applies to
* the outer L2TP packet and not to the inner one
* - release the dst to force a route lookup on the inner
* IP packet since skb->dst currently points to the dst
* of the UDP tunnel
* - reset netfilter information as it doesn't apply
* to the inner packet either
*/
secpath_reset(skb);
skb_dst_drop(skb);
nf_reset(skb);
po = pppox_sk(sk);
ppp_input(&po->chan, skb);
} else {
l2tp_info(session, PPPOL2TP_MSG_DATA, "%s: socket not bound\n",
session->name);
/* Not bound. Nothing we can do, so discard. */
atomic_long_inc(&session->stats.rx_errors);
kfree_skb(skb);
}
return;
no_sock:
l2tp_info(session, PPPOL2TP_MSG_DATA, "%s: no socket\n", session->name);
kfree_skb(skb);
}
static void pppol2tp_session_sock_hold(struct l2tp_session *session)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
if (ps->sock)
sock_hold(ps->sock);
}
static void pppol2tp_session_sock_put(struct l2tp_session *session)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
if (ps->sock)
sock_put(ps->sock);
}
/************************************************************************
* Transmit handling
***********************************************************************/
/* This is the sendmsg for the PPPoL2TP pppol2tp_session socket. We come here
* when a user application does a sendmsg() on the session socket. L2TP and
* PPP headers must be inserted into the user's data.
*/
static int pppol2tp_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t total_len)
{
static const unsigned char ppph[2] = { 0xff, 0x03 };
struct sock *sk = sock->sk;
struct sk_buff *skb;
int error;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int uhlen;
error = -ENOTCONN;
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto error;
/* Get session and tunnel contexts */
error = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto error;
ps = l2tp_session_priv(session);
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto error_put_sess;
uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
/* Allocate a socket buffer */
error = -ENOMEM;
skb = sock_wmalloc(sk, NET_SKB_PAD + sizeof(struct iphdr) +
uhlen + session->hdr_len +
sizeof(ppph) + total_len,
0, GFP_KERNEL);
if (!skb)
goto error_put_sess_tun;
/* Reserve space for headers. */
skb_reserve(skb, NET_SKB_PAD);
skb_reset_network_header(skb);
skb_reserve(skb, sizeof(struct iphdr));
skb_reset_transport_header(skb);
skb_reserve(skb, uhlen);
/* Add PPP header */
skb->data[0] = ppph[0];
skb->data[1] = ppph[1];
skb_put(skb, 2);
/* Copy user data into skb */
error = memcpy_fromiovec(skb_put(skb, total_len), m->msg_iov,
total_len);
if (error < 0) {
kfree_skb(skb);
goto error_put_sess_tun;
}
local_bh_disable();
l2tp_xmit_skb(session, skb, session->hdr_len);
local_bh_enable();
sock_put(ps->tunnel_sock);
sock_put(sk);
return total_len;
error_put_sess_tun:
sock_put(ps->tunnel_sock);
error_put_sess:
sock_put(sk);
error:
return error;
}
/* Transmit function called by generic PPP driver. Sends PPP frame
* over PPPoL2TP socket.
*
* This is almost the same as pppol2tp_sendmsg(), but rather than
* being called with a msghdr from userspace, it is called with a skb
* from the kernel.
*
* The supplied skb from ppp doesn't have enough headroom for the
* insertion of L2TP, UDP and IP headers so we need to allocate more
* headroom in the skb. This will create a cloned skb. But we must be
* careful in the error case because the caller will expect to free
* the skb it supplied, not our cloned skb. So we take care to always
* leave the original skb unfreed if we return an error.
*/
static int pppol2tp_xmit(struct ppp_channel *chan, struct sk_buff *skb)
{
static const u8 ppph[2] = { 0xff, 0x03 };
struct sock *sk = (struct sock *) chan->private;
struct sock *sk_tun;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int uhlen, headroom;
if (sock_flag(sk, SOCK_DEAD) || !(sk->sk_state & PPPOX_CONNECTED))
goto abort;
/* Get session and tunnel contexts from the socket */
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto abort;
ps = l2tp_session_priv(session);
sk_tun = ps->tunnel_sock;
if (sk_tun == NULL)
goto abort_put_sess;
tunnel = l2tp_sock_to_tunnel(sk_tun);
if (tunnel == NULL)
goto abort_put_sess;
uhlen = (tunnel->encap == L2TP_ENCAPTYPE_UDP) ? sizeof(struct udphdr) : 0;
headroom = NET_SKB_PAD +
sizeof(struct iphdr) + /* IP header */
uhlen + /* UDP header (if L2TP_ENCAPTYPE_UDP) */
session->hdr_len + /* L2TP header */
sizeof(ppph); /* PPP header */
if (skb_cow_head(skb, headroom))
goto abort_put_sess_tun;
/* Setup PPP header */
__skb_push(skb, sizeof(ppph));
skb->data[0] = ppph[0];
skb->data[1] = ppph[1];
local_bh_disable();
l2tp_xmit_skb(session, skb, session->hdr_len);
local_bh_enable();
sock_put(sk_tun);
sock_put(sk);
return 1;
abort_put_sess_tun:
sock_put(sk_tun);
abort_put_sess:
sock_put(sk);
abort:
/* Free the original skb */
kfree_skb(skb);
return 1;
}
/*****************************************************************************
* Session (and tunnel control) socket create/destroy.
*****************************************************************************/
/* Called by l2tp_core when a session socket is being closed.
*/
static void pppol2tp_session_close(struct l2tp_session *session)
{
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct sock *sk = ps->sock;
struct socket *sock = sk->sk_socket;
BUG_ON(session->magic != L2TP_SESSION_MAGIC);
if (sock) {
inet_shutdown(sock, 2);
/* Don't let the session go away before our socket does */
l2tp_session_inc_refcount(session);
}
return;
}
/* Really kill the session socket. (Called from sock_put() if
* refcnt == 0.)
*/
static void pppol2tp_session_destruct(struct sock *sk)
{
struct l2tp_session *session = sk->sk_user_data;
if (session) {
sk->sk_user_data = NULL;
BUG_ON(session->magic != L2TP_SESSION_MAGIC);
l2tp_session_dec_refcount(session);
}
return;
}
/* Called when the PPPoX socket (session) is closed.
*/
static int pppol2tp_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
int error;
if (!sk)
return 0;
error = -EBADF;
lock_sock(sk);
if (sock_flag(sk, SOCK_DEAD) != 0)
goto error;
pppox_unbind_sock(sk);
/* Signal the death of the socket. */
sk->sk_state = PPPOX_DEAD;
sock_orphan(sk);
sock->sk = NULL;
session = pppol2tp_sock_to_session(sk);
/* Purge any queued data */
if (session != NULL) {
__l2tp_session_unhash(session);
l2tp_session_queue_purge(session);
sock_put(sk);
}
skb_queue_purge(&sk->sk_receive_queue);
skb_queue_purge(&sk->sk_write_queue);
release_sock(sk);
/* This will delete the session context via
* pppol2tp_session_destruct() if the socket's refcnt drops to
* zero.
*/
sock_put(sk);
return 0;
error:
release_sock(sk);
return error;
}
static struct proto pppol2tp_sk_proto = {
.name = "PPPOL2TP",
.owner = THIS_MODULE,
.obj_size = sizeof(struct pppox_sock),
};
static int pppol2tp_backlog_recv(struct sock *sk, struct sk_buff *skb)
{
int rc;
rc = l2tp_udp_encap_recv(sk, skb);
if (rc)
kfree_skb(skb);
return NET_RX_SUCCESS;
}
/* socket() handler. Initialize a new struct sock.
*/
static int pppol2tp_create(struct net *net, struct socket *sock)
{
int error = -ENOMEM;
struct sock *sk;
sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pppol2tp_sk_proto);
if (!sk)
goto out;
sock_init_data(sock, sk);
sock->state = SS_UNCONNECTED;
sock->ops = &pppol2tp_ops;
sk->sk_backlog_rcv = pppol2tp_backlog_recv;
sk->sk_protocol = PX_PROTO_OL2TP;
sk->sk_family = PF_PPPOX;
sk->sk_state = PPPOX_NONE;
sk->sk_type = SOCK_STREAM;
sk->sk_destruct = pppol2tp_session_destruct;
error = 0;
out:
return error;
}
#if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE)
static void pppol2tp_show(struct seq_file *m, void *arg)
{
struct l2tp_session *session = arg;
struct pppol2tp_session *ps = l2tp_session_priv(session);
if (ps) {
struct pppox_sock *po = pppox_sk(ps->sock);
if (po)
seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan));
}
}
#endif
/* connect() handler. Attach a PPPoX socket to a tunnel UDP socket
*/
static int pppol2tp_connect(struct socket *sock, struct sockaddr *uservaddr,
int sockaddr_len, int flags)
{
struct sock *sk = sock->sk;
struct sockaddr_pppol2tp *sp = (struct sockaddr_pppol2tp *) uservaddr;
struct pppox_sock *po = pppox_sk(sk);
struct l2tp_session *session = NULL;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
struct dst_entry *dst;
struct l2tp_session_cfg cfg = { 0, };
int error = 0;
u32 tunnel_id, peer_tunnel_id;
u32 session_id, peer_session_id;
int ver = 2;
int fd;
lock_sock(sk);
error = -EINVAL;
if (sp->sa_protocol != PX_PROTO_OL2TP)
goto end;
/* Check for already bound sockets */
error = -EBUSY;
if (sk->sk_state & PPPOX_CONNECTED)
goto end;
/* We don't supporting rebinding anyway */
error = -EALREADY;
if (sk->sk_user_data)
goto end; /* socket is already attached */
/* Get params from socket address. Handle L2TPv2 and L2TPv3.
* This is nasty because there are different sockaddr_pppol2tp
* structs for L2TPv2, L2TPv3, over IPv4 and IPv6. We use
* the sockaddr size to determine which structure the caller
* is using.
*/
peer_tunnel_id = 0;
if (sockaddr_len == sizeof(struct sockaddr_pppol2tp)) {
fd = sp->pppol2tp.fd;
tunnel_id = sp->pppol2tp.s_tunnel;
peer_tunnel_id = sp->pppol2tp.d_tunnel;
session_id = sp->pppol2tp.s_session;
peer_session_id = sp->pppol2tp.d_session;
} else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpv3)) {
struct sockaddr_pppol2tpv3 *sp3 =
(struct sockaddr_pppol2tpv3 *) sp;
ver = 3;
fd = sp3->pppol2tp.fd;
tunnel_id = sp3->pppol2tp.s_tunnel;
peer_tunnel_id = sp3->pppol2tp.d_tunnel;
session_id = sp3->pppol2tp.s_session;
peer_session_id = sp3->pppol2tp.d_session;
} else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpin6)) {
struct sockaddr_pppol2tpin6 *sp6 =
(struct sockaddr_pppol2tpin6 *) sp;
fd = sp6->pppol2tp.fd;
tunnel_id = sp6->pppol2tp.s_tunnel;
peer_tunnel_id = sp6->pppol2tp.d_tunnel;
session_id = sp6->pppol2tp.s_session;
peer_session_id = sp6->pppol2tp.d_session;
} else if (sockaddr_len == sizeof(struct sockaddr_pppol2tpv3in6)) {
struct sockaddr_pppol2tpv3in6 *sp6 =
(struct sockaddr_pppol2tpv3in6 *) sp;
ver = 3;
fd = sp6->pppol2tp.fd;
tunnel_id = sp6->pppol2tp.s_tunnel;
peer_tunnel_id = sp6->pppol2tp.d_tunnel;
session_id = sp6->pppol2tp.s_session;
peer_session_id = sp6->pppol2tp.d_session;
} else {
error = -EINVAL;
goto end; /* bad socket address */
}
/* Don't bind if tunnel_id is 0 */
error = -EINVAL;
if (tunnel_id == 0)
goto end;
tunnel = l2tp_tunnel_find(sock_net(sk), tunnel_id);
/* Special case: create tunnel context if session_id and
* peer_session_id is 0. Otherwise look up tunnel using supplied
* tunnel id.
*/
if ((session_id == 0) && (peer_session_id == 0)) {
if (tunnel == NULL) {
struct l2tp_tunnel_cfg tcfg = {
.encap = L2TP_ENCAPTYPE_UDP,
.debug = 0,
};
error = l2tp_tunnel_create(sock_net(sk), fd, ver, tunnel_id, peer_tunnel_id, &tcfg, &tunnel);
if (error < 0)
goto end;
}
} else {
/* Error if we can't find the tunnel */
error = -ENOENT;
if (tunnel == NULL)
goto end;
/* Error if socket is not prepped */
if (tunnel->sock == NULL)
goto end;
}
if (tunnel->recv_payload_hook == NULL)
tunnel->recv_payload_hook = pppol2tp_recv_payload_hook;
if (tunnel->peer_tunnel_id == 0)
tunnel->peer_tunnel_id = peer_tunnel_id;
/* Create session if it doesn't already exist. We handle the
* case where a session was previously created by the netlink
* interface by checking that the session doesn't already have
* a socket and its tunnel socket are what we expect. If any
* of those checks fail, return EEXIST to the caller.
*/
session = l2tp_session_find(sock_net(sk), tunnel, session_id);
if (session == NULL) {
/* Default MTU must allow space for UDP/L2TP/PPP
* headers.
*/
cfg.mtu = cfg.mru = 1500 - PPPOL2TP_HEADER_OVERHEAD;
/* Allocate and initialize a new session context. */
session = l2tp_session_create(sizeof(struct pppol2tp_session),
tunnel, session_id,
peer_session_id, &cfg);
if (session == NULL) {
error = -ENOMEM;
goto end;
}
} else {
ps = l2tp_session_priv(session);
error = -EEXIST;
if (ps->sock != NULL)
goto end;
/* consistency checks */
if (ps->tunnel_sock != tunnel->sock)
goto end;
}
/* Associate session with its PPPoL2TP socket */
ps = l2tp_session_priv(session);
ps->owner = current->pid;
ps->sock = sk;
ps->tunnel_sock = tunnel->sock;
session->recv_skb = pppol2tp_recv;
session->session_close = pppol2tp_session_close;
#if defined(CONFIG_L2TP_DEBUGFS) || defined(CONFIG_L2TP_DEBUGFS_MODULE)
session->show = pppol2tp_show;
#endif
/* We need to know each time a skb is dropped from the reorder
* queue.
*/
session->ref = pppol2tp_session_sock_hold;
session->deref = pppol2tp_session_sock_put;
/* If PMTU discovery was enabled, use the MTU that was discovered */
dst = sk_dst_get(sk);
if (dst != NULL) {
u32 pmtu = dst_mtu(__sk_dst_get(sk));
if (pmtu != 0)
session->mtu = session->mru = pmtu -
PPPOL2TP_HEADER_OVERHEAD;
dst_release(dst);
}
/* Special case: if source & dest session_id == 0x0000, this
* socket is being created to manage the tunnel. Just set up
* the internal context for use by ioctl() and sockopt()
* handlers.
*/
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
error = 0;
goto out_no_ppp;
}
/* The only header we need to worry about is the L2TP
* header. This size is different depending on whether
* sequence numbers are enabled for the data channel.
*/
po->chan.hdrlen = PPPOL2TP_L2TP_HDR_SIZE_NOSEQ;
po->chan.private = sk;
po->chan.ops = &pppol2tp_chan_ops;
po->chan.mtu = session->mtu;
error = ppp_register_net_channel(sock_net(sk), &po->chan);
if (error)
goto end;
out_no_ppp:
/* This is how we get the session context from the socket. */
sk->sk_user_data = session;
sk->sk_state = PPPOX_CONNECTED;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: created\n",
session->name);
end:
release_sock(sk);
return error;
}
#ifdef CONFIG_L2TP_V3
/* Called when creating sessions via the netlink interface.
*/
static int pppol2tp_session_create(struct net *net, u32 tunnel_id, u32 session_id, u32 peer_session_id, struct l2tp_session_cfg *cfg)
{
int error;
struct l2tp_tunnel *tunnel;
struct l2tp_session *session;
struct pppol2tp_session *ps;
tunnel = l2tp_tunnel_find(net, tunnel_id);
/* Error if we can't find the tunnel */
error = -ENOENT;
if (tunnel == NULL)
goto out;
/* Error if tunnel socket is not prepped */
if (tunnel->sock == NULL)
goto out;
/* Check that this session doesn't already exist */
error = -EEXIST;
session = l2tp_session_find(net, tunnel, session_id);
if (session != NULL)
goto out;
/* Default MTU values. */
if (cfg->mtu == 0)
cfg->mtu = 1500 - PPPOL2TP_HEADER_OVERHEAD;
if (cfg->mru == 0)
cfg->mru = cfg->mtu;
/* Allocate and initialize a new session context. */
error = -ENOMEM;
session = l2tp_session_create(sizeof(struct pppol2tp_session),
tunnel, session_id,
peer_session_id, cfg);
if (session == NULL)
goto out;
ps = l2tp_session_priv(session);
ps->tunnel_sock = tunnel->sock;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: created\n",
session->name);
error = 0;
out:
return error;
}
#endif /* CONFIG_L2TP_V3 */
/* getname() support.
*/
static int pppol2tp_getname(struct socket *sock, struct sockaddr *uaddr,
int *usockaddr_len, int peer)
{
int len = 0;
int error = 0;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct sock *sk = sock->sk;
struct inet_sock *inet;
struct pppol2tp_session *pls;
error = -ENOTCONN;
if (sk == NULL)
goto end;
if (sk->sk_state != PPPOX_CONNECTED)
goto end;
error = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
pls = l2tp_session_priv(session);
tunnel = l2tp_sock_to_tunnel(pls->tunnel_sock);
if (tunnel == NULL) {
error = -EBADF;
goto end_put_sess;
}
inet = inet_sk(tunnel->sock);
if ((tunnel->version == 2) && (tunnel->sock->sk_family == AF_INET)) {
struct sockaddr_pppol2tp sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin_family = AF_INET;
sp.pppol2tp.addr.sin_port = inet->inet_dport;
sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr;
memcpy(uaddr, &sp, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if ((tunnel->version == 2) &&
(tunnel->sock->sk_family == AF_INET6)) {
struct sockaddr_pppol2tpin6 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin6_family = AF_INET6;
sp.pppol2tp.addr.sin6_port = inet->inet_dport;
memcpy(&sp.pppol2tp.addr.sin6_addr, &tunnel->sock->sk_v6_daddr,
sizeof(tunnel->sock->sk_v6_daddr));
memcpy(uaddr, &sp, len);
} else if ((tunnel->version == 3) &&
(tunnel->sock->sk_family == AF_INET6)) {
struct sockaddr_pppol2tpv3in6 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin6_family = AF_INET6;
sp.pppol2tp.addr.sin6_port = inet->inet_dport;
memcpy(&sp.pppol2tp.addr.sin6_addr, &tunnel->sock->sk_v6_daddr,
sizeof(tunnel->sock->sk_v6_daddr));
memcpy(uaddr, &sp, len);
#endif
} else if (tunnel->version == 3) {
struct sockaddr_pppol2tpv3 sp;
len = sizeof(sp);
memset(&sp, 0, len);
sp.sa_family = AF_PPPOX;
sp.sa_protocol = PX_PROTO_OL2TP;
sp.pppol2tp.fd = tunnel->fd;
sp.pppol2tp.pid = pls->owner;
sp.pppol2tp.s_tunnel = tunnel->tunnel_id;
sp.pppol2tp.d_tunnel = tunnel->peer_tunnel_id;
sp.pppol2tp.s_session = session->session_id;
sp.pppol2tp.d_session = session->peer_session_id;
sp.pppol2tp.addr.sin_family = AF_INET;
sp.pppol2tp.addr.sin_port = inet->inet_dport;
sp.pppol2tp.addr.sin_addr.s_addr = inet->inet_daddr;
memcpy(uaddr, &sp, len);
}
*usockaddr_len = len;
sock_put(pls->tunnel_sock);
end_put_sess:
sock_put(sk);
error = 0;
end:
return error;
}
/****************************************************************************
* ioctl() handlers.
*
* The PPPoX socket is created for L2TP sessions: tunnels have their own UDP
* sockets. However, in order to control kernel tunnel features, we allow
* userspace to create a special "tunnel" PPPoX socket which is used for
* control only. Tunnel PPPoX sockets have session_id == 0 and simply allow
* the user application to issue L2TP setsockopt(), getsockopt() and ioctl()
* calls.
****************************************************************************/
static void pppol2tp_copy_stats(struct pppol2tp_ioc_stats *dest,
struct l2tp_stats *stats)
{
dest->tx_packets = atomic_long_read(&stats->tx_packets);
dest->tx_bytes = atomic_long_read(&stats->tx_bytes);
dest->tx_errors = atomic_long_read(&stats->tx_errors);
dest->rx_packets = atomic_long_read(&stats->rx_packets);
dest->rx_bytes = atomic_long_read(&stats->rx_bytes);
dest->rx_seq_discards = atomic_long_read(&stats->rx_seq_discards);
dest->rx_oos_packets = atomic_long_read(&stats->rx_oos_packets);
dest->rx_errors = atomic_long_read(&stats->rx_errors);
}
/* Session ioctl helper.
*/
static int pppol2tp_session_ioctl(struct l2tp_session *session,
unsigned int cmd, unsigned long arg)
{
struct ifreq ifr;
int err = 0;
struct sock *sk;
int val = (int) arg;
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct l2tp_tunnel *tunnel = session->tunnel;
struct pppol2tp_ioc_stats stats;
l2tp_dbg(session, PPPOL2TP_MSG_CONTROL,
"%s: pppol2tp_session_ioctl(cmd=%#x, arg=%#lx)\n",
session->name, cmd, arg);
sk = ps->sock;
sock_hold(sk);
switch (cmd) {
case SIOCGIFMTU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (copy_from_user(&ifr, (void __user *) arg, sizeof(struct ifreq)))
break;
ifr.ifr_mtu = session->mtu;
if (copy_to_user((void __user *) arg, &ifr, sizeof(struct ifreq)))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get mtu=%d\n",
session->name, session->mtu);
err = 0;
break;
case SIOCSIFMTU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (copy_from_user(&ifr, (void __user *) arg, sizeof(struct ifreq)))
break;
session->mtu = ifr.ifr_mtu;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set mtu=%d\n",
session->name, session->mtu);
err = 0;
break;
case PPPIOCGMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (put_user(session->mru, (int __user *) arg))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get mru=%d\n",
session->name, session->mru);
err = 0;
break;
case PPPIOCSMRU:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
err = -EFAULT;
if (get_user(val, (int __user *) arg))
break;
session->mru = val;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set mru=%d\n",
session->name, session->mru);
err = 0;
break;
case PPPIOCGFLAGS:
err = -EFAULT;
if (put_user(ps->flags, (int __user *) arg))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get flags=%d\n",
session->name, ps->flags);
err = 0;
break;
case PPPIOCSFLAGS:
err = -EFAULT;
if (get_user(val, (int __user *) arg))
break;
ps->flags = val;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set flags=%d\n",
session->name, ps->flags);
err = 0;
break;
case PPPIOCGL2TPSTATS:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
memset(&stats, 0, sizeof(stats));
stats.tunnel_id = tunnel->tunnel_id;
stats.session_id = session->session_id;
pppol2tp_copy_stats(&stats, &session->stats);
if (copy_to_user((void __user *) arg, &stats,
sizeof(stats)))
break;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get L2TP stats\n",
session->name);
err = 0;
break;
default:
err = -ENOSYS;
break;
}
sock_put(sk);
return err;
}
/* Tunnel ioctl helper.
*
* Note the special handling for PPPIOCGL2TPSTATS below. If the ioctl data
* specifies a session_id, the session ioctl handler is called. This allows an
* application to retrieve session stats via a tunnel socket.
*/
static int pppol2tp_tunnel_ioctl(struct l2tp_tunnel *tunnel,
unsigned int cmd, unsigned long arg)
{
int err = 0;
struct sock *sk;
struct pppol2tp_ioc_stats stats;
l2tp_dbg(tunnel, PPPOL2TP_MSG_CONTROL,
"%s: pppol2tp_tunnel_ioctl(cmd=%#x, arg=%#lx)\n",
tunnel->name, cmd, arg);
sk = tunnel->sock;
sock_hold(sk);
switch (cmd) {
case PPPIOCGL2TPSTATS:
err = -ENXIO;
if (!(sk->sk_state & PPPOX_CONNECTED))
break;
if (copy_from_user(&stats, (void __user *) arg,
sizeof(stats))) {
err = -EFAULT;
break;
}
if (stats.session_id != 0) {
/* resend to session ioctl handler */
struct l2tp_session *session =
l2tp_session_find(sock_net(sk), tunnel, stats.session_id);
if (session != NULL)
err = pppol2tp_session_ioctl(session, cmd, arg);
else
err = -EBADR;
break;
}
#ifdef CONFIG_XFRM
stats.using_ipsec = (sk->sk_policy[0] || sk->sk_policy[1]) ? 1 : 0;
#endif
pppol2tp_copy_stats(&stats, &tunnel->stats);
if (copy_to_user((void __user *) arg, &stats, sizeof(stats))) {
err = -EFAULT;
break;
}
l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: get L2TP stats\n",
tunnel->name);
err = 0;
break;
default:
err = -ENOSYS;
break;
}
sock_put(sk);
return err;
}
/* Main ioctl() handler.
* Dispatch to tunnel or session helpers depending on the socket.
*/
static int pppol2tp_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int err;
if (!sk)
return 0;
err = -EBADF;
if (sock_flag(sk, SOCK_DEAD) != 0)
goto end;
err = -ENOTCONN;
if ((sk->sk_user_data == NULL) ||
(!(sk->sk_state & (PPPOX_CONNECTED | PPPOX_BOUND))))
goto end;
/* Get session context from the socket */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
/* Special case: if session's session_id is zero, treat ioctl as a
* tunnel ioctl
*/
ps = l2tp_session_priv(session);
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
err = -EBADF;
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto end_put_sess;
err = pppol2tp_tunnel_ioctl(tunnel, cmd, arg);
sock_put(ps->tunnel_sock);
goto end_put_sess;
}
err = pppol2tp_session_ioctl(session, cmd, arg);
end_put_sess:
sock_put(sk);
end:
return err;
}
/*****************************************************************************
* setsockopt() / getsockopt() support.
*
* The PPPoX socket is created for L2TP sessions: tunnels have their own UDP
* sockets. In order to control kernel tunnel features, we allow userspace to
* create a special "tunnel" PPPoX socket which is used for control only.
* Tunnel PPPoX sockets have session_id == 0 and simply allow the user
* application to issue L2TP setsockopt(), getsockopt() and ioctl() calls.
*****************************************************************************/
/* Tunnel setsockopt() helper.
*/
static int pppol2tp_tunnel_setsockopt(struct sock *sk,
struct l2tp_tunnel *tunnel,
int optname, int val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_DEBUG:
tunnel->debug = val;
l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: set debug=%x\n",
tunnel->name, tunnel->debug);
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Session setsockopt helper.
*/
static int pppol2tp_session_setsockopt(struct sock *sk,
struct l2tp_session *session,
int optname, int val)
{
int err = 0;
struct pppol2tp_session *ps = l2tp_session_priv(session);
switch (optname) {
case PPPOL2TP_SO_RECVSEQ:
if ((val != 0) && (val != 1)) {
err = -EINVAL;
break;
}
session->recv_seq = val ? -1 : 0;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set recv_seq=%d\n",
session->name, session->recv_seq);
break;
case PPPOL2TP_SO_SENDSEQ:
if ((val != 0) && (val != 1)) {
err = -EINVAL;
break;
}
session->send_seq = val ? -1 : 0;
{
struct sock *ssk = ps->sock;
struct pppox_sock *po = pppox_sk(ssk);
po->chan.hdrlen = val ? PPPOL2TP_L2TP_HDR_SIZE_SEQ :
PPPOL2TP_L2TP_HDR_SIZE_NOSEQ;
}
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set send_seq=%d\n",
session->name, session->send_seq);
break;
case PPPOL2TP_SO_LNSMODE:
if ((val != 0) && (val != 1)) {
err = -EINVAL;
break;
}
session->lns_mode = val ? -1 : 0;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set lns_mode=%d\n",
session->name, session->lns_mode);
break;
case PPPOL2TP_SO_DEBUG:
session->debug = val;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: set debug=%x\n",
session->name, session->debug);
break;
case PPPOL2TP_SO_REORDERTO:
session->reorder_timeout = msecs_to_jiffies(val);
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: set reorder_timeout=%d\n",
session->name, session->reorder_timeout);
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Main setsockopt() entry point.
* Does API checks, then calls either the tunnel or session setsockopt
* handler, according to whether the PPPoL2TP socket is a for a regular
* session or the special tunnel type.
*/
static int pppol2tp_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
struct pppol2tp_session *ps;
int val;
int err;
if (level != SOL_PPPOL2TP)
return udp_prot.setsockopt(sk, level, optname, optval, optlen);
if (optlen < sizeof(int))
return -EINVAL;
if (get_user(val, (int __user *)optval))
return -EFAULT;
err = -ENOTCONN;
if (sk->sk_user_data == NULL)
goto end;
/* Get session context from the socket */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
/* Special case: if session_id == 0x0000, treat as operation on tunnel
*/
ps = l2tp_session_priv(session);
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
err = -EBADF;
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto end_put_sess;
err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val);
sock_put(ps->tunnel_sock);
} else
err = pppol2tp_session_setsockopt(sk, session, optname, val);
err = 0;
end_put_sess:
sock_put(sk);
end:
return err;
}
/* Tunnel getsockopt helper. Called with sock locked.
*/
static int pppol2tp_tunnel_getsockopt(struct sock *sk,
struct l2tp_tunnel *tunnel,
int optname, int *val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_DEBUG:
*val = tunnel->debug;
l2tp_info(tunnel, PPPOL2TP_MSG_CONTROL, "%s: get debug=%x\n",
tunnel->name, tunnel->debug);
break;
default:
err = -ENOPROTOOPT;
break;
}
return err;
}
/* Session getsockopt helper. Called with sock locked.
*/
static int pppol2tp_session_getsockopt(struct sock *sk,
struct l2tp_session *session,
int optname, int *val)
{
int err = 0;
switch (optname) {
case PPPOL2TP_SO_RECVSEQ:
*val = session->recv_seq;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get recv_seq=%d\n", session->name, *val);
break;
case PPPOL2TP_SO_SENDSEQ:
*val = session->send_seq;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get send_seq=%d\n", session->name, *val);
break;
case PPPOL2TP_SO_LNSMODE:
*val = session->lns_mode;
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get lns_mode=%d\n", session->name, *val);
break;
case PPPOL2TP_SO_DEBUG:
*val = session->debug;
l2tp_info(session, PPPOL2TP_MSG_CONTROL, "%s: get debug=%d\n",
session->name, *val);
break;
case PPPOL2TP_SO_REORDERTO:
*val = (int) jiffies_to_msecs(session->reorder_timeout);
l2tp_info(session, PPPOL2TP_MSG_CONTROL,
"%s: get reorder_timeout=%d\n", session->name, *val);
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
/* Main getsockopt() entry point.
* Does API checks, then calls either the tunnel or session getsockopt
* handler, according to whether the PPPoX socket is a for a regular session
* or the special tunnel type.
*/
static int pppol2tp_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel;
int val, len;
int err;
struct pppol2tp_session *ps;
if (level != SOL_PPPOL2TP)
return udp_prot.getsockopt(sk, level, optname, optval, optlen);
if (get_user(len, optlen))
return -EFAULT;
len = min_t(unsigned int, len, sizeof(int));
if (len < 0)
return -EINVAL;
err = -ENOTCONN;
if (sk->sk_user_data == NULL)
goto end;
/* Get the session context */
err = -EBADF;
session = pppol2tp_sock_to_session(sk);
if (session == NULL)
goto end;
/* Special case: if session_id == 0x0000, treat as operation on tunnel */
ps = l2tp_session_priv(session);
if ((session->session_id == 0) &&
(session->peer_session_id == 0)) {
err = -EBADF;
tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock);
if (tunnel == NULL)
goto end_put_sess;
err = pppol2tp_tunnel_getsockopt(sk, tunnel, optname, &val);
sock_put(ps->tunnel_sock);
} else
err = pppol2tp_session_getsockopt(sk, session, optname, &val);
err = -EFAULT;
if (put_user(len, optlen))
goto end_put_sess;
if (copy_to_user((void __user *) optval, &val, len))
goto end_put_sess;
err = 0;
end_put_sess:
sock_put(sk);
end:
return err;
}
/*****************************************************************************
* /proc filesystem for debug
* Since the original pppol2tp driver provided /proc/net/pppol2tp for
* L2TPv2, we dump only L2TPv2 tunnels and sessions here.
*****************************************************************************/
static unsigned int pppol2tp_net_id;
#ifdef CONFIG_PROC_FS
struct pppol2tp_seq_data {
struct seq_net_private p;
int tunnel_idx; /* current tunnel */
int session_idx; /* index of session within current tunnel */
struct l2tp_tunnel *tunnel;
struct l2tp_session *session; /* NULL means get next tunnel */
};
static void pppol2tp_next_tunnel(struct net *net, struct pppol2tp_seq_data *pd)
{
for (;;) {
pd->tunnel = l2tp_tunnel_find_nth(net, pd->tunnel_idx);
pd->tunnel_idx++;
if (pd->tunnel == NULL)
break;
/* Ignore L2TPv3 tunnels */
if (pd->tunnel->version < 3)
break;
}
}
static void pppol2tp_next_session(struct net *net, struct pppol2tp_seq_data *pd)
{
pd->session = l2tp_session_find_nth(pd->tunnel, pd->session_idx);
pd->session_idx++;
if (pd->session == NULL) {
pd->session_idx = 0;
pppol2tp_next_tunnel(net, pd);
}
}
static void *pppol2tp_seq_start(struct seq_file *m, loff_t *offs)
{
struct pppol2tp_seq_data *pd = SEQ_START_TOKEN;
loff_t pos = *offs;
struct net *net;
if (!pos)
goto out;
BUG_ON(m->private == NULL);
pd = m->private;
net = seq_file_net(m);
if (pd->tunnel == NULL)
pppol2tp_next_tunnel(net, pd);
else
pppol2tp_next_session(net, pd);
/* NULL tunnel and session indicates end of list */
if ((pd->tunnel == NULL) && (pd->session == NULL))
pd = NULL;
out:
return pd;
}
static void *pppol2tp_seq_next(struct seq_file *m, void *v, loff_t *pos)
{
(*pos)++;
return NULL;
}
static void pppol2tp_seq_stop(struct seq_file *p, void *v)
{
/* nothing to do */
}
static void pppol2tp_seq_tunnel_show(struct seq_file *m, void *v)
{
struct l2tp_tunnel *tunnel = v;
seq_printf(m, "\nTUNNEL '%s', %c %d\n",
tunnel->name,
(tunnel == tunnel->sock->sk_user_data) ? 'Y' : 'N',
atomic_read(&tunnel->ref_count) - 1);
seq_printf(m, " %08x %ld/%ld/%ld %ld/%ld/%ld\n",
tunnel->debug,
atomic_long_read(&tunnel->stats.tx_packets),
atomic_long_read(&tunnel->stats.tx_bytes),
atomic_long_read(&tunnel->stats.tx_errors),
atomic_long_read(&tunnel->stats.rx_packets),
atomic_long_read(&tunnel->stats.rx_bytes),
atomic_long_read(&tunnel->stats.rx_errors));
}
static void pppol2tp_seq_session_show(struct seq_file *m, void *v)
{
struct l2tp_session *session = v;
struct l2tp_tunnel *tunnel = session->tunnel;
struct pppol2tp_session *ps = l2tp_session_priv(session);
struct pppox_sock *po = pppox_sk(ps->sock);
u32 ip = 0;
u16 port = 0;
if (tunnel->sock) {
struct inet_sock *inet = inet_sk(tunnel->sock);
ip = ntohl(inet->inet_saddr);
port = ntohs(inet->inet_sport);
}
seq_printf(m, " SESSION '%s' %08X/%d %04X/%04X -> "
"%04X/%04X %d %c\n",
session->name, ip, port,
tunnel->tunnel_id,
session->session_id,
tunnel->peer_tunnel_id,
session->peer_session_id,
ps->sock->sk_state,
(session == ps->sock->sk_user_data) ?
'Y' : 'N');
seq_printf(m, " %d/%d/%c/%c/%s %08x %u\n",
session->mtu, session->mru,
session->recv_seq ? 'R' : '-',
session->send_seq ? 'S' : '-',
session->lns_mode ? "LNS" : "LAC",
session->debug,
jiffies_to_msecs(session->reorder_timeout));
seq_printf(m, " %hu/%hu %ld/%ld/%ld %ld/%ld/%ld\n",
session->nr, session->ns,
atomic_long_read(&session->stats.tx_packets),
atomic_long_read(&session->stats.tx_bytes),
atomic_long_read(&session->stats.tx_errors),
atomic_long_read(&session->stats.rx_packets),
atomic_long_read(&session->stats.rx_bytes),
atomic_long_read(&session->stats.rx_errors));
if (po)
seq_printf(m, " interface %s\n", ppp_dev_name(&po->chan));
}
static int pppol2tp_seq_show(struct seq_file *m, void *v)
{
struct pppol2tp_seq_data *pd = v;
/* display header on line 1 */
if (v == SEQ_START_TOKEN) {
seq_puts(m, "PPPoL2TP driver info, " PPPOL2TP_DRV_VERSION "\n");
seq_puts(m, "TUNNEL name, user-data-ok session-count\n");
seq_puts(m, " debug tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
seq_puts(m, " SESSION name, addr/port src-tid/sid "
"dest-tid/sid state user-data-ok\n");
seq_puts(m, " mtu/mru/rcvseq/sendseq/lns debug reorderto\n");
seq_puts(m, " nr/ns tx-pkts/bytes/errs rx-pkts/bytes/errs\n");
goto out;
}
/* Show the tunnel or session context.
*/
if (pd->session == NULL)
pppol2tp_seq_tunnel_show(m, pd->tunnel);
else
pppol2tp_seq_session_show(m, pd->session);
out:
return 0;
}
static const struct seq_operations pppol2tp_seq_ops = {
.start = pppol2tp_seq_start,
.next = pppol2tp_seq_next,
.stop = pppol2tp_seq_stop,
.show = pppol2tp_seq_show,
};
/* Called when our /proc file is opened. We allocate data for use when
* iterating our tunnel / session contexts and store it in the private
* data of the seq_file.
*/
static int pppol2tp_proc_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &pppol2tp_seq_ops,
sizeof(struct pppol2tp_seq_data));
}
static const struct file_operations pppol2tp_proc_fops = {
.owner = THIS_MODULE,
.open = pppol2tp_proc_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif /* CONFIG_PROC_FS */
/*****************************************************************************
* Network namespace
*****************************************************************************/
static __net_init int pppol2tp_init_net(struct net *net)
{
struct proc_dir_entry *pde;
int err = 0;
pde = proc_create("pppol2tp", S_IRUGO, net->proc_net,
&pppol2tp_proc_fops);
if (!pde) {
err = -ENOMEM;
goto out;
}
out:
return err;
}
static __net_exit void pppol2tp_exit_net(struct net *net)
{
remove_proc_entry("pppol2tp", net->proc_net);
}
static struct pernet_operations pppol2tp_net_ops = {
.init = pppol2tp_init_net,
.exit = pppol2tp_exit_net,
.id = &pppol2tp_net_id,
};
/*****************************************************************************
* Init and cleanup
*****************************************************************************/
static const struct proto_ops pppol2tp_ops = {
.family = AF_PPPOX,
.owner = THIS_MODULE,
.release = pppol2tp_release,
.bind = sock_no_bind,
.connect = pppol2tp_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = pppol2tp_getname,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = pppol2tp_setsockopt,
.getsockopt = pppol2tp_getsockopt,
.sendmsg = pppol2tp_sendmsg,
.recvmsg = pppol2tp_recvmsg,
.mmap = sock_no_mmap,
.ioctl = pppox_ioctl,
};
static const struct pppox_proto pppol2tp_proto = {
.create = pppol2tp_create,
.ioctl = pppol2tp_ioctl,
.owner = THIS_MODULE,
};
#ifdef CONFIG_L2TP_V3
static const struct l2tp_nl_cmd_ops pppol2tp_nl_cmd_ops = {
.session_create = pppol2tp_session_create,
.session_delete = l2tp_session_delete,
};
#endif /* CONFIG_L2TP_V3 */
static int __init pppol2tp_init(void)
{
int err;
err = register_pernet_device(&pppol2tp_net_ops);
if (err)
goto out;
err = proto_register(&pppol2tp_sk_proto, 0);
if (err)
goto out_unregister_pppol2tp_pernet;
err = register_pppox_proto(PX_PROTO_OL2TP, &pppol2tp_proto);
if (err)
goto out_unregister_pppol2tp_proto;
#ifdef CONFIG_L2TP_V3
err = l2tp_nl_register_ops(L2TP_PWTYPE_PPP, &pppol2tp_nl_cmd_ops);
if (err)
goto out_unregister_pppox;
#endif
pr_info("PPPoL2TP kernel driver, %s\n", PPPOL2TP_DRV_VERSION);
out:
return err;
#ifdef CONFIG_L2TP_V3
out_unregister_pppox:
unregister_pppox_proto(PX_PROTO_OL2TP);
#endif
out_unregister_pppol2tp_proto:
proto_unregister(&pppol2tp_sk_proto);
out_unregister_pppol2tp_pernet:
unregister_pernet_device(&pppol2tp_net_ops);
goto out;
}
static void __exit pppol2tp_exit(void)
{
#ifdef CONFIG_L2TP_V3
l2tp_nl_unregister_ops(L2TP_PWTYPE_PPP);
#endif
unregister_pppox_proto(PX_PROTO_OL2TP);
proto_unregister(&pppol2tp_sk_proto);
unregister_pernet_device(&pppol2tp_net_ops);
}
module_init(pppol2tp_init);
module_exit(pppol2tp_exit);
MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
MODULE_DESCRIPTION("PPP over L2TP over UDP");
MODULE_LICENSE("GPL");
MODULE_VERSION(PPPOL2TP_DRV_VERSION);
MODULE_ALIAS("pppox-proto-" __stringify(PX_PROTO_OL2TP));
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_19 |
crossvul-cpp_data_bad_364_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% CCCC AAA L SSSSS %
% C A A L SS %
% C AAAAA L SSS %
% C A A L SS %
% CCCC A A LLLLL SSSSS %
% %
% %
% Read/Write CALS Raster Group 1 Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% The CALS raster format is a standard developed by the Computer Aided
% Acquisition and Logistics Support (CALS) office of the United States
% Department of Defense to standardize graphics data interchange for
% electronic publishing, especially in the areas of technical graphics,
% CAD/CAM, and image processing applications.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
Forward declarations.
*/
static MagickBooleanType
WriteCALSImage(const ImageInfo *,Image *,ExceptionInfo *);
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s C A L S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsCALS() returns MagickTrue if the image format type, identified by the
% magick string, is CALS Raster Group 1.
%
% The format of the IsCALS method is:
%
% MagickBooleanType IsCALS(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsCALS(const unsigned char *magick,const size_t length)
{
if (length < 128)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"version: MIL-STD-1840",21) == 0)
return(MagickTrue);
if (LocaleNCompare((const char *) magick,"srcdocid:",9) == 0)
return(MagickTrue);
if (LocaleNCompare((const char *) magick,"rorient:",8) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C A L S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadCALSImage() reads an CALS Raster Group 1 image format image file and
% returns it. It allocates the memory necessary for the new Image structure
% and returns a pointer to the new image.
%
% The format of the ReadCALSImage method is:
%
% Image *ReadCALSImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadCALSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
header[MagickPathExtent],
message[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register ssize_t
i;
unsigned long
density,
direction,
height,
orientation,
pel_path,
type,
width;
/*
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 CALS header.
*/
(void) memset(header,0,sizeof(header));
density=0;
direction=0;
orientation=1;
pel_path=0;
type=1;
width=0;
height=0;
for (i=0; i < 16; i++)
{
if (ReadBlob(image,128,(unsigned char *) header) != 128)
break;
switch (*header)
{
case 'R':
case 'r':
{
if (LocaleNCompare(header,"rdensty:",8) == 0)
{
(void) sscanf(header+8,"%lu",&density);
break;
}
if (LocaleNCompare(header,"rpelcnt:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&width,&height);
break;
}
if (LocaleNCompare(header,"rorient:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&pel_path,&direction);
if (pel_path == 90)
orientation=5;
else
if (pel_path == 180)
orientation=3;
else
if (pel_path == 270)
orientation=7;
if (direction == 90)
orientation++;
break;
}
if (LocaleNCompare(header,"rtype:",6) == 0)
{
(void) sscanf(header+6,"%lu",&type);
break;
}
break;
}
}
}
/*
Read CALS pixels.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
while ((c=ReadBlobByte(image)) != EOF)
(void) fputc(c,file);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"group4:%s",
filename);
(void) FormatLocaleString(message,MagickPathExtent,"%lux%lu",width,height);
(void) CloneString(&read_info->size,message);
(void) FormatLocaleString(message,MagickPathExtent,"%lu",density);
(void) CloneString(&read_info->density,message);
read_info->orientation=(OrientationType) orientation;
image=ReadImage(read_info,exception);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"CALS",MagickPathExtent);
}
read_info=DestroyImageInfo(read_info);
(void) RelinquishUniqueFileResource(filename);
return(image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r C A L S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterCALSImage() adds attributes for the CALS Raster Group 1 image file
% image format to the list of supported formats. The attributes include the
% image format tag, a method to read and/or write the format, whether the
% format supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief description
% of the format.
%
% The format of the RegisterCALSImage method is:
%
% size_t RegisterCALSImage(void)
%
*/
ModuleExport size_t RegisterCALSImage(void)
{
#define CALSDescription "Continuous Acquisition and Life-cycle Support Type 1"
#define CALSNote "Specified in MIL-R-28002 and MIL-PRF-28002"
MagickInfo
*entry;
entry=AcquireMagickInfo("CALS","CAL",CALSDescription);
entry->decoder=(DecodeImageHandler *) ReadCALSImage;
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->encoder=(EncodeImageHandler *) WriteCALSImage;
#endif
entry->flags^=CoderAdjoinFlag;
entry->magick=(IsImageFormatHandler *) IsCALS;
entry->note=ConstantString(CALSNote);
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("CALS","CALS",CALSDescription);
entry->decoder=(DecodeImageHandler *) ReadCALSImage;
#if defined(MAGICKCORE_TIFF_DELEGATE)
entry->encoder=(EncodeImageHandler *) WriteCALSImage;
#endif
entry->flags^=CoderAdjoinFlag;
entry->magick=(IsImageFormatHandler *) IsCALS;
entry->note=ConstantString(CALSNote);
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r C A L S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterCALSImage() removes format registrations made by the
% CALS module from the list of supported formats.
%
% The format of the UnregisterCALSImage method is:
%
% UnregisterCALSImage(void)
%
*/
ModuleExport void UnregisterCALSImage(void)
{
(void) UnregisterMagickInfo("CAL");
(void) UnregisterMagickInfo("CALS");
}
#if defined(MAGICKCORE_TIFF_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e C A L S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteCALSImage() writes an image to a file in CALS Raster Group 1 image
% format.
%
% The format of the WriteCALSImage method is:
%
% MagickBooleanType WriteCALSImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ssize_t WriteCALSRecord(Image *image,const char *data)
{
char
pad[128];
register const char
*p;
register ssize_t
i;
ssize_t
count;
i=0;
count=0;
if (data != (const char *) NULL)
{
p=data;
for (i=0; (i < 128) && (p[i] != '\0'); i++);
count=WriteBlob(image,(size_t) i,(const unsigned char *) data);
}
if (i < 128)
{
i=128-i;
(void) memset(pad,' ',(size_t) i);
count=WriteBlob(image,(size_t) i,(const unsigned char *) pad);
}
return(count);
}
static MagickBooleanType WriteCALSImage(const ImageInfo *image_info,
Image *image,ExceptionInfo *exception)
{
char
header[129];
Image
*group4_image;
ImageInfo
*write_info;
MagickBooleanType
status;
register ssize_t
i;
size_t
density,
length,
orient_x,
orient_y;
ssize_t
count;
unsigned char
*group4;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
/*
Create standard CALS header.
*/
count=WriteCALSRecord(image,"srcdocid: NONE");
(void) count;
count=WriteCALSRecord(image,"dstdocid: NONE");
count=WriteCALSRecord(image,"txtfilid: NONE");
count=WriteCALSRecord(image,"figid: NONE");
count=WriteCALSRecord(image,"srcgph: NONE");
count=WriteCALSRecord(image,"doccls: NONE");
count=WriteCALSRecord(image,"rtype: 1");
orient_x=0;
orient_y=0;
switch (image->orientation)
{
case TopRightOrientation:
{
orient_x=180;
orient_y=270;
break;
}
case BottomRightOrientation:
{
orient_x=180;
orient_y=90;
break;
}
case BottomLeftOrientation:
{
orient_y=90;
break;
}
case LeftTopOrientation:
{
orient_x=270;
break;
}
case RightTopOrientation:
{
orient_x=270;
orient_y=180;
break;
}
case RightBottomOrientation:
{
orient_x=90;
orient_y=180;
break;
}
case LeftBottomOrientation:
{
orient_x=90;
break;
}
default:
{
orient_y=270;
break;
}
}
(void) FormatLocaleString(header,sizeof(header),"rorient: %03ld,%03ld",
(long) orient_x,(long) orient_y);
count=WriteCALSRecord(image,header);
(void) FormatLocaleString(header,sizeof(header),"rpelcnt: %06lu,%06lu",
(unsigned long) image->columns,(unsigned long) image->rows);
count=WriteCALSRecord(image,header);
density=200;
if (image_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
(void) ParseGeometry(image_info->density,&geometry_info);
density=(size_t) floor(geometry_info.rho+0.5);
}
(void) FormatLocaleString(header,sizeof(header),"rdensty: %04lu",
(unsigned long) density);
count=WriteCALSRecord(image,header);
count=WriteCALSRecord(image,"notes: NONE");
(void) memset(header,' ',128);
for (i=0; i < 5; i++)
(void) WriteBlob(image,128,(unsigned char *) header);
/*
Write CALS pixels.
*/
write_info=CloneImageInfo(image_info);
(void) CopyMagickString(write_info->filename,"GROUP4:",MagickPathExtent);
(void) CopyMagickString(write_info->magick,"GROUP4",MagickPathExtent);
group4_image=CloneImage(image,0,0,MagickTrue,exception);
if (group4_image == (Image *) NULL)
{
write_info=DestroyImageInfo(write_info);
(void) CloseBlob(image);
return(MagickFalse);
}
group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length,
exception);
group4_image=DestroyImage(group4_image);
if (group4 == (unsigned char *) NULL)
{
write_info=DestroyImageInfo(write_info);
(void) CloseBlob(image);
return(MagickFalse);
}
write_info=DestroyImageInfo(write_info);
if (WriteBlob(image,length,group4) != (ssize_t) length)
status=MagickFalse;
group4=(unsigned char *) RelinquishMagickMemory(group4);
(void) CloseBlob(image);
return(status);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_364_0 |
crossvul-cpp_data_bad_3987_1 | #include "clar_libgit2.h"
#include "checkout_helpers.h"
#include "git2/checkout.h"
#include "repository.h"
#include "buffer.h"
#include "futils.h"
static const char *repo_name = "nasty";
static git_repository *repo;
static git_checkout_options checkout_opts;
void test_checkout_nasty__initialize(void)
{
repo = cl_git_sandbox_init(repo_name);
GIT_INIT_STRUCTURE(&checkout_opts, GIT_CHECKOUT_OPTIONS_VERSION);
checkout_opts.checkout_strategy = GIT_CHECKOUT_FORCE;
}
void test_checkout_nasty__cleanup(void)
{
cl_git_sandbox_cleanup();
}
static void test_checkout_passes(const char *refname, const char *filename)
{
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
git_buf path = GIT_BUF_INIT;
cl_git_pass(git_buf_joinpath(&path, repo_name, filename));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, refname));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE |
GIT_CHECKOUT_DONT_UPDATE_INDEX;
cl_git_pass(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(!git_path_exists(path.ptr));
git_commit_free(commit);
git_buf_dispose(&path);
}
static void test_checkout_fails(const char *refname, const char *filename)
{
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
git_buf path = GIT_BUF_INIT;
cl_git_pass(git_buf_joinpath(&path, repo_name, filename));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, refname));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE;
cl_git_fail(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(!git_path_exists(path.ptr));
git_commit_free(commit);
git_buf_dispose(&path);
}
/* A tree that contains ".git" as a tree, with a blob inside
* (".git/foobar").
*/
void test_checkout_nasty__dotgit_tree(void)
{
test_checkout_fails("refs/heads/dotgit_tree", ".git/foobar");
}
/* A tree that contains ".GIT" as a tree, with a blob inside
* (".GIT/foobar").
*/
void test_checkout_nasty__dotcapitalgit_tree(void)
{
test_checkout_fails("refs/heads/dotcapitalgit_tree", ".GIT/foobar");
}
/* A tree that contains a tree ".", with a blob inside ("./foobar").
*/
void test_checkout_nasty__dot_tree(void)
{
test_checkout_fails("refs/heads/dot_tree", "foobar");
}
/* A tree that contains a tree ".", with a tree ".git", with a blob
* inside ("./.git/foobar").
*/
void test_checkout_nasty__dot_dotgit_tree(void)
{
test_checkout_fails("refs/heads/dot_dotgit_tree", ".git/foobar");
}
/* A tree that contains a tree, with a tree "..", with a tree ".git", with a
* blob inside ("foo/../.git/foobar").
*/
void test_checkout_nasty__dotdot_dotgit_tree(void)
{
test_checkout_fails("refs/heads/dotdot_dotgit_tree", ".git/foobar");
}
/* A tree that contains a tree, with a tree "..", with a blob inside
* ("foo/../foobar").
*/
void test_checkout_nasty__dotdot_tree(void)
{
test_checkout_fails("refs/heads/dotdot_tree", "foobar");
}
/* A tree that contains a blob with the rogue name ".git/foobar" */
void test_checkout_nasty__dotgit_path(void)
{
test_checkout_fails("refs/heads/dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name ".GIT/foobar" */
void test_checkout_nasty__dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "./.git/foobar" */
void test_checkout_nasty__dot_dotgit_path(void)
{
test_checkout_fails("refs/heads/dot_dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name "./.GIT/foobar" */
void test_checkout_nasty__dot_dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dot_dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "foo/../.git/foobar" */
void test_checkout_nasty__dotdot_dotgit_path(void)
{
test_checkout_fails("refs/heads/dotdot_dotgit_path", ".git/foobar");
}
/* A tree that contains a blob with the rogue name "foo/../.GIT/foobar" */
void test_checkout_nasty__dotdot_dotcapitalgit_path(void)
{
test_checkout_fails("refs/heads/dotdot_dotcapitalgit_path", ".GIT/foobar");
}
/* A tree that contains a blob with the rogue name "foo/." */
void test_checkout_nasty__dot_path(void)
{
test_checkout_fails("refs/heads/dot_path", "./foobar");
}
/* A tree that contains a blob with the rogue name "foo/." */
void test_checkout_nasty__dot_path_two(void)
{
test_checkout_fails("refs/heads/dot_path_two", "foo/.");
}
/* A tree that contains a blob with the rogue name "foo/../foobar" */
void test_checkout_nasty__dotdot_path(void)
{
test_checkout_fails("refs/heads/dotdot_path", "foobar");
}
/* A tree that contains an entry with a backslash ".git\foobar" */
void test_checkout_nasty__dotgit_backslash_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dotgit_backslash_path", ".git/foobar");
#endif
}
/* A tree that contains an entry with a backslash ".GIT\foobar" */
void test_checkout_nasty__dotcapitalgit_backslash_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dotcapitalgit_backslash_path", ".GIT/foobar");
#endif
}
/* A tree that contains an entry with a backslash ".\.GIT\foobar" */
void test_checkout_nasty__dot_backslash_dotcapitalgit_path(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_backslash_dotcapitalgit_path", ".GIT/foobar");
#endif
}
/* A tree that contains an entry ".git.", because Win32 APIs will drop the
* trailing slash.
*/
void test_checkout_nasty__dot_git_dot(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_dot", ".git/foobar");
#endif
}
/* A tree that contains an entry "git~1", because that is typically the
* short name for ".git".
*/
void test_checkout_nasty__git_tilde1(void)
{
test_checkout_fails("refs/heads/git_tilde1", ".git/foobar");
test_checkout_fails("refs/heads/git_tilde1", "git~1/foobar");
}
/* A tree that contains an entry "git~2", when we have forced the short
* name for ".git" into "GIT~2".
*/
void test_checkout_nasty__git_custom_shortname(void)
{
#ifdef GIT_WIN32
if (!cl_sandbox_supports_8dot3())
clar__skip();
cl_must_pass(p_rename("nasty/.git", "nasty/_temp"));
cl_git_write2file("nasty/git~1", "", 0, O_RDWR|O_CREAT, 0666);
cl_must_pass(p_rename("nasty/_temp", "nasty/.git"));
test_checkout_fails("refs/heads/git_tilde2", ".git/foobar");
#endif
}
/* A tree that contains an entry "git~3", which should be allowed, since
* it is not the typical short name ("GIT~1") or the actual short name
* ("GIT~2") for ".git".
*/
void test_checkout_nasty__only_looks_like_a_git_shortname(void)
{
#ifdef GIT_WIN32
git_oid commit_id;
git_commit *commit;
git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
cl_must_pass(p_rename("nasty/.git", "nasty/_temp"));
cl_git_write2file("nasty/git~1", "", 0, O_RDWR|O_CREAT, 0666);
cl_must_pass(p_rename("nasty/_temp", "nasty/.git"));
cl_git_pass(git_reference_name_to_id(&commit_id, repo, "refs/heads/git_tilde3"));
cl_git_pass(git_commit_lookup(&commit, repo, &commit_id));
opts.checkout_strategy = GIT_CHECKOUT_FORCE;
cl_git_pass(git_checkout_tree(repo, (const git_object *)commit, &opts));
cl_assert(git_path_exists("nasty/git~3/foobar"));
git_commit_free(commit);
#endif
}
/* A tree that contains an entry "git:", because Win32 APIs will reject
* that as looking too similar to a drive letter.
*/
void test_checkout_nasty__dot_git_colon(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_colon", ".git/foobar");
#endif
}
/* A tree that contains an entry "git:foo", because Win32 APIs will turn
* that into ".git".
*/
void test_checkout_nasty__dot_git_colon_stuff(void)
{
#ifdef GIT_WIN32
test_checkout_fails("refs/heads/dot_git_colon_stuff", ".git/foobar");
#endif
}
/* Trees that contains entries with a tree ".git" that contain
* byte sequences:
* { 0xe2, 0x80, 0x8c }
* { 0xe2, 0x80, 0x8d }
* { 0xe2, 0x80, 0x8e }
* { 0xe2, 0x80, 0x8f }
* { 0xe2, 0x80, 0xaa }
* { 0xe2, 0x80, 0xab }
* { 0xe2, 0x80, 0xac }
* { 0xe2, 0x80, 0xad }
* { 0xe2, 0x81, 0xae }
* { 0xe2, 0x81, 0xaa }
* { 0xe2, 0x81, 0xab }
* { 0xe2, 0x81, 0xac }
* { 0xe2, 0x81, 0xad }
* { 0xe2, 0x81, 0xae }
* { 0xe2, 0x81, 0xaf }
* { 0xef, 0xbb, 0xbf }
* Because these map to characters that HFS filesystems "ignore". Thus
* ".git<U+200C>" will map to ".git".
*/
void test_checkout_nasty__dot_git_hfs_ignorable(void)
{
#ifdef __APPLE__
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_1", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_2", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_3", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_4", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_5", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_6", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_7", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_8", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_9", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_10", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_11", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_12", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_13", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_14", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_15", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_16", ".git/foobar");
#endif
}
void test_checkout_nasty__honors_core_protecthfs(void)
{
cl_repo_set_bool(repo, "core.protectHFS", true);
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_1", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_2", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_3", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_4", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_5", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_6", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_7", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_8", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_9", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_10", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_11", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_12", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_13", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_14", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_15", ".git/foobar");
test_checkout_fails("refs/heads/dotgit_hfs_ignorable_16", ".git/foobar");
}
void test_checkout_nasty__honors_core_protectntfs(void)
{
cl_repo_set_bool(repo, "core.protectNTFS", true);
test_checkout_fails("refs/heads/dotgit_backslash_path", ".git/foobar");
test_checkout_fails("refs/heads/dotcapitalgit_backslash_path", ".GIT/foobar");
test_checkout_fails("refs/heads/dot_git_dot", ".git/foobar");
test_checkout_fails("refs/heads/git_tilde1", ".git/foobar");
}
void test_checkout_nasty__symlink1(void)
{
test_checkout_passes("refs/heads/symlink1", ".git/foobar");
}
void test_checkout_nasty__symlink2(void)
{
test_checkout_passes("refs/heads/symlink2", ".git/foobar");
}
void test_checkout_nasty__symlink3(void)
{
test_checkout_passes("refs/heads/symlink3", ".git/foobar");
}
void test_checkout_nasty__gitmodules_symlink(void)
{
cl_repo_set_bool(repo, "core.protectHFS", true);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
cl_repo_set_bool(repo, "core.protectHFS", false);
cl_repo_set_bool(repo, "core.protectNTFS", true);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
cl_repo_set_bool(repo, "core.protectNTFS", false);
test_checkout_fails("refs/heads/gitmodules-symlink", ".gitmodules");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_3987_1 |
crossvul-cpp_data_bad_1718_0 | /* $OpenBSD: monitor.c,v 1.150 2015/06/22 23:42:16 djm Exp $ */
/*
* Copyright 2002 Niels Provos <provos@citi.umich.edu>
* Copyright 2002 Markus Friedl <markus@openbsd.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "includes.h"
#include <sys/types.h>
#include <sys/socket.h>
#include "openbsd-compat/sys-tree.h"
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#ifdef HAVE_PATHS_H
#include <paths.h>
#endif
#include <pwd.h>
#include <signal.h>
#ifdef HAVE_STDINT_H
#include <stdint.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>
#ifdef HAVE_POLL_H
#include <poll.h>
#else
# ifdef HAVE_SYS_POLL_H
# include <sys/poll.h>
# endif
#endif
#ifdef SKEY
#include <skey.h>
#endif
#ifdef WITH_OPENSSL
#include <openssl/dh.h>
#endif
#include "openbsd-compat/sys-queue.h"
#include "atomicio.h"
#include "xmalloc.h"
#include "ssh.h"
#include "key.h"
#include "buffer.h"
#include "hostfile.h"
#include "auth.h"
#include "cipher.h"
#include "kex.h"
#include "dh.h"
#ifdef TARGET_OS_MAC /* XXX Broken krb5 headers on Mac */
#undef TARGET_OS_MAC
#include "zlib.h"
#define TARGET_OS_MAC 1
#else
#include "zlib.h"
#endif
#include "packet.h"
#include "auth-options.h"
#include "sshpty.h"
#include "channels.h"
#include "session.h"
#include "sshlogin.h"
#include "canohost.h"
#include "log.h"
#include "misc.h"
#include "servconf.h"
#include "monitor.h"
#include "monitor_mm.h"
#ifdef GSSAPI
#include "ssh-gss.h"
#endif
#include "monitor_wrap.h"
#include "monitor_fdpass.h"
#include "compat.h"
#include "ssh2.h"
#include "roaming.h"
#include "authfd.h"
#include "match.h"
#include "ssherr.h"
#ifdef GSSAPI
static Gssctxt *gsscontext = NULL;
#endif
/* Imports */
extern ServerOptions options;
extern u_int utmp_len;
extern u_char session_id[];
extern Buffer auth_debug;
extern int auth_debug_init;
extern Buffer loginmsg;
/* State exported from the child */
static struct sshbuf *child_state;
/* Functions on the monitor that answer unprivileged requests */
int mm_answer_moduli(int, Buffer *);
int mm_answer_sign(int, Buffer *);
int mm_answer_pwnamallow(int, Buffer *);
int mm_answer_auth2_read_banner(int, Buffer *);
int mm_answer_authserv(int, Buffer *);
int mm_answer_authpassword(int, Buffer *);
int mm_answer_bsdauthquery(int, Buffer *);
int mm_answer_bsdauthrespond(int, Buffer *);
int mm_answer_skeyquery(int, Buffer *);
int mm_answer_skeyrespond(int, Buffer *);
int mm_answer_keyallowed(int, Buffer *);
int mm_answer_keyverify(int, Buffer *);
int mm_answer_pty(int, Buffer *);
int mm_answer_pty_cleanup(int, Buffer *);
int mm_answer_term(int, Buffer *);
int mm_answer_rsa_keyallowed(int, Buffer *);
int mm_answer_rsa_challenge(int, Buffer *);
int mm_answer_rsa_response(int, Buffer *);
int mm_answer_sesskey(int, Buffer *);
int mm_answer_sessid(int, Buffer *);
#ifdef USE_PAM
int mm_answer_pam_start(int, Buffer *);
int mm_answer_pam_account(int, Buffer *);
int mm_answer_pam_init_ctx(int, Buffer *);
int mm_answer_pam_query(int, Buffer *);
int mm_answer_pam_respond(int, Buffer *);
int mm_answer_pam_free_ctx(int, Buffer *);
#endif
#ifdef GSSAPI
int mm_answer_gss_setup_ctx(int, Buffer *);
int mm_answer_gss_accept_ctx(int, Buffer *);
int mm_answer_gss_userok(int, Buffer *);
int mm_answer_gss_checkmic(int, Buffer *);
#endif
#ifdef SSH_AUDIT_EVENTS
int mm_answer_audit_event(int, Buffer *);
int mm_answer_audit_command(int, Buffer *);
#endif
static int monitor_read_log(struct monitor *);
static Authctxt *authctxt;
#ifdef WITH_SSH1
static BIGNUM *ssh1_challenge = NULL; /* used for ssh1 rsa auth */
#endif
/* local state for key verify */
static u_char *key_blob = NULL;
static u_int key_bloblen = 0;
static int key_blobtype = MM_NOKEY;
static char *hostbased_cuser = NULL;
static char *hostbased_chost = NULL;
static char *auth_method = "unknown";
static char *auth_submethod = NULL;
static u_int session_id2_len = 0;
static u_char *session_id2 = NULL;
static pid_t monitor_child_pid;
struct mon_table {
enum monitor_reqtype type;
int flags;
int (*f)(int, Buffer *);
};
#define MON_ISAUTH 0x0004 /* Required for Authentication */
#define MON_AUTHDECIDE 0x0008 /* Decides Authentication */
#define MON_ONCE 0x0010 /* Disable after calling */
#define MON_ALOG 0x0020 /* Log auth attempt without authenticating */
#define MON_AUTH (MON_ISAUTH|MON_AUTHDECIDE)
#define MON_PERMIT 0x1000 /* Request is permitted */
struct mon_table mon_dispatch_proto20[] = {
#ifdef WITH_OPENSSL
{MONITOR_REQ_MODULI, MON_ONCE, mm_answer_moduli},
#endif
{MONITOR_REQ_SIGN, MON_ONCE, mm_answer_sign},
{MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
{MONITOR_REQ_AUTHSERV, MON_ONCE, mm_answer_authserv},
{MONITOR_REQ_AUTH2_READ_BANNER, MON_ONCE, mm_answer_auth2_read_banner},
{MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
#ifdef USE_PAM
{MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
{MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
{MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
{MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
{MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
{MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
#endif
#ifdef SSH_AUDIT_EVENTS
{MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
#endif
#ifdef BSD_AUTH
{MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
{MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
#endif
#ifdef SKEY
{MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
{MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
#endif
{MONITOR_REQ_KEYALLOWED, MON_ISAUTH, mm_answer_keyallowed},
{MONITOR_REQ_KEYVERIFY, MON_AUTH, mm_answer_keyverify},
#ifdef GSSAPI
{MONITOR_REQ_GSSSETUP, MON_ISAUTH, mm_answer_gss_setup_ctx},
{MONITOR_REQ_GSSSTEP, MON_ISAUTH, mm_answer_gss_accept_ctx},
{MONITOR_REQ_GSSUSEROK, MON_AUTH, mm_answer_gss_userok},
{MONITOR_REQ_GSSCHECKMIC, MON_ISAUTH, mm_answer_gss_checkmic},
#endif
{0, 0, NULL}
};
struct mon_table mon_dispatch_postauth20[] = {
#ifdef WITH_OPENSSL
{MONITOR_REQ_MODULI, 0, mm_answer_moduli},
#endif
{MONITOR_REQ_SIGN, 0, mm_answer_sign},
{MONITOR_REQ_PTY, 0, mm_answer_pty},
{MONITOR_REQ_PTYCLEANUP, 0, mm_answer_pty_cleanup},
{MONITOR_REQ_TERM, 0, mm_answer_term},
#ifdef SSH_AUDIT_EVENTS
{MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
{MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT, mm_answer_audit_command},
#endif
{0, 0, NULL}
};
struct mon_table mon_dispatch_proto15[] = {
#ifdef WITH_SSH1
{MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
{MONITOR_REQ_SESSKEY, MON_ONCE, mm_answer_sesskey},
{MONITOR_REQ_SESSID, MON_ONCE, mm_answer_sessid},
{MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
{MONITOR_REQ_RSAKEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_rsa_keyallowed},
{MONITOR_REQ_KEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_keyallowed},
{MONITOR_REQ_RSACHALLENGE, MON_ONCE, mm_answer_rsa_challenge},
{MONITOR_REQ_RSARESPONSE, MON_ONCE|MON_AUTHDECIDE, mm_answer_rsa_response},
#ifdef BSD_AUTH
{MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
{MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
#endif
#ifdef SKEY
{MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
{MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
#endif
#ifdef USE_PAM
{MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
{MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
{MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
{MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
{MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
{MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
#endif
#ifdef SSH_AUDIT_EVENTS
{MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
#endif
#endif /* WITH_SSH1 */
{0, 0, NULL}
};
struct mon_table mon_dispatch_postauth15[] = {
#ifdef WITH_SSH1
{MONITOR_REQ_PTY, MON_ONCE, mm_answer_pty},
{MONITOR_REQ_PTYCLEANUP, MON_ONCE, mm_answer_pty_cleanup},
{MONITOR_REQ_TERM, 0, mm_answer_term},
#ifdef SSH_AUDIT_EVENTS
{MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
{MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT|MON_ONCE, mm_answer_audit_command},
#endif
#endif /* WITH_SSH1 */
{0, 0, NULL}
};
struct mon_table *mon_dispatch;
/* Specifies if a certain message is allowed at the moment */
static void
monitor_permit(struct mon_table *ent, enum monitor_reqtype type, int permit)
{
while (ent->f != NULL) {
if (ent->type == type) {
ent->flags &= ~MON_PERMIT;
ent->flags |= permit ? MON_PERMIT : 0;
return;
}
ent++;
}
}
static void
monitor_permit_authentications(int permit)
{
struct mon_table *ent = mon_dispatch;
while (ent->f != NULL) {
if (ent->flags & MON_AUTH) {
ent->flags &= ~MON_PERMIT;
ent->flags |= permit ? MON_PERMIT : 0;
}
ent++;
}
}
void
monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
{
struct mon_table *ent;
int authenticated = 0, partial = 0;
debug3("preauth child monitor started");
close(pmonitor->m_recvfd);
close(pmonitor->m_log_sendfd);
pmonitor->m_log_sendfd = pmonitor->m_recvfd = -1;
authctxt = _authctxt;
memset(authctxt, 0, sizeof(*authctxt));
authctxt->loginmsg = &loginmsg;
if (compat20) {
mon_dispatch = mon_dispatch_proto20;
/* Permit requests for moduli and signatures */
monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
} else {
mon_dispatch = mon_dispatch_proto15;
monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 1);
}
/* The first few requests do not require asynchronous access */
while (!authenticated) {
partial = 0;
auth_method = "unknown";
auth_submethod = NULL;
authenticated = (monitor_read(pmonitor, mon_dispatch, &ent) == 1);
/* Special handling for multiple required authentications */
if (options.num_auth_methods != 0) {
if (!compat20)
fatal("AuthenticationMethods is not supported"
"with SSH protocol 1");
if (authenticated &&
!auth2_update_methods_lists(authctxt,
auth_method, auth_submethod)) {
debug3("%s: method %s: partial", __func__,
auth_method);
authenticated = 0;
partial = 1;
}
}
if (authenticated) {
if (!(ent->flags & MON_AUTHDECIDE))
fatal("%s: unexpected authentication from %d",
__func__, ent->type);
if (authctxt->pw->pw_uid == 0 &&
!auth_root_allowed(auth_method))
authenticated = 0;
#ifdef USE_PAM
/* PAM needs to perform account checks after auth */
if (options.use_pam && authenticated) {
Buffer m;
buffer_init(&m);
mm_request_receive_expect(pmonitor->m_sendfd,
MONITOR_REQ_PAM_ACCOUNT, &m);
authenticated = mm_answer_pam_account(pmonitor->m_sendfd, &m);
buffer_free(&m);
}
#endif
}
if (ent->flags & (MON_AUTHDECIDE|MON_ALOG)) {
auth_log(authctxt, authenticated, partial,
auth_method, auth_submethod);
if (!partial && !authenticated)
authctxt->failures++;
}
}
if (!authctxt->valid)
fatal("%s: authenticated invalid user", __func__);
if (strcmp(auth_method, "unknown") == 0)
fatal("%s: authentication method name unknown", __func__);
debug("%s: %s has been authenticated by privileged process",
__func__, authctxt->user);
mm_get_keystate(pmonitor);
/* Drain any buffered messages from the child */
while (pmonitor->m_log_recvfd != -1 && monitor_read_log(pmonitor) == 0)
;
close(pmonitor->m_sendfd);
close(pmonitor->m_log_recvfd);
pmonitor->m_sendfd = pmonitor->m_log_recvfd = -1;
}
static void
monitor_set_child_handler(pid_t pid)
{
monitor_child_pid = pid;
}
static void
monitor_child_handler(int sig)
{
kill(monitor_child_pid, sig);
}
void
monitor_child_postauth(struct monitor *pmonitor)
{
close(pmonitor->m_recvfd);
pmonitor->m_recvfd = -1;
monitor_set_child_handler(pmonitor->m_pid);
signal(SIGHUP, &monitor_child_handler);
signal(SIGTERM, &monitor_child_handler);
signal(SIGINT, &monitor_child_handler);
#ifdef SIGXFSZ
signal(SIGXFSZ, SIG_IGN);
#endif
if (compat20) {
mon_dispatch = mon_dispatch_postauth20;
/* Permit requests for moduli and signatures */
monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
} else {
mon_dispatch = mon_dispatch_postauth15;
monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
}
if (!no_pty_flag) {
monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
}
for (;;)
monitor_read(pmonitor, mon_dispatch, NULL);
}
void
monitor_sync(struct monitor *pmonitor)
{
if (options.compression) {
/* The member allocation is not visible, so sync it */
mm_share_sync(&pmonitor->m_zlib, &pmonitor->m_zback);
}
}
/* Allocation functions for zlib */
static void *
mm_zalloc(struct mm_master *mm, u_int ncount, u_int size)
{
size_t len = (size_t) size * ncount;
void *address;
if (len == 0 || ncount > SIZE_MAX / size)
fatal("%s: mm_zalloc(%u, %u)", __func__, ncount, size);
address = mm_malloc(mm, len);
return (address);
}
static void
mm_zfree(struct mm_master *mm, void *address)
{
mm_free(mm, address);
}
static int
monitor_read_log(struct monitor *pmonitor)
{
Buffer logmsg;
u_int len, level;
char *msg;
buffer_init(&logmsg);
/* Read length */
buffer_append_space(&logmsg, 4);
if (atomicio(read, pmonitor->m_log_recvfd,
buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg)) {
if (errno == EPIPE) {
buffer_free(&logmsg);
debug("%s: child log fd closed", __func__);
close(pmonitor->m_log_recvfd);
pmonitor->m_log_recvfd = -1;
return -1;
}
fatal("%s: log fd read: %s", __func__, strerror(errno));
}
len = buffer_get_int(&logmsg);
if (len <= 4 || len > 8192)
fatal("%s: invalid log message length %u", __func__, len);
/* Read severity, message */
buffer_clear(&logmsg);
buffer_append_space(&logmsg, len);
if (atomicio(read, pmonitor->m_log_recvfd,
buffer_ptr(&logmsg), buffer_len(&logmsg)) != buffer_len(&logmsg))
fatal("%s: log fd read: %s", __func__, strerror(errno));
/* Log it */
level = buffer_get_int(&logmsg);
msg = buffer_get_string(&logmsg, NULL);
if (log_level_name(level) == NULL)
fatal("%s: invalid log level %u (corrupted message?)",
__func__, level);
do_log2(level, "%s [preauth]", msg);
buffer_free(&logmsg);
free(msg);
return 0;
}
int
monitor_read(struct monitor *pmonitor, struct mon_table *ent,
struct mon_table **pent)
{
Buffer m;
int ret;
u_char type;
struct pollfd pfd[2];
for (;;) {
memset(&pfd, 0, sizeof(pfd));
pfd[0].fd = pmonitor->m_sendfd;
pfd[0].events = POLLIN;
pfd[1].fd = pmonitor->m_log_recvfd;
pfd[1].events = pfd[1].fd == -1 ? 0 : POLLIN;
if (poll(pfd, pfd[1].fd == -1 ? 1 : 2, -1) == -1) {
if (errno == EINTR || errno == EAGAIN)
continue;
fatal("%s: poll: %s", __func__, strerror(errno));
}
if (pfd[1].revents) {
/*
* Drain all log messages before processing next
* monitor request.
*/
monitor_read_log(pmonitor);
continue;
}
if (pfd[0].revents)
break; /* Continues below */
}
buffer_init(&m);
mm_request_receive(pmonitor->m_sendfd, &m);
type = buffer_get_char(&m);
debug3("%s: checking request %d", __func__, type);
while (ent->f != NULL) {
if (ent->type == type)
break;
ent++;
}
if (ent->f != NULL) {
if (!(ent->flags & MON_PERMIT))
fatal("%s: unpermitted request %d", __func__,
type);
ret = (*ent->f)(pmonitor->m_sendfd, &m);
buffer_free(&m);
/* The child may use this request only once, disable it */
if (ent->flags & MON_ONCE) {
debug2("%s: %d used once, disabling now", __func__,
type);
ent->flags &= ~MON_PERMIT;
}
if (pent != NULL)
*pent = ent;
return ret;
}
fatal("%s: unsupported request: %d", __func__, type);
/* NOTREACHED */
return (-1);
}
/* allowed key state */
static int
monitor_allowed_key(u_char *blob, u_int bloblen)
{
/* make sure key is allowed */
if (key_blob == NULL || key_bloblen != bloblen ||
timingsafe_bcmp(key_blob, blob, key_bloblen))
return (0);
return (1);
}
static void
monitor_reset_key_state(void)
{
/* reset state */
free(key_blob);
free(hostbased_cuser);
free(hostbased_chost);
key_blob = NULL;
key_bloblen = 0;
key_blobtype = MM_NOKEY;
hostbased_cuser = NULL;
hostbased_chost = NULL;
}
#ifdef WITH_OPENSSL
int
mm_answer_moduli(int sock, Buffer *m)
{
DH *dh;
int min, want, max;
min = buffer_get_int(m);
want = buffer_get_int(m);
max = buffer_get_int(m);
debug3("%s: got parameters: %d %d %d",
__func__, min, want, max);
/* We need to check here, too, in case the child got corrupted */
if (max < min || want < min || max < want)
fatal("%s: bad parameters: %d %d %d",
__func__, min, want, max);
buffer_clear(m);
dh = choose_dh(min, want, max);
if (dh == NULL) {
buffer_put_char(m, 0);
return (0);
} else {
/* Send first bignum */
buffer_put_char(m, 1);
buffer_put_bignum2(m, dh->p);
buffer_put_bignum2(m, dh->g);
DH_free(dh);
}
mm_request_send(sock, MONITOR_ANS_MODULI, m);
return (0);
}
#endif
int
mm_answer_sign(int sock, Buffer *m)
{
struct ssh *ssh = active_state; /* XXX */
extern int auth_sock; /* XXX move to state struct? */
struct sshkey *key;
struct sshbuf *sigbuf;
u_char *p;
u_char *signature;
size_t datlen, siglen;
int r, keyid, is_proof = 0;
const char proof_req[] = "hostkeys-prove-00@openssh.com";
debug3("%s", __func__);
if ((r = sshbuf_get_u32(m, &keyid)) != 0 ||
(r = sshbuf_get_string(m, &p, &datlen)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
/*
* Supported KEX types use SHA1 (20 bytes), SHA256 (32 bytes),
* SHA384 (48 bytes) and SHA512 (64 bytes).
*
* Otherwise, verify the signature request is for a hostkey
* proof.
*
* XXX perform similar check for KEX signature requests too?
* it's not trivial, since what is signed is the hash, rather
* than the full kex structure...
*/
if (datlen != 20 && datlen != 32 && datlen != 48 && datlen != 64) {
/*
* Construct expected hostkey proof and compare it to what
* the client sent us.
*/
if (session_id2_len == 0) /* hostkeys is never first */
fatal("%s: bad data length: %zu", __func__, datlen);
if ((key = get_hostkey_public_by_index(keyid, ssh)) == NULL)
fatal("%s: no hostkey for index %d", __func__, keyid);
if ((sigbuf = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new", __func__);
if ((r = sshbuf_put_cstring(sigbuf, proof_req)) != 0 ||
(r = sshbuf_put_string(sigbuf, session_id2,
session_id2_len) != 0) ||
(r = sshkey_puts(key, sigbuf)) != 0)
fatal("%s: couldn't prepare private key "
"proof buffer: %s", __func__, ssh_err(r));
if (datlen != sshbuf_len(sigbuf) ||
memcmp(p, sshbuf_ptr(sigbuf), sshbuf_len(sigbuf)) != 0)
fatal("%s: bad data length: %zu, hostkey proof len %zu",
__func__, datlen, sshbuf_len(sigbuf));
sshbuf_free(sigbuf);
is_proof = 1;
}
/* save session id, it will be passed on the first call */
if (session_id2_len == 0) {
session_id2_len = datlen;
session_id2 = xmalloc(session_id2_len);
memcpy(session_id2, p, session_id2_len);
}
if ((key = get_hostkey_by_index(keyid)) != NULL) {
if ((r = sshkey_sign(key, &signature, &siglen, p, datlen,
datafellows)) != 0)
fatal("%s: sshkey_sign failed: %s",
__func__, ssh_err(r));
} else if ((key = get_hostkey_public_by_index(keyid, ssh)) != NULL &&
auth_sock > 0) {
if ((r = ssh_agent_sign(auth_sock, key, &signature, &siglen,
p, datlen, datafellows)) != 0) {
fatal("%s: ssh_agent_sign failed: %s",
__func__, ssh_err(r));
}
} else
fatal("%s: no hostkey from index %d", __func__, keyid);
debug3("%s: %s signature %p(%zu)", __func__,
is_proof ? "KEX" : "hostkey proof", signature, siglen);
sshbuf_reset(m);
if ((r = sshbuf_put_string(m, signature, siglen)) != 0)
fatal("%s: buffer error: %s", __func__, ssh_err(r));
free(p);
free(signature);
mm_request_send(sock, MONITOR_ANS_SIGN, m);
/* Turn on permissions for getpwnam */
monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
return (0);
}
/* Retrieves the password entry and also checks if the user is permitted */
int
mm_answer_pwnamallow(int sock, Buffer *m)
{
char *username;
struct passwd *pwent;
int allowed = 0;
u_int i;
debug3("%s", __func__);
if (authctxt->attempt++ != 0)
fatal("%s: multiple attempts for getpwnam", __func__);
username = buffer_get_string(m, NULL);
pwent = getpwnamallow(username);
authctxt->user = xstrdup(username);
setproctitle("%s [priv]", pwent ? username : "unknown");
free(username);
buffer_clear(m);
if (pwent == NULL) {
buffer_put_char(m, 0);
authctxt->pw = fakepw();
goto out;
}
allowed = 1;
authctxt->pw = pwent;
authctxt->valid = 1;
buffer_put_char(m, 1);
buffer_put_string(m, pwent, sizeof(struct passwd));
buffer_put_cstring(m, pwent->pw_name);
buffer_put_cstring(m, "*");
#ifdef HAVE_STRUCT_PASSWD_PW_GECOS
buffer_put_cstring(m, pwent->pw_gecos);
#endif
#ifdef HAVE_STRUCT_PASSWD_PW_CLASS
buffer_put_cstring(m, pwent->pw_class);
#endif
buffer_put_cstring(m, pwent->pw_dir);
buffer_put_cstring(m, pwent->pw_shell);
out:
buffer_put_string(m, &options, sizeof(options));
#define M_CP_STROPT(x) do { \
if (options.x != NULL) \
buffer_put_cstring(m, options.x); \
} while (0)
#define M_CP_STRARRAYOPT(x, nx) do { \
for (i = 0; i < options.nx; i++) \
buffer_put_cstring(m, options.x[i]); \
} while (0)
/* See comment in servconf.h */
COPY_MATCH_STRING_OPTS();
#undef M_CP_STROPT
#undef M_CP_STRARRAYOPT
/* Create valid auth method lists */
if (compat20 && auth2_setup_methods_lists(authctxt) != 0) {
/*
* The monitor will continue long enough to let the child
* run to it's packet_disconnect(), but it must not allow any
* authentication to succeed.
*/
debug("%s: no valid authentication method lists", __func__);
}
debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
mm_request_send(sock, MONITOR_ANS_PWNAM, m);
/* For SSHv1 allow authentication now */
if (!compat20)
monitor_permit_authentications(1);
else {
/* Allow service/style information on the auth context */
monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
}
#ifdef USE_PAM
if (options.use_pam)
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
#endif
return (0);
}
int mm_answer_auth2_read_banner(int sock, Buffer *m)
{
char *banner;
buffer_clear(m);
banner = auth2_read_banner();
buffer_put_cstring(m, banner != NULL ? banner : "");
mm_request_send(sock, MONITOR_ANS_AUTH2_READ_BANNER, m);
free(banner);
return (0);
}
int
mm_answer_authserv(int sock, Buffer *m)
{
monitor_permit_authentications(1);
authctxt->service = buffer_get_string(m, NULL);
authctxt->style = buffer_get_string(m, NULL);
debug3("%s: service=%s, style=%s",
__func__, authctxt->service, authctxt->style);
if (strlen(authctxt->style) == 0) {
free(authctxt->style);
authctxt->style = NULL;
}
return (0);
}
int
mm_answer_authpassword(int sock, Buffer *m)
{
static int call_count;
char *passwd;
int authenticated;
u_int plen;
passwd = buffer_get_string(m, &plen);
/* Only authenticate if the context is valid */
authenticated = options.password_authentication &&
auth_password(authctxt, passwd);
explicit_bzero(passwd, strlen(passwd));
free(passwd);
buffer_clear(m);
buffer_put_int(m, authenticated);
debug3("%s: sending result %d", __func__, authenticated);
mm_request_send(sock, MONITOR_ANS_AUTHPASSWORD, m);
call_count++;
if (plen == 0 && call_count == 1)
auth_method = "none";
else
auth_method = "password";
/* Causes monitor loop to terminate if authenticated */
return (authenticated);
}
#ifdef BSD_AUTH
int
mm_answer_bsdauthquery(int sock, Buffer *m)
{
char *name, *infotxt;
u_int numprompts;
u_int *echo_on;
char **prompts;
u_int success;
success = bsdauth_query(authctxt, &name, &infotxt, &numprompts,
&prompts, &echo_on) < 0 ? 0 : 1;
buffer_clear(m);
buffer_put_int(m, success);
if (success)
buffer_put_cstring(m, prompts[0]);
debug3("%s: sending challenge success: %u", __func__, success);
mm_request_send(sock, MONITOR_ANS_BSDAUTHQUERY, m);
if (success) {
free(name);
free(infotxt);
free(prompts);
free(echo_on);
}
return (0);
}
int
mm_answer_bsdauthrespond(int sock, Buffer *m)
{
char *response;
int authok;
if (authctxt->as == 0)
fatal("%s: no bsd auth session", __func__);
response = buffer_get_string(m, NULL);
authok = options.challenge_response_authentication &&
auth_userresponse(authctxt->as, response, 0);
authctxt->as = NULL;
debug3("%s: <%s> = <%d>", __func__, response, authok);
free(response);
buffer_clear(m);
buffer_put_int(m, authok);
debug3("%s: sending authenticated: %d", __func__, authok);
mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
if (compat20) {
auth_method = "keyboard-interactive";
auth_submethod = "bsdauth";
} else
auth_method = "bsdauth";
return (authok != 0);
}
#endif
#ifdef SKEY
int
mm_answer_skeyquery(int sock, Buffer *m)
{
struct skey skey;
char challenge[1024];
u_int success;
success = _compat_skeychallenge(&skey, authctxt->user, challenge,
sizeof(challenge)) < 0 ? 0 : 1;
buffer_clear(m);
buffer_put_int(m, success);
if (success)
buffer_put_cstring(m, challenge);
debug3("%s: sending challenge success: %u", __func__, success);
mm_request_send(sock, MONITOR_ANS_SKEYQUERY, m);
return (0);
}
int
mm_answer_skeyrespond(int sock, Buffer *m)
{
char *response;
int authok;
response = buffer_get_string(m, NULL);
authok = (options.challenge_response_authentication &&
authctxt->valid &&
skey_haskey(authctxt->pw->pw_name) == 0 &&
skey_passcheck(authctxt->pw->pw_name, response) != -1);
free(response);
buffer_clear(m);
buffer_put_int(m, authok);
debug3("%s: sending authenticated: %d", __func__, authok);
mm_request_send(sock, MONITOR_ANS_SKEYRESPOND, m);
auth_method = "skey";
return (authok != 0);
}
#endif
#ifdef USE_PAM
int
mm_answer_pam_start(int sock, Buffer *m)
{
if (!options.use_pam)
fatal("UsePAM not set, but ended up in %s anyway", __func__);
start_pam(authctxt);
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_ACCOUNT, 1);
return (0);
}
int
mm_answer_pam_account(int sock, Buffer *m)
{
u_int ret;
if (!options.use_pam)
fatal("UsePAM not set, but ended up in %s anyway", __func__);
ret = do_pam_account();
buffer_put_int(m, ret);
buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
mm_request_send(sock, MONITOR_ANS_PAM_ACCOUNT, m);
return (ret);
}
static void *sshpam_ctxt, *sshpam_authok;
extern KbdintDevice sshpam_device;
int
mm_answer_pam_init_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
authctxt->user = buffer_get_string(m, NULL);
sshpam_ctxt = (sshpam_device.init_ctx)(authctxt);
sshpam_authok = NULL;
buffer_clear(m);
if (sshpam_ctxt != NULL) {
monitor_permit(mon_dispatch, MONITOR_REQ_PAM_FREE_CTX, 1);
buffer_put_int(m, 1);
} else {
buffer_put_int(m, 0);
}
mm_request_send(sock, MONITOR_ANS_PAM_INIT_CTX, m);
return (0);
}
int
mm_answer_pam_query(int sock, Buffer *m)
{
char *name = NULL, *info = NULL, **prompts = NULL;
u_int i, num = 0, *echo_on = 0;
int ret;
debug3("%s", __func__);
sshpam_authok = NULL;
ret = (sshpam_device.query)(sshpam_ctxt, &name, &info, &num, &prompts, &echo_on);
if (ret == 0 && num == 0)
sshpam_authok = sshpam_ctxt;
if (num > 1 || name == NULL || info == NULL)
ret = -1;
buffer_clear(m);
buffer_put_int(m, ret);
buffer_put_cstring(m, name);
free(name);
buffer_put_cstring(m, info);
free(info);
buffer_put_int(m, num);
for (i = 0; i < num; ++i) {
buffer_put_cstring(m, prompts[i]);
free(prompts[i]);
buffer_put_int(m, echo_on[i]);
}
free(prompts);
free(echo_on);
auth_method = "keyboard-interactive";
auth_submethod = "pam";
mm_request_send(sock, MONITOR_ANS_PAM_QUERY, m);
return (0);
}
int
mm_answer_pam_respond(int sock, Buffer *m)
{
char **resp;
u_int i, num;
int ret;
debug3("%s", __func__);
sshpam_authok = NULL;
num = buffer_get_int(m);
if (num > 0) {
resp = xcalloc(num, sizeof(char *));
for (i = 0; i < num; ++i)
resp[i] = buffer_get_string(m, NULL);
ret = (sshpam_device.respond)(sshpam_ctxt, num, resp);
for (i = 0; i < num; ++i)
free(resp[i]);
free(resp);
} else {
ret = (sshpam_device.respond)(sshpam_ctxt, num, NULL);
}
buffer_clear(m);
buffer_put_int(m, ret);
mm_request_send(sock, MONITOR_ANS_PAM_RESPOND, m);
auth_method = "keyboard-interactive";
auth_submethod = "pam";
if (ret == 0)
sshpam_authok = sshpam_ctxt;
return (0);
}
int
mm_answer_pam_free_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
(sshpam_device.free_ctx)(sshpam_ctxt);
buffer_clear(m);
mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
auth_method = "keyboard-interactive";
auth_submethod = "pam";
return (sshpam_authok == sshpam_ctxt);
}
#endif
int
mm_answer_keyallowed(int sock, Buffer *m)
{
Key *key;
char *cuser, *chost;
u_char *blob;
u_int bloblen, pubkey_auth_attempt;
enum mm_keytype type = 0;
int allowed = 0;
debug3("%s entering", __func__);
type = buffer_get_int(m);
cuser = buffer_get_string(m, NULL);
chost = buffer_get_string(m, NULL);
blob = buffer_get_string(m, &bloblen);
pubkey_auth_attempt = buffer_get_int(m);
key = key_from_blob(blob, bloblen);
if ((compat20 && type == MM_RSAHOSTKEY) ||
(!compat20 && type != MM_RSAHOSTKEY))
fatal("%s: key type and protocol mismatch", __func__);
debug3("%s: key_from_blob: %p", __func__, key);
if (key != NULL && authctxt->valid) {
/* These should not make it past the privsep child */
if (key_type_plain(key->type) == KEY_RSA &&
(datafellows & SSH_BUG_RSASIGMD5) != 0)
fatal("%s: passed a SSH_BUG_RSASIGMD5 key", __func__);
switch (type) {
case MM_USERKEY:
allowed = options.pubkey_authentication &&
!auth2_userkey_already_used(authctxt, key) &&
match_pattern_list(sshkey_ssh_name(key),
options.pubkey_key_types, 0) == 1 &&
user_key_allowed(authctxt->pw, key,
pubkey_auth_attempt);
pubkey_auth_info(authctxt, key, NULL);
auth_method = "publickey";
if (options.pubkey_authentication &&
(!pubkey_auth_attempt || allowed != 1))
auth_clear_options();
break;
case MM_HOSTKEY:
allowed = options.hostbased_authentication &&
match_pattern_list(sshkey_ssh_name(key),
options.hostbased_key_types, 0) == 1 &&
hostbased_key_allowed(authctxt->pw,
cuser, chost, key);
pubkey_auth_info(authctxt, key,
"client user \"%.100s\", client host \"%.100s\"",
cuser, chost);
auth_method = "hostbased";
break;
#ifdef WITH_SSH1
case MM_RSAHOSTKEY:
key->type = KEY_RSA1; /* XXX */
allowed = options.rhosts_rsa_authentication &&
auth_rhosts_rsa_key_allowed(authctxt->pw,
cuser, chost, key);
if (options.rhosts_rsa_authentication && allowed != 1)
auth_clear_options();
auth_method = "rsa";
break;
#endif
default:
fatal("%s: unknown key type %d", __func__, type);
break;
}
}
if (key != NULL)
key_free(key);
/* clear temporarily storage (used by verify) */
monitor_reset_key_state();
if (allowed) {
/* Save temporarily for comparison in verify */
key_blob = blob;
key_bloblen = bloblen;
key_blobtype = type;
hostbased_cuser = cuser;
hostbased_chost = chost;
} else {
/* Log failed attempt */
auth_log(authctxt, 0, 0, auth_method, NULL);
free(blob);
free(cuser);
free(chost);
}
debug3("%s: key %p is %s",
__func__, key, allowed ? "allowed" : "not allowed");
buffer_clear(m);
buffer_put_int(m, allowed);
buffer_put_int(m, forced_command != NULL);
mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
if (type == MM_RSAHOSTKEY)
monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
return (0);
}
static int
monitor_valid_userblob(u_char *data, u_int datalen)
{
Buffer b;
char *p, *userstyle;
u_int len;
int fail = 0;
buffer_init(&b);
buffer_append(&b, data, datalen);
if (datafellows & SSH_OLD_SESSIONID) {
p = buffer_ptr(&b);
len = buffer_len(&b);
if ((session_id2 == NULL) ||
(len < session_id2_len) ||
(timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
fail++;
buffer_consume(&b, session_id2_len);
} else {
p = buffer_get_string(&b, &len);
if ((session_id2 == NULL) ||
(len != session_id2_len) ||
(timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
fail++;
free(p);
}
if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
fail++;
p = buffer_get_cstring(&b, NULL);
xasprintf(&userstyle, "%s%s%s", authctxt->user,
authctxt->style ? ":" : "",
authctxt->style ? authctxt->style : "");
if (strcmp(userstyle, p) != 0) {
logit("wrong user name passed to monitor: expected %s != %.100s",
userstyle, p);
fail++;
}
free(userstyle);
free(p);
buffer_skip_string(&b);
if (datafellows & SSH_BUG_PKAUTH) {
if (!buffer_get_char(&b))
fail++;
} else {
p = buffer_get_cstring(&b, NULL);
if (strcmp("publickey", p) != 0)
fail++;
free(p);
if (!buffer_get_char(&b))
fail++;
buffer_skip_string(&b);
}
buffer_skip_string(&b);
if (buffer_len(&b) != 0)
fail++;
buffer_free(&b);
return (fail == 0);
}
static int
monitor_valid_hostbasedblob(u_char *data, u_int datalen, char *cuser,
char *chost)
{
Buffer b;
char *p, *userstyle;
u_int len;
int fail = 0;
buffer_init(&b);
buffer_append(&b, data, datalen);
p = buffer_get_string(&b, &len);
if ((session_id2 == NULL) ||
(len != session_id2_len) ||
(timingsafe_bcmp(p, session_id2, session_id2_len) != 0))
fail++;
free(p);
if (buffer_get_char(&b) != SSH2_MSG_USERAUTH_REQUEST)
fail++;
p = buffer_get_cstring(&b, NULL);
xasprintf(&userstyle, "%s%s%s", authctxt->user,
authctxt->style ? ":" : "",
authctxt->style ? authctxt->style : "");
if (strcmp(userstyle, p) != 0) {
logit("wrong user name passed to monitor: expected %s != %.100s",
userstyle, p);
fail++;
}
free(userstyle);
free(p);
buffer_skip_string(&b); /* service */
p = buffer_get_cstring(&b, NULL);
if (strcmp(p, "hostbased") != 0)
fail++;
free(p);
buffer_skip_string(&b); /* pkalg */
buffer_skip_string(&b); /* pkblob */
/* verify client host, strip trailing dot if necessary */
p = buffer_get_string(&b, NULL);
if (((len = strlen(p)) > 0) && p[len - 1] == '.')
p[len - 1] = '\0';
if (strcmp(p, chost) != 0)
fail++;
free(p);
/* verify client user */
p = buffer_get_string(&b, NULL);
if (strcmp(p, cuser) != 0)
fail++;
free(p);
if (buffer_len(&b) != 0)
fail++;
buffer_free(&b);
return (fail == 0);
}
int
mm_answer_keyverify(int sock, Buffer *m)
{
Key *key;
u_char *signature, *data, *blob;
u_int signaturelen, datalen, bloblen;
int verified = 0;
int valid_data = 0;
blob = buffer_get_string(m, &bloblen);
signature = buffer_get_string(m, &signaturelen);
data = buffer_get_string(m, &datalen);
if (hostbased_cuser == NULL || hostbased_chost == NULL ||
!monitor_allowed_key(blob, bloblen))
fatal("%s: bad key, not previously allowed", __func__);
key = key_from_blob(blob, bloblen);
if (key == NULL)
fatal("%s: bad public key blob", __func__);
switch (key_blobtype) {
case MM_USERKEY:
valid_data = monitor_valid_userblob(data, datalen);
break;
case MM_HOSTKEY:
valid_data = monitor_valid_hostbasedblob(data, datalen,
hostbased_cuser, hostbased_chost);
break;
default:
valid_data = 0;
break;
}
if (!valid_data)
fatal("%s: bad signature data blob", __func__);
verified = key_verify(key, signature, signaturelen, data, datalen);
debug3("%s: key %p signature %s",
__func__, key, (verified == 1) ? "verified" : "unverified");
/* If auth was successful then record key to ensure it isn't reused */
if (verified == 1)
auth2_record_userkey(authctxt, key);
else
key_free(key);
free(blob);
free(signature);
free(data);
auth_method = key_blobtype == MM_USERKEY ? "publickey" : "hostbased";
monitor_reset_key_state();
buffer_clear(m);
buffer_put_int(m, verified);
mm_request_send(sock, MONITOR_ANS_KEYVERIFY, m);
return (verified == 1);
}
static void
mm_record_login(Session *s, struct passwd *pw)
{
socklen_t fromlen;
struct sockaddr_storage from;
if (options.use_login)
return;
/*
* Get IP address of client. If the connection is not a socket, let
* the address be 0.0.0.0.
*/
memset(&from, 0, sizeof(from));
fromlen = sizeof(from);
if (packet_connection_is_on_socket()) {
if (getpeername(packet_get_connection_in(),
(struct sockaddr *)&from, &fromlen) < 0) {
debug("getpeername: %.100s", strerror(errno));
cleanup_exit(255);
}
}
/* Record that there was a login on that tty from the remote host. */
record_login(s->pid, s->tty, pw->pw_name, pw->pw_uid,
get_remote_name_or_ip(utmp_len, options.use_dns),
(struct sockaddr *)&from, fromlen);
}
static void
mm_session_close(Session *s)
{
debug3("%s: session %d pid %ld", __func__, s->self, (long)s->pid);
if (s->ttyfd != -1) {
debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ptyfd);
session_pty_cleanup2(s);
}
session_unused(s->self);
}
int
mm_answer_pty(int sock, Buffer *m)
{
extern struct monitor *pmonitor;
Session *s;
int res, fd0;
debug3("%s entering", __func__);
buffer_clear(m);
s = session_new();
if (s == NULL)
goto error;
s->authctxt = authctxt;
s->pw = authctxt->pw;
s->pid = pmonitor->m_pid;
res = pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty));
if (res == 0)
goto error;
pty_setowner(authctxt->pw, s->tty);
buffer_put_int(m, 1);
buffer_put_cstring(m, s->tty);
/* We need to trick ttyslot */
if (dup2(s->ttyfd, 0) == -1)
fatal("%s: dup2", __func__);
mm_record_login(s, authctxt->pw);
/* Now we can close the file descriptor again */
close(0);
/* send messages generated by record_login */
buffer_put_string(m, buffer_ptr(&loginmsg), buffer_len(&loginmsg));
buffer_clear(&loginmsg);
mm_request_send(sock, MONITOR_ANS_PTY, m);
if (mm_send_fd(sock, s->ptyfd) == -1 ||
mm_send_fd(sock, s->ttyfd) == -1)
fatal("%s: send fds failed", __func__);
/* make sure nothing uses fd 0 */
if ((fd0 = open(_PATH_DEVNULL, O_RDONLY)) < 0)
fatal("%s: open(/dev/null): %s", __func__, strerror(errno));
if (fd0 != 0)
error("%s: fd0 %d != 0", __func__, fd0);
/* slave is not needed */
close(s->ttyfd);
s->ttyfd = s->ptyfd;
/* no need to dup() because nobody closes ptyfd */
s->ptymaster = s->ptyfd;
debug3("%s: tty %s ptyfd %d", __func__, s->tty, s->ttyfd);
return (0);
error:
if (s != NULL)
mm_session_close(s);
buffer_put_int(m, 0);
mm_request_send(sock, MONITOR_ANS_PTY, m);
return (0);
}
int
mm_answer_pty_cleanup(int sock, Buffer *m)
{
Session *s;
char *tty;
debug3("%s entering", __func__);
tty = buffer_get_string(m, NULL);
if ((s = session_by_tty(tty)) != NULL)
mm_session_close(s);
buffer_clear(m);
free(tty);
return (0);
}
#ifdef WITH_SSH1
int
mm_answer_sesskey(int sock, Buffer *m)
{
BIGNUM *p;
int rsafail;
/* Turn off permissions */
monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0);
if ((p = BN_new()) == NULL)
fatal("%s: BN_new", __func__);
buffer_get_bignum2(m, p);
rsafail = ssh1_session_key(p);
buffer_clear(m);
buffer_put_int(m, rsafail);
buffer_put_bignum2(m, p);
BN_clear_free(p);
mm_request_send(sock, MONITOR_ANS_SESSKEY, m);
/* Turn on permissions for sessid passing */
monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1);
return (0);
}
int
mm_answer_sessid(int sock, Buffer *m)
{
int i;
debug3("%s entering", __func__);
if (buffer_len(m) != 16)
fatal("%s: bad ssh1 session id", __func__);
for (i = 0; i < 16; i++)
session_id[i] = buffer_get_char(m);
/* Turn on permissions for getpwnam */
monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
return (0);
}
int
mm_answer_rsa_keyallowed(int sock, Buffer *m)
{
BIGNUM *client_n;
Key *key = NULL;
u_char *blob = NULL;
u_int blen = 0;
int allowed = 0;
debug3("%s entering", __func__);
auth_method = "rsa";
if (options.rsa_authentication && authctxt->valid) {
if ((client_n = BN_new()) == NULL)
fatal("%s: BN_new", __func__);
buffer_get_bignum2(m, client_n);
allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key);
BN_clear_free(client_n);
}
buffer_clear(m);
buffer_put_int(m, allowed);
buffer_put_int(m, forced_command != NULL);
/* clear temporarily storage (used by generate challenge) */
monitor_reset_key_state();
if (allowed && key != NULL) {
key->type = KEY_RSA; /* cheat for key_to_blob */
if (key_to_blob(key, &blob, &blen) == 0)
fatal("%s: key_to_blob failed", __func__);
buffer_put_string(m, blob, blen);
/* Save temporarily for comparison in verify */
key_blob = blob;
key_bloblen = blen;
key_blobtype = MM_RSAUSERKEY;
}
if (key != NULL)
key_free(key);
mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m);
monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0);
return (0);
}
int
mm_answer_rsa_challenge(int sock, Buffer *m)
{
Key *key = NULL;
u_char *blob;
u_int blen;
debug3("%s entering", __func__);
if (!authctxt->valid)
fatal("%s: authctxt not valid", __func__);
blob = buffer_get_string(m, &blen);
if (!monitor_allowed_key(blob, blen))
fatal("%s: bad key, not previously allowed", __func__);
if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
fatal("%s: key type mismatch", __func__);
if ((key = key_from_blob(blob, blen)) == NULL)
fatal("%s: received bad key", __func__);
if (key->type != KEY_RSA)
fatal("%s: received bad key type %d", __func__, key->type);
key->type = KEY_RSA1;
if (ssh1_challenge)
BN_clear_free(ssh1_challenge);
ssh1_challenge = auth_rsa_generate_challenge(key);
buffer_clear(m);
buffer_put_bignum2(m, ssh1_challenge);
debug3("%s sending reply", __func__);
mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);
monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);
free(blob);
key_free(key);
return (0);
}
int
mm_answer_rsa_response(int sock, Buffer *m)
{
Key *key = NULL;
u_char *blob, *response;
u_int blen, len;
int success;
debug3("%s entering", __func__);
if (!authctxt->valid)
fatal("%s: authctxt not valid", __func__);
if (ssh1_challenge == NULL)
fatal("%s: no ssh1_challenge", __func__);
blob = buffer_get_string(m, &blen);
if (!monitor_allowed_key(blob, blen))
fatal("%s: bad key, not previously allowed", __func__);
if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
fatal("%s: key type mismatch: %d", __func__, key_blobtype);
if ((key = key_from_blob(blob, blen)) == NULL)
fatal("%s: received bad key", __func__);
response = buffer_get_string(m, &len);
if (len != 16)
fatal("%s: received bad response to challenge", __func__);
success = auth_rsa_verify_response(key, ssh1_challenge, response);
free(blob);
key_free(key);
free(response);
auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa";
/* reset state */
BN_clear_free(ssh1_challenge);
ssh1_challenge = NULL;
monitor_reset_key_state();
buffer_clear(m);
buffer_put_int(m, success);
mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m);
return (success);
}
#endif
int
mm_answer_term(int sock, Buffer *req)
{
extern struct monitor *pmonitor;
int res, status;
debug3("%s: tearing down sessions", __func__);
/* The child is terminating */
session_destroy_all(&mm_session_close);
#ifdef USE_PAM
if (options.use_pam)
sshpam_cleanup();
#endif
while (waitpid(pmonitor->m_pid, &status, 0) == -1)
if (errno != EINTR)
exit(1);
res = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
/* Terminate process */
exit(res);
}
#ifdef SSH_AUDIT_EVENTS
/* Report that an audit event occurred */
int
mm_answer_audit_event(int socket, Buffer *m)
{
ssh_audit_event_t event;
debug3("%s entering", __func__);
event = buffer_get_int(m);
switch(event) {
case SSH_AUTH_FAIL_PUBKEY:
case SSH_AUTH_FAIL_HOSTBASED:
case SSH_AUTH_FAIL_GSSAPI:
case SSH_LOGIN_EXCEED_MAXTRIES:
case SSH_LOGIN_ROOT_DENIED:
case SSH_CONNECTION_CLOSE:
case SSH_INVALID_USER:
audit_event(event);
break;
default:
fatal("Audit event type %d not permitted", event);
}
return (0);
}
int
mm_answer_audit_command(int socket, Buffer *m)
{
u_int len;
char *cmd;
debug3("%s entering", __func__);
cmd = buffer_get_string(m, &len);
/* sanity check command, if so how? */
audit_run_command(cmd);
free(cmd);
return (0);
}
#endif /* SSH_AUDIT_EVENTS */
void
monitor_apply_keystate(struct monitor *pmonitor)
{
struct ssh *ssh = active_state; /* XXX */
struct kex *kex;
int r;
debug3("%s: packet_set_state", __func__);
if ((r = ssh_packet_set_state(ssh, child_state)) != 0)
fatal("%s: packet_set_state: %s", __func__, ssh_err(r));
sshbuf_free(child_state);
child_state = NULL;
if ((kex = ssh->kex) != 0) {
/* XXX set callbacks */
#ifdef WITH_OPENSSL
kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
# ifdef OPENSSL_HAS_ECC
kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
# endif
#endif /* WITH_OPENSSL */
kex->kex[KEX_C25519_SHA256] = kexc25519_server;
kex->load_host_public_key=&get_hostkey_public_by_type;
kex->load_host_private_key=&get_hostkey_private_by_type;
kex->host_key_index=&get_hostkey_index;
kex->sign = sshd_hostkey_sign;
}
/* Update with new address */
if (options.compression) {
ssh_packet_set_compress_hooks(ssh, pmonitor->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
}
/* This function requries careful sanity checking */
void
mm_get_keystate(struct monitor *pmonitor)
{
debug3("%s: Waiting for new keys", __func__);
if ((child_state = sshbuf_new()) == NULL)
fatal("%s: sshbuf_new failed", __func__);
mm_request_receive_expect(pmonitor->m_sendfd, MONITOR_REQ_KEYEXPORT,
child_state);
debug3("%s: GOT new keys", __func__);
}
/* XXX */
#define FD_CLOSEONEXEC(x) do { \
if (fcntl(x, F_SETFD, FD_CLOEXEC) == -1) \
fatal("fcntl(%d, F_SETFD)", x); \
} while (0)
static void
monitor_openfds(struct monitor *mon, int do_logfds)
{
int pair[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
fatal("%s: socketpair: %s", __func__, strerror(errno));
FD_CLOSEONEXEC(pair[0]);
FD_CLOSEONEXEC(pair[1]);
mon->m_recvfd = pair[0];
mon->m_sendfd = pair[1];
if (do_logfds) {
if (pipe(pair) == -1)
fatal("%s: pipe: %s", __func__, strerror(errno));
FD_CLOSEONEXEC(pair[0]);
FD_CLOSEONEXEC(pair[1]);
mon->m_log_recvfd = pair[0];
mon->m_log_sendfd = pair[1];
} else
mon->m_log_recvfd = mon->m_log_sendfd = -1;
}
#define MM_MEMSIZE 65536
struct monitor *
monitor_init(void)
{
struct ssh *ssh = active_state; /* XXX */
struct monitor *mon;
mon = xcalloc(1, sizeof(*mon));
monitor_openfds(mon, 1);
/* Used to share zlib space across processes */
if (options.compression) {
mon->m_zback = mm_create(NULL, MM_MEMSIZE);
mon->m_zlib = mm_create(mon->m_zback, 20 * MM_MEMSIZE);
/* Compression needs to share state across borders */
ssh_packet_set_compress_hooks(ssh, mon->m_zlib,
(ssh_packet_comp_alloc_func *)mm_zalloc,
(ssh_packet_comp_free_func *)mm_zfree);
}
return mon;
}
void
monitor_reinit(struct monitor *mon)
{
monitor_openfds(mon, 0);
}
#ifdef GSSAPI
int
mm_answer_gss_setup_ctx(int sock, Buffer *m)
{
gss_OID_desc goid;
OM_uint32 major;
u_int len;
goid.elements = buffer_get_string(m, &len);
goid.length = len;
major = ssh_gssapi_server_ctx(&gsscontext, &goid);
free(goid.elements);
buffer_clear(m);
buffer_put_int(m, major);
mm_request_send(sock, MONITOR_ANS_GSSSETUP, m);
/* Now we have a context, enable the step */
monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 1);
return (0);
}
int
mm_answer_gss_accept_ctx(int sock, Buffer *m)
{
gss_buffer_desc in;
gss_buffer_desc out = GSS_C_EMPTY_BUFFER;
OM_uint32 major, minor;
OM_uint32 flags = 0; /* GSI needs this */
u_int len;
in.value = buffer_get_string(m, &len);
in.length = len;
major = ssh_gssapi_accept_ctx(gsscontext, &in, &out, &flags);
free(in.value);
buffer_clear(m);
buffer_put_int(m, major);
buffer_put_string(m, out.value, out.length);
buffer_put_int(m, flags);
mm_request_send(sock, MONITOR_ANS_GSSSTEP, m);
gss_release_buffer(&minor, &out);
if (major == GSS_S_COMPLETE) {
monitor_permit(mon_dispatch, MONITOR_REQ_GSSSTEP, 0);
monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
monitor_permit(mon_dispatch, MONITOR_REQ_GSSCHECKMIC, 1);
}
return (0);
}
int
mm_answer_gss_checkmic(int sock, Buffer *m)
{
gss_buffer_desc gssbuf, mic;
OM_uint32 ret;
u_int len;
gssbuf.value = buffer_get_string(m, &len);
gssbuf.length = len;
mic.value = buffer_get_string(m, &len);
mic.length = len;
ret = ssh_gssapi_checkmic(gsscontext, &gssbuf, &mic);
free(gssbuf.value);
free(mic.value);
buffer_clear(m);
buffer_put_int(m, ret);
mm_request_send(sock, MONITOR_ANS_GSSCHECKMIC, m);
if (!GSS_ERROR(ret))
monitor_permit(mon_dispatch, MONITOR_REQ_GSSUSEROK, 1);
return (0);
}
int
mm_answer_gss_userok(int sock, Buffer *m)
{
int authenticated;
authenticated = authctxt->valid && ssh_gssapi_userok(authctxt->user);
buffer_clear(m);
buffer_put_int(m, authenticated);
debug3("%s: sending result %d", __func__, authenticated);
mm_request_send(sock, MONITOR_ANS_GSSUSEROK, m);
auth_method = "gssapi-with-mic";
/* Monitor loop will terminate if authenticated */
return (authenticated);
}
#endif /* GSSAPI */
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1718_0 |
crossvul-cpp_data_good_5794_2 | /*
* Kernel-based Virtual Machine driver for Linux
*
* derived from drivers/kvm/kvm_main.c
*
* Copyright (C) 2006 Qumranet, Inc.
* Copyright (C) 2008 Qumranet, Inc.
* Copyright IBM Corporation, 2008
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* Authors:
* Avi Kivity <avi@qumranet.com>
* Yaniv Kamay <yaniv@qumranet.com>
* Amit Shah <amit.shah@qumranet.com>
* Ben-Ami Yassour <benami@il.ibm.com>
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
*/
#include <linux/kvm_host.h>
#include "irq.h"
#include "mmu.h"
#include "i8254.h"
#include "tss.h"
#include "kvm_cache_regs.h"
#include "x86.h"
#include "cpuid.h"
#include <linux/clocksource.h>
#include <linux/interrupt.h>
#include <linux/kvm.h>
#include <linux/fs.h>
#include <linux/vmalloc.h>
#include <linux/module.h>
#include <linux/mman.h>
#include <linux/highmem.h>
#include <linux/iommu.h>
#include <linux/intel-iommu.h>
#include <linux/cpufreq.h>
#include <linux/user-return-notifier.h>
#include <linux/srcu.h>
#include <linux/slab.h>
#include <linux/perf_event.h>
#include <linux/uaccess.h>
#include <linux/hash.h>
#include <linux/pci.h>
#include <linux/timekeeper_internal.h>
#include <linux/pvclock_gtod.h>
#include <trace/events/kvm.h>
#define CREATE_TRACE_POINTS
#include "trace.h"
#include <asm/debugreg.h>
#include <asm/msr.h>
#include <asm/desc.h>
#include <asm/mtrr.h>
#include <asm/mce.h>
#include <asm/i387.h>
#include <asm/fpu-internal.h> /* Ugh! */
#include <asm/xcr.h>
#include <asm/pvclock.h>
#include <asm/div64.h>
#define MAX_IO_MSRS 256
#define KVM_MAX_MCE_BANKS 32
#define KVM_MCE_CAP_SUPPORTED (MCG_CTL_P | MCG_SER_P)
#define emul_to_vcpu(ctxt) \
container_of(ctxt, struct kvm_vcpu, arch.emulate_ctxt)
/* EFER defaults:
* - enable syscall per default because its emulated by KVM
* - enable LME and LMA per default on 64 bit KVM
*/
#ifdef CONFIG_X86_64
static
u64 __read_mostly efer_reserved_bits = ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
#else
static u64 __read_mostly efer_reserved_bits = ~((u64)EFER_SCE);
#endif
#define VM_STAT(x) offsetof(struct kvm, stat.x), KVM_STAT_VM
#define VCPU_STAT(x) offsetof(struct kvm_vcpu, stat.x), KVM_STAT_VCPU
static void update_cr8_intercept(struct kvm_vcpu *vcpu);
static void process_nmi(struct kvm_vcpu *vcpu);
struct kvm_x86_ops *kvm_x86_ops;
EXPORT_SYMBOL_GPL(kvm_x86_ops);
static bool ignore_msrs = 0;
module_param(ignore_msrs, bool, S_IRUGO | S_IWUSR);
bool kvm_has_tsc_control;
EXPORT_SYMBOL_GPL(kvm_has_tsc_control);
u32 kvm_max_guest_tsc_khz;
EXPORT_SYMBOL_GPL(kvm_max_guest_tsc_khz);
/* tsc tolerance in parts per million - default to 1/2 of the NTP threshold */
static u32 tsc_tolerance_ppm = 250;
module_param(tsc_tolerance_ppm, uint, S_IRUGO | S_IWUSR);
#define KVM_NR_SHARED_MSRS 16
struct kvm_shared_msrs_global {
int nr;
u32 msrs[KVM_NR_SHARED_MSRS];
};
struct kvm_shared_msrs {
struct user_return_notifier urn;
bool registered;
struct kvm_shared_msr_values {
u64 host;
u64 curr;
} values[KVM_NR_SHARED_MSRS];
};
static struct kvm_shared_msrs_global __read_mostly shared_msrs_global;
static struct kvm_shared_msrs __percpu *shared_msrs;
struct kvm_stats_debugfs_item debugfs_entries[] = {
{ "pf_fixed", VCPU_STAT(pf_fixed) },
{ "pf_guest", VCPU_STAT(pf_guest) },
{ "tlb_flush", VCPU_STAT(tlb_flush) },
{ "invlpg", VCPU_STAT(invlpg) },
{ "exits", VCPU_STAT(exits) },
{ "io_exits", VCPU_STAT(io_exits) },
{ "mmio_exits", VCPU_STAT(mmio_exits) },
{ "signal_exits", VCPU_STAT(signal_exits) },
{ "irq_window", VCPU_STAT(irq_window_exits) },
{ "nmi_window", VCPU_STAT(nmi_window_exits) },
{ "halt_exits", VCPU_STAT(halt_exits) },
{ "halt_wakeup", VCPU_STAT(halt_wakeup) },
{ "hypercalls", VCPU_STAT(hypercalls) },
{ "request_irq", VCPU_STAT(request_irq_exits) },
{ "irq_exits", VCPU_STAT(irq_exits) },
{ "host_state_reload", VCPU_STAT(host_state_reload) },
{ "efer_reload", VCPU_STAT(efer_reload) },
{ "fpu_reload", VCPU_STAT(fpu_reload) },
{ "insn_emulation", VCPU_STAT(insn_emulation) },
{ "insn_emulation_fail", VCPU_STAT(insn_emulation_fail) },
{ "irq_injections", VCPU_STAT(irq_injections) },
{ "nmi_injections", VCPU_STAT(nmi_injections) },
{ "mmu_shadow_zapped", VM_STAT(mmu_shadow_zapped) },
{ "mmu_pte_write", VM_STAT(mmu_pte_write) },
{ "mmu_pte_updated", VM_STAT(mmu_pte_updated) },
{ "mmu_pde_zapped", VM_STAT(mmu_pde_zapped) },
{ "mmu_flooded", VM_STAT(mmu_flooded) },
{ "mmu_recycled", VM_STAT(mmu_recycled) },
{ "mmu_cache_miss", VM_STAT(mmu_cache_miss) },
{ "mmu_unsync", VM_STAT(mmu_unsync) },
{ "remote_tlb_flush", VM_STAT(remote_tlb_flush) },
{ "largepages", VM_STAT(lpages) },
{ NULL }
};
u64 __read_mostly host_xcr0;
static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt);
static inline void kvm_async_pf_hash_reset(struct kvm_vcpu *vcpu)
{
int i;
for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU); i++)
vcpu->arch.apf.gfns[i] = ~0;
}
static void kvm_on_user_return(struct user_return_notifier *urn)
{
unsigned slot;
struct kvm_shared_msrs *locals
= container_of(urn, struct kvm_shared_msrs, urn);
struct kvm_shared_msr_values *values;
for (slot = 0; slot < shared_msrs_global.nr; ++slot) {
values = &locals->values[slot];
if (values->host != values->curr) {
wrmsrl(shared_msrs_global.msrs[slot], values->host);
values->curr = values->host;
}
}
locals->registered = false;
user_return_notifier_unregister(urn);
}
static void shared_msr_update(unsigned slot, u32 msr)
{
u64 value;
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
/* only read, and nobody should modify it at this time,
* so don't need lock */
if (slot >= shared_msrs_global.nr) {
printk(KERN_ERR "kvm: invalid MSR slot!");
return;
}
rdmsrl_safe(msr, &value);
smsr->values[slot].host = value;
smsr->values[slot].curr = value;
}
void kvm_define_shared_msr(unsigned slot, u32 msr)
{
if (slot >= shared_msrs_global.nr)
shared_msrs_global.nr = slot + 1;
shared_msrs_global.msrs[slot] = msr;
/* we need ensured the shared_msr_global have been updated */
smp_wmb();
}
EXPORT_SYMBOL_GPL(kvm_define_shared_msr);
static void kvm_shared_msr_cpu_online(void)
{
unsigned i;
for (i = 0; i < shared_msrs_global.nr; ++i)
shared_msr_update(i, shared_msrs_global.msrs[i]);
}
void kvm_set_shared_msr(unsigned slot, u64 value, u64 mask)
{
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
if (((value ^ smsr->values[slot].curr) & mask) == 0)
return;
smsr->values[slot].curr = value;
wrmsrl(shared_msrs_global.msrs[slot], value);
if (!smsr->registered) {
smsr->urn.on_user_return = kvm_on_user_return;
user_return_notifier_register(&smsr->urn);
smsr->registered = true;
}
}
EXPORT_SYMBOL_GPL(kvm_set_shared_msr);
static void drop_user_return_notifiers(void *ignore)
{
unsigned int cpu = smp_processor_id();
struct kvm_shared_msrs *smsr = per_cpu_ptr(shared_msrs, cpu);
if (smsr->registered)
kvm_on_user_return(&smsr->urn);
}
u64 kvm_get_apic_base(struct kvm_vcpu *vcpu)
{
return vcpu->arch.apic_base;
}
EXPORT_SYMBOL_GPL(kvm_get_apic_base);
void kvm_set_apic_base(struct kvm_vcpu *vcpu, u64 data)
{
/* TODO: reserve bits check */
kvm_lapic_set_base(vcpu, data);
}
EXPORT_SYMBOL_GPL(kvm_set_apic_base);
asmlinkage void kvm_spurious_fault(void)
{
/* Fault while not rebooting. We want the trace. */
BUG();
}
EXPORT_SYMBOL_GPL(kvm_spurious_fault);
#define EXCPT_BENIGN 0
#define EXCPT_CONTRIBUTORY 1
#define EXCPT_PF 2
static int exception_class(int vector)
{
switch (vector) {
case PF_VECTOR:
return EXCPT_PF;
case DE_VECTOR:
case TS_VECTOR:
case NP_VECTOR:
case SS_VECTOR:
case GP_VECTOR:
return EXCPT_CONTRIBUTORY;
default:
break;
}
return EXCPT_BENIGN;
}
static void kvm_multiple_exception(struct kvm_vcpu *vcpu,
unsigned nr, bool has_error, u32 error_code,
bool reinject)
{
u32 prev_nr;
int class1, class2;
kvm_make_request(KVM_REQ_EVENT, vcpu);
if (!vcpu->arch.exception.pending) {
queue:
vcpu->arch.exception.pending = true;
vcpu->arch.exception.has_error_code = has_error;
vcpu->arch.exception.nr = nr;
vcpu->arch.exception.error_code = error_code;
vcpu->arch.exception.reinject = reinject;
return;
}
/* to check exception */
prev_nr = vcpu->arch.exception.nr;
if (prev_nr == DF_VECTOR) {
/* triple fault -> shutdown */
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return;
}
class1 = exception_class(prev_nr);
class2 = exception_class(nr);
if ((class1 == EXCPT_CONTRIBUTORY && class2 == EXCPT_CONTRIBUTORY)
|| (class1 == EXCPT_PF && class2 != EXCPT_BENIGN)) {
/* generate double fault per SDM Table 5-5 */
vcpu->arch.exception.pending = true;
vcpu->arch.exception.has_error_code = true;
vcpu->arch.exception.nr = DF_VECTOR;
vcpu->arch.exception.error_code = 0;
} else
/* replace previous exception with a new one in a hope
that instruction re-execution will regenerate lost
exception */
goto queue;
}
void kvm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
kvm_multiple_exception(vcpu, nr, false, 0, false);
}
EXPORT_SYMBOL_GPL(kvm_queue_exception);
void kvm_requeue_exception(struct kvm_vcpu *vcpu, unsigned nr)
{
kvm_multiple_exception(vcpu, nr, false, 0, true);
}
EXPORT_SYMBOL_GPL(kvm_requeue_exception);
void kvm_complete_insn_gp(struct kvm_vcpu *vcpu, int err)
{
if (err)
kvm_inject_gp(vcpu, 0);
else
kvm_x86_ops->skip_emulated_instruction(vcpu);
}
EXPORT_SYMBOL_GPL(kvm_complete_insn_gp);
void kvm_inject_page_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
{
++vcpu->stat.pf_guest;
vcpu->arch.cr2 = fault->address;
kvm_queue_exception_e(vcpu, PF_VECTOR, fault->error_code);
}
EXPORT_SYMBOL_GPL(kvm_inject_page_fault);
void kvm_propagate_fault(struct kvm_vcpu *vcpu, struct x86_exception *fault)
{
if (mmu_is_nested(vcpu) && !fault->nested_page_fault)
vcpu->arch.nested_mmu.inject_page_fault(vcpu, fault);
else
vcpu->arch.mmu.inject_page_fault(vcpu, fault);
}
void kvm_inject_nmi(struct kvm_vcpu *vcpu)
{
atomic_inc(&vcpu->arch.nmi_queued);
kvm_make_request(KVM_REQ_NMI, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_inject_nmi);
void kvm_queue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
{
kvm_multiple_exception(vcpu, nr, true, error_code, false);
}
EXPORT_SYMBOL_GPL(kvm_queue_exception_e);
void kvm_requeue_exception_e(struct kvm_vcpu *vcpu, unsigned nr, u32 error_code)
{
kvm_multiple_exception(vcpu, nr, true, error_code, true);
}
EXPORT_SYMBOL_GPL(kvm_requeue_exception_e);
/*
* Checks if cpl <= required_cpl; if true, return true. Otherwise queue
* a #GP and return false.
*/
bool kvm_require_cpl(struct kvm_vcpu *vcpu, int required_cpl)
{
if (kvm_x86_ops->get_cpl(vcpu) <= required_cpl)
return true;
kvm_queue_exception_e(vcpu, GP_VECTOR, 0);
return false;
}
EXPORT_SYMBOL_GPL(kvm_require_cpl);
/*
* This function will be used to read from the physical memory of the currently
* running guest. The difference to kvm_read_guest_page is that this function
* can read from guest physical or from the guest's guest physical memory.
*/
int kvm_read_guest_page_mmu(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu,
gfn_t ngfn, void *data, int offset, int len,
u32 access)
{
gfn_t real_gfn;
gpa_t ngpa;
ngpa = gfn_to_gpa(ngfn);
real_gfn = mmu->translate_gpa(vcpu, ngpa, access);
if (real_gfn == UNMAPPED_GVA)
return -EFAULT;
real_gfn = gpa_to_gfn(real_gfn);
return kvm_read_guest_page(vcpu->kvm, real_gfn, data, offset, len);
}
EXPORT_SYMBOL_GPL(kvm_read_guest_page_mmu);
int kvm_read_nested_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
void *data, int offset, int len, u32 access)
{
return kvm_read_guest_page_mmu(vcpu, vcpu->arch.walk_mmu, gfn,
data, offset, len, access);
}
/*
* Load the pae pdptrs. Return true is they are all valid.
*/
int load_pdptrs(struct kvm_vcpu *vcpu, struct kvm_mmu *mmu, unsigned long cr3)
{
gfn_t pdpt_gfn = cr3 >> PAGE_SHIFT;
unsigned offset = ((cr3 & (PAGE_SIZE-1)) >> 5) << 2;
int i;
int ret;
u64 pdpte[ARRAY_SIZE(mmu->pdptrs)];
ret = kvm_read_guest_page_mmu(vcpu, mmu, pdpt_gfn, pdpte,
offset * sizeof(u64), sizeof(pdpte),
PFERR_USER_MASK|PFERR_WRITE_MASK);
if (ret < 0) {
ret = 0;
goto out;
}
for (i = 0; i < ARRAY_SIZE(pdpte); ++i) {
if (is_present_gpte(pdpte[i]) &&
(pdpte[i] & vcpu->arch.mmu.rsvd_bits_mask[0][2])) {
ret = 0;
goto out;
}
}
ret = 1;
memcpy(mmu->pdptrs, pdpte, sizeof(mmu->pdptrs));
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail);
__set_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_dirty);
out:
return ret;
}
EXPORT_SYMBOL_GPL(load_pdptrs);
static bool pdptrs_changed(struct kvm_vcpu *vcpu)
{
u64 pdpte[ARRAY_SIZE(vcpu->arch.walk_mmu->pdptrs)];
bool changed = true;
int offset;
gfn_t gfn;
int r;
if (is_long_mode(vcpu) || !is_pae(vcpu))
return false;
if (!test_bit(VCPU_EXREG_PDPTR,
(unsigned long *)&vcpu->arch.regs_avail))
return true;
gfn = (kvm_read_cr3(vcpu) & ~31u) >> PAGE_SHIFT;
offset = (kvm_read_cr3(vcpu) & ~31u) & (PAGE_SIZE - 1);
r = kvm_read_nested_guest_page(vcpu, gfn, pdpte, offset, sizeof(pdpte),
PFERR_USER_MASK | PFERR_WRITE_MASK);
if (r < 0)
goto out;
changed = memcmp(pdpte, vcpu->arch.walk_mmu->pdptrs, sizeof(pdpte)) != 0;
out:
return changed;
}
int kvm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
{
unsigned long old_cr0 = kvm_read_cr0(vcpu);
unsigned long update_bits = X86_CR0_PG | X86_CR0_WP |
X86_CR0_CD | X86_CR0_NW;
cr0 |= X86_CR0_ET;
#ifdef CONFIG_X86_64
if (cr0 & 0xffffffff00000000UL)
return 1;
#endif
cr0 &= ~CR0_RESERVED_BITS;
if ((cr0 & X86_CR0_NW) && !(cr0 & X86_CR0_CD))
return 1;
if ((cr0 & X86_CR0_PG) && !(cr0 & X86_CR0_PE))
return 1;
if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
#ifdef CONFIG_X86_64
if ((vcpu->arch.efer & EFER_LME)) {
int cs_db, cs_l;
if (!is_pae(vcpu))
return 1;
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
if (cs_l)
return 1;
} else
#endif
if (is_pae(vcpu) && !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
kvm_read_cr3(vcpu)))
return 1;
}
if (!(cr0 & X86_CR0_PG) && kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE))
return 1;
kvm_x86_ops->set_cr0(vcpu, cr0);
if ((cr0 ^ old_cr0) & X86_CR0_PG) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
}
if ((cr0 ^ old_cr0) & update_bits)
kvm_mmu_reset_context(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr0);
void kvm_lmsw(struct kvm_vcpu *vcpu, unsigned long msw)
{
(void)kvm_set_cr0(vcpu, kvm_read_cr0_bits(vcpu, ~0x0eul) | (msw & 0x0f));
}
EXPORT_SYMBOL_GPL(kvm_lmsw);
static void kvm_load_guest_xcr0(struct kvm_vcpu *vcpu)
{
if (kvm_read_cr4_bits(vcpu, X86_CR4_OSXSAVE) &&
!vcpu->guest_xcr0_loaded) {
/* kvm_set_xcr() also depends on this */
xsetbv(XCR_XFEATURE_ENABLED_MASK, vcpu->arch.xcr0);
vcpu->guest_xcr0_loaded = 1;
}
}
static void kvm_put_guest_xcr0(struct kvm_vcpu *vcpu)
{
if (vcpu->guest_xcr0_loaded) {
if (vcpu->arch.xcr0 != host_xcr0)
xsetbv(XCR_XFEATURE_ENABLED_MASK, host_xcr0);
vcpu->guest_xcr0_loaded = 0;
}
}
int __kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
{
u64 xcr0;
u64 valid_bits;
/* Only support XCR_XFEATURE_ENABLED_MASK(xcr0) now */
if (index != XCR_XFEATURE_ENABLED_MASK)
return 1;
xcr0 = xcr;
if (!(xcr0 & XSTATE_FP))
return 1;
if ((xcr0 & XSTATE_YMM) && !(xcr0 & XSTATE_SSE))
return 1;
/*
* Do not allow the guest to set bits that we do not support
* saving. However, xcr0 bit 0 is always set, even if the
* emulated CPU does not support XSAVE (see fx_init).
*/
valid_bits = vcpu->arch.guest_supported_xcr0 | XSTATE_FP;
if (xcr0 & ~valid_bits)
return 1;
kvm_put_guest_xcr0(vcpu);
vcpu->arch.xcr0 = xcr0;
return 0;
}
int kvm_set_xcr(struct kvm_vcpu *vcpu, u32 index, u64 xcr)
{
if (kvm_x86_ops->get_cpl(vcpu) != 0 ||
__kvm_set_xcr(vcpu, index, xcr)) {
kvm_inject_gp(vcpu, 0);
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_xcr);
int kvm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
{
unsigned long old_cr4 = kvm_read_cr4(vcpu);
unsigned long pdptr_bits = X86_CR4_PGE | X86_CR4_PSE |
X86_CR4_PAE | X86_CR4_SMEP;
if (cr4 & CR4_RESERVED_BITS)
return 1;
if (!guest_cpuid_has_xsave(vcpu) && (cr4 & X86_CR4_OSXSAVE))
return 1;
if (!guest_cpuid_has_smep(vcpu) && (cr4 & X86_CR4_SMEP))
return 1;
if (!guest_cpuid_has_fsgsbase(vcpu) && (cr4 & X86_CR4_FSGSBASE))
return 1;
if (is_long_mode(vcpu)) {
if (!(cr4 & X86_CR4_PAE))
return 1;
} else if (is_paging(vcpu) && (cr4 & X86_CR4_PAE)
&& ((cr4 ^ old_cr4) & pdptr_bits)
&& !load_pdptrs(vcpu, vcpu->arch.walk_mmu,
kvm_read_cr3(vcpu)))
return 1;
if ((cr4 & X86_CR4_PCIDE) && !(old_cr4 & X86_CR4_PCIDE)) {
if (!guest_cpuid_has_pcid(vcpu))
return 1;
/* PCID can not be enabled when cr3[11:0]!=000H or EFER.LMA=0 */
if ((kvm_read_cr3(vcpu) & X86_CR3_PCID_MASK) || !is_long_mode(vcpu))
return 1;
}
if (kvm_x86_ops->set_cr4(vcpu, cr4))
return 1;
if (((cr4 ^ old_cr4) & pdptr_bits) ||
(!(cr4 & X86_CR4_PCIDE) && (old_cr4 & X86_CR4_PCIDE)))
kvm_mmu_reset_context(vcpu);
if ((cr4 ^ old_cr4) & X86_CR4_OSXSAVE)
kvm_update_cpuid(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr4);
int kvm_set_cr3(struct kvm_vcpu *vcpu, unsigned long cr3)
{
if (cr3 == kvm_read_cr3(vcpu) && !pdptrs_changed(vcpu)) {
kvm_mmu_sync_roots(vcpu);
kvm_mmu_flush_tlb(vcpu);
return 0;
}
if (is_long_mode(vcpu)) {
if (kvm_read_cr4_bits(vcpu, X86_CR4_PCIDE)) {
if (cr3 & CR3_PCID_ENABLED_RESERVED_BITS)
return 1;
} else
if (cr3 & CR3_L_MODE_RESERVED_BITS)
return 1;
} else {
if (is_pae(vcpu)) {
if (cr3 & CR3_PAE_RESERVED_BITS)
return 1;
if (is_paging(vcpu) &&
!load_pdptrs(vcpu, vcpu->arch.walk_mmu, cr3))
return 1;
}
/*
* We don't check reserved bits in nonpae mode, because
* this isn't enforced, and VMware depends on this.
*/
}
vcpu->arch.cr3 = cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
kvm_mmu_new_cr3(vcpu);
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr3);
int kvm_set_cr8(struct kvm_vcpu *vcpu, unsigned long cr8)
{
if (cr8 & CR8_RESERVED_BITS)
return 1;
if (irqchip_in_kernel(vcpu->kvm))
kvm_lapic_set_tpr(vcpu, cr8);
else
vcpu->arch.cr8 = cr8;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_cr8);
unsigned long kvm_get_cr8(struct kvm_vcpu *vcpu)
{
if (irqchip_in_kernel(vcpu->kvm))
return kvm_lapic_get_cr8(vcpu);
else
return vcpu->arch.cr8;
}
EXPORT_SYMBOL_GPL(kvm_get_cr8);
static void kvm_update_dr7(struct kvm_vcpu *vcpu)
{
unsigned long dr7;
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP)
dr7 = vcpu->arch.guest_debug_dr7;
else
dr7 = vcpu->arch.dr7;
kvm_x86_ops->set_dr7(vcpu, dr7);
vcpu->arch.switch_db_regs = (dr7 & DR7_BP_EN_MASK);
}
static int __kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
{
switch (dr) {
case 0 ... 3:
vcpu->arch.db[dr] = val;
if (!(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP))
vcpu->arch.eff_db[dr] = val;
break;
case 4:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1; /* #UD */
/* fall through */
case 6:
if (val & 0xffffffff00000000ULL)
return -1; /* #GP */
vcpu->arch.dr6 = (val & DR6_VOLATILE) | DR6_FIXED_1;
break;
case 5:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1; /* #UD */
/* fall through */
default: /* 7 */
if (val & 0xffffffff00000000ULL)
return -1; /* #GP */
vcpu->arch.dr7 = (val & DR7_VOLATILE) | DR7_FIXED_1;
kvm_update_dr7(vcpu);
break;
}
return 0;
}
int kvm_set_dr(struct kvm_vcpu *vcpu, int dr, unsigned long val)
{
int res;
res = __kvm_set_dr(vcpu, dr, val);
if (res > 0)
kvm_queue_exception(vcpu, UD_VECTOR);
else if (res < 0)
kvm_inject_gp(vcpu, 0);
return res;
}
EXPORT_SYMBOL_GPL(kvm_set_dr);
static int _kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
{
switch (dr) {
case 0 ... 3:
*val = vcpu->arch.db[dr];
break;
case 4:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1;
/* fall through */
case 6:
*val = vcpu->arch.dr6;
break;
case 5:
if (kvm_read_cr4_bits(vcpu, X86_CR4_DE))
return 1;
/* fall through */
default: /* 7 */
*val = vcpu->arch.dr7;
break;
}
return 0;
}
int kvm_get_dr(struct kvm_vcpu *vcpu, int dr, unsigned long *val)
{
if (_kvm_get_dr(vcpu, dr, val)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 1;
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_get_dr);
bool kvm_rdpmc(struct kvm_vcpu *vcpu)
{
u32 ecx = kvm_register_read(vcpu, VCPU_REGS_RCX);
u64 data;
int err;
err = kvm_pmu_read_pmc(vcpu, ecx, &data);
if (err)
return err;
kvm_register_write(vcpu, VCPU_REGS_RAX, (u32)data);
kvm_register_write(vcpu, VCPU_REGS_RDX, data >> 32);
return err;
}
EXPORT_SYMBOL_GPL(kvm_rdpmc);
/*
* List of msr numbers which we expose to userspace through KVM_GET_MSRS
* and KVM_SET_MSRS, and KVM_GET_MSR_INDEX_LIST.
*
* This list is modified at module load time to reflect the
* capabilities of the host cpu. This capabilities test skips MSRs that are
* kvm-specific. Those are put in the beginning of the list.
*/
#define KVM_SAVE_MSRS_BEGIN 10
static u32 msrs_to_save[] = {
MSR_KVM_SYSTEM_TIME, MSR_KVM_WALL_CLOCK,
MSR_KVM_SYSTEM_TIME_NEW, MSR_KVM_WALL_CLOCK_NEW,
HV_X64_MSR_GUEST_OS_ID, HV_X64_MSR_HYPERCALL,
HV_X64_MSR_APIC_ASSIST_PAGE, MSR_KVM_ASYNC_PF_EN, MSR_KVM_STEAL_TIME,
MSR_KVM_PV_EOI_EN,
MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
MSR_STAR,
#ifdef CONFIG_X86_64
MSR_CSTAR, MSR_KERNEL_GS_BASE, MSR_SYSCALL_MASK, MSR_LSTAR,
#endif
MSR_IA32_TSC, MSR_IA32_CR_PAT, MSR_VM_HSAVE_PA,
MSR_IA32_FEATURE_CONTROL
};
static unsigned num_msrs_to_save;
static const u32 emulated_msrs[] = {
MSR_IA32_TSC_ADJUST,
MSR_IA32_TSCDEADLINE,
MSR_IA32_MISC_ENABLE,
MSR_IA32_MCG_STATUS,
MSR_IA32_MCG_CTL,
};
bool kvm_valid_efer(struct kvm_vcpu *vcpu, u64 efer)
{
if (efer & efer_reserved_bits)
return false;
if (efer & EFER_FFXSR) {
struct kvm_cpuid_entry2 *feat;
feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
if (!feat || !(feat->edx & bit(X86_FEATURE_FXSR_OPT)))
return false;
}
if (efer & EFER_SVME) {
struct kvm_cpuid_entry2 *feat;
feat = kvm_find_cpuid_entry(vcpu, 0x80000001, 0);
if (!feat || !(feat->ecx & bit(X86_FEATURE_SVM)))
return false;
}
return true;
}
EXPORT_SYMBOL_GPL(kvm_valid_efer);
static int set_efer(struct kvm_vcpu *vcpu, u64 efer)
{
u64 old_efer = vcpu->arch.efer;
if (!kvm_valid_efer(vcpu, efer))
return 1;
if (is_paging(vcpu)
&& (vcpu->arch.efer & EFER_LME) != (efer & EFER_LME))
return 1;
efer &= ~EFER_LMA;
efer |= vcpu->arch.efer & EFER_LMA;
kvm_x86_ops->set_efer(vcpu, efer);
/* Update reserved bits */
if ((efer ^ old_efer) & EFER_NX)
kvm_mmu_reset_context(vcpu);
return 0;
}
void kvm_enable_efer_bits(u64 mask)
{
efer_reserved_bits &= ~mask;
}
EXPORT_SYMBOL_GPL(kvm_enable_efer_bits);
/*
* Writes msr value into into the appropriate "register".
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
int kvm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
{
return kvm_x86_ops->set_msr(vcpu, msr);
}
/*
* Adapt set_msr() to msr_io()'s calling convention
*/
static int do_set_msr(struct kvm_vcpu *vcpu, unsigned index, u64 *data)
{
struct msr_data msr;
msr.data = *data;
msr.index = index;
msr.host_initiated = true;
return kvm_set_msr(vcpu, &msr);
}
#ifdef CONFIG_X86_64
struct pvclock_gtod_data {
seqcount_t seq;
struct { /* extract of a clocksource struct */
int vclock_mode;
cycle_t cycle_last;
cycle_t mask;
u32 mult;
u32 shift;
} clock;
/* open coded 'struct timespec' */
u64 monotonic_time_snsec;
time_t monotonic_time_sec;
};
static struct pvclock_gtod_data pvclock_gtod_data;
static void update_pvclock_gtod(struct timekeeper *tk)
{
struct pvclock_gtod_data *vdata = &pvclock_gtod_data;
write_seqcount_begin(&vdata->seq);
/* copy pvclock gtod data */
vdata->clock.vclock_mode = tk->clock->archdata.vclock_mode;
vdata->clock.cycle_last = tk->clock->cycle_last;
vdata->clock.mask = tk->clock->mask;
vdata->clock.mult = tk->mult;
vdata->clock.shift = tk->shift;
vdata->monotonic_time_sec = tk->xtime_sec
+ tk->wall_to_monotonic.tv_sec;
vdata->monotonic_time_snsec = tk->xtime_nsec
+ (tk->wall_to_monotonic.tv_nsec
<< tk->shift);
while (vdata->monotonic_time_snsec >=
(((u64)NSEC_PER_SEC) << tk->shift)) {
vdata->monotonic_time_snsec -=
((u64)NSEC_PER_SEC) << tk->shift;
vdata->monotonic_time_sec++;
}
write_seqcount_end(&vdata->seq);
}
#endif
static void kvm_write_wall_clock(struct kvm *kvm, gpa_t wall_clock)
{
int version;
int r;
struct pvclock_wall_clock wc;
struct timespec boot;
if (!wall_clock)
return;
r = kvm_read_guest(kvm, wall_clock, &version, sizeof(version));
if (r)
return;
if (version & 1)
++version; /* first time write, random junk */
++version;
kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
/*
* The guest calculates current wall clock time by adding
* system time (updated by kvm_guest_time_update below) to the
* wall clock specified here. guest system time equals host
* system time for us, thus we must fill in host boot time here.
*/
getboottime(&boot);
if (kvm->arch.kvmclock_offset) {
struct timespec ts = ns_to_timespec(kvm->arch.kvmclock_offset);
boot = timespec_sub(boot, ts);
}
wc.sec = boot.tv_sec;
wc.nsec = boot.tv_nsec;
wc.version = version;
kvm_write_guest(kvm, wall_clock, &wc, sizeof(wc));
version++;
kvm_write_guest(kvm, wall_clock, &version, sizeof(version));
}
static uint32_t div_frac(uint32_t dividend, uint32_t divisor)
{
uint32_t quotient, remainder;
/* Don't try to replace with do_div(), this one calculates
* "(dividend << 32) / divisor" */
__asm__ ( "divl %4"
: "=a" (quotient), "=d" (remainder)
: "0" (0), "1" (dividend), "r" (divisor) );
return quotient;
}
static void kvm_get_time_scale(uint32_t scaled_khz, uint32_t base_khz,
s8 *pshift, u32 *pmultiplier)
{
uint64_t scaled64;
int32_t shift = 0;
uint64_t tps64;
uint32_t tps32;
tps64 = base_khz * 1000LL;
scaled64 = scaled_khz * 1000LL;
while (tps64 > scaled64*2 || tps64 & 0xffffffff00000000ULL) {
tps64 >>= 1;
shift--;
}
tps32 = (uint32_t)tps64;
while (tps32 <= scaled64 || scaled64 & 0xffffffff00000000ULL) {
if (scaled64 & 0xffffffff00000000ULL || tps32 & 0x80000000)
scaled64 >>= 1;
else
tps32 <<= 1;
shift++;
}
*pshift = shift;
*pmultiplier = div_frac(scaled64, tps32);
pr_debug("%s: base_khz %u => %u, shift %d, mul %u\n",
__func__, base_khz, scaled_khz, shift, *pmultiplier);
}
static inline u64 get_kernel_ns(void)
{
struct timespec ts;
WARN_ON(preemptible());
ktime_get_ts(&ts);
monotonic_to_bootbased(&ts);
return timespec_to_ns(&ts);
}
#ifdef CONFIG_X86_64
static atomic_t kvm_guest_has_master_clock = ATOMIC_INIT(0);
#endif
static DEFINE_PER_CPU(unsigned long, cpu_tsc_khz);
unsigned long max_tsc_khz;
static inline u64 nsec_to_cycles(struct kvm_vcpu *vcpu, u64 nsec)
{
return pvclock_scale_delta(nsec, vcpu->arch.virtual_tsc_mult,
vcpu->arch.virtual_tsc_shift);
}
static u32 adjust_tsc_khz(u32 khz, s32 ppm)
{
u64 v = (u64)khz * (1000000 + ppm);
do_div(v, 1000000);
return v;
}
static void kvm_set_tsc_khz(struct kvm_vcpu *vcpu, u32 this_tsc_khz)
{
u32 thresh_lo, thresh_hi;
int use_scaling = 0;
/* tsc_khz can be zero if TSC calibration fails */
if (this_tsc_khz == 0)
return;
/* Compute a scale to convert nanoseconds in TSC cycles */
kvm_get_time_scale(this_tsc_khz, NSEC_PER_SEC / 1000,
&vcpu->arch.virtual_tsc_shift,
&vcpu->arch.virtual_tsc_mult);
vcpu->arch.virtual_tsc_khz = this_tsc_khz;
/*
* Compute the variation in TSC rate which is acceptable
* within the range of tolerance and decide if the
* rate being applied is within that bounds of the hardware
* rate. If so, no scaling or compensation need be done.
*/
thresh_lo = adjust_tsc_khz(tsc_khz, -tsc_tolerance_ppm);
thresh_hi = adjust_tsc_khz(tsc_khz, tsc_tolerance_ppm);
if (this_tsc_khz < thresh_lo || this_tsc_khz > thresh_hi) {
pr_debug("kvm: requested TSC rate %u falls outside tolerance [%u,%u]\n", this_tsc_khz, thresh_lo, thresh_hi);
use_scaling = 1;
}
kvm_x86_ops->set_tsc_khz(vcpu, this_tsc_khz, use_scaling);
}
static u64 compute_guest_tsc(struct kvm_vcpu *vcpu, s64 kernel_ns)
{
u64 tsc = pvclock_scale_delta(kernel_ns-vcpu->arch.this_tsc_nsec,
vcpu->arch.virtual_tsc_mult,
vcpu->arch.virtual_tsc_shift);
tsc += vcpu->arch.this_tsc_write;
return tsc;
}
void kvm_track_tsc_matching(struct kvm_vcpu *vcpu)
{
#ifdef CONFIG_X86_64
bool vcpus_matched;
bool do_request = false;
struct kvm_arch *ka = &vcpu->kvm->arch;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
atomic_read(&vcpu->kvm->online_vcpus));
if (vcpus_matched && gtod->clock.vclock_mode == VCLOCK_TSC)
if (!ka->use_master_clock)
do_request = 1;
if (!vcpus_matched && ka->use_master_clock)
do_request = 1;
if (do_request)
kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu);
trace_kvm_track_tsc(vcpu->vcpu_id, ka->nr_vcpus_matched_tsc,
atomic_read(&vcpu->kvm->online_vcpus),
ka->use_master_clock, gtod->clock.vclock_mode);
#endif
}
static void update_ia32_tsc_adjust_msr(struct kvm_vcpu *vcpu, s64 offset)
{
u64 curr_offset = kvm_x86_ops->read_tsc_offset(vcpu);
vcpu->arch.ia32_tsc_adjust_msr += offset - curr_offset;
}
void kvm_write_tsc(struct kvm_vcpu *vcpu, struct msr_data *msr)
{
struct kvm *kvm = vcpu->kvm;
u64 offset, ns, elapsed;
unsigned long flags;
s64 usdiff;
bool matched;
u64 data = msr->data;
raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags);
offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
ns = get_kernel_ns();
elapsed = ns - kvm->arch.last_tsc_nsec;
if (vcpu->arch.virtual_tsc_khz) {
int faulted = 0;
/* n.b - signed multiplication and division required */
usdiff = data - kvm->arch.last_tsc_write;
#ifdef CONFIG_X86_64
usdiff = (usdiff * 1000) / vcpu->arch.virtual_tsc_khz;
#else
/* do_div() only does unsigned */
asm("1: idivl %[divisor]\n"
"2: xor %%edx, %%edx\n"
" movl $0, %[faulted]\n"
"3:\n"
".section .fixup,\"ax\"\n"
"4: movl $1, %[faulted]\n"
" jmp 3b\n"
".previous\n"
_ASM_EXTABLE(1b, 4b)
: "=A"(usdiff), [faulted] "=r" (faulted)
: "A"(usdiff * 1000), [divisor] "rm"(vcpu->arch.virtual_tsc_khz));
#endif
do_div(elapsed, 1000);
usdiff -= elapsed;
if (usdiff < 0)
usdiff = -usdiff;
/* idivl overflow => difference is larger than USEC_PER_SEC */
if (faulted)
usdiff = USEC_PER_SEC;
} else
usdiff = USEC_PER_SEC; /* disable TSC match window below */
/*
* Special case: TSC write with a small delta (1 second) of virtual
* cycle time against real time is interpreted as an attempt to
* synchronize the CPU.
*
* For a reliable TSC, we can match TSC offsets, and for an unstable
* TSC, we add elapsed time in this computation. We could let the
* compensation code attempt to catch up if we fall behind, but
* it's better to try to match offsets from the beginning.
*/
if (usdiff < USEC_PER_SEC &&
vcpu->arch.virtual_tsc_khz == kvm->arch.last_tsc_khz) {
if (!check_tsc_unstable()) {
offset = kvm->arch.cur_tsc_offset;
pr_debug("kvm: matched tsc offset for %llu\n", data);
} else {
u64 delta = nsec_to_cycles(vcpu, elapsed);
data += delta;
offset = kvm_x86_ops->compute_tsc_offset(vcpu, data);
pr_debug("kvm: adjusted tsc offset by %llu\n", delta);
}
matched = true;
} else {
/*
* We split periods of matched TSC writes into generations.
* For each generation, we track the original measured
* nanosecond time, offset, and write, so if TSCs are in
* sync, we can match exact offset, and if not, we can match
* exact software computation in compute_guest_tsc()
*
* These values are tracked in kvm->arch.cur_xxx variables.
*/
kvm->arch.cur_tsc_generation++;
kvm->arch.cur_tsc_nsec = ns;
kvm->arch.cur_tsc_write = data;
kvm->arch.cur_tsc_offset = offset;
matched = false;
pr_debug("kvm: new tsc generation %u, clock %llu\n",
kvm->arch.cur_tsc_generation, data);
}
/*
* We also track th most recent recorded KHZ, write and time to
* allow the matching interval to be extended at each write.
*/
kvm->arch.last_tsc_nsec = ns;
kvm->arch.last_tsc_write = data;
kvm->arch.last_tsc_khz = vcpu->arch.virtual_tsc_khz;
/* Reset of TSC must disable overshoot protection below */
vcpu->arch.hv_clock.tsc_timestamp = 0;
vcpu->arch.last_guest_tsc = data;
/* Keep track of which generation this VCPU has synchronized to */
vcpu->arch.this_tsc_generation = kvm->arch.cur_tsc_generation;
vcpu->arch.this_tsc_nsec = kvm->arch.cur_tsc_nsec;
vcpu->arch.this_tsc_write = kvm->arch.cur_tsc_write;
if (guest_cpuid_has_tsc_adjust(vcpu) && !msr->host_initiated)
update_ia32_tsc_adjust_msr(vcpu, offset);
kvm_x86_ops->write_tsc_offset(vcpu, offset);
raw_spin_unlock_irqrestore(&kvm->arch.tsc_write_lock, flags);
spin_lock(&kvm->arch.pvclock_gtod_sync_lock);
if (matched)
kvm->arch.nr_vcpus_matched_tsc++;
else
kvm->arch.nr_vcpus_matched_tsc = 0;
kvm_track_tsc_matching(vcpu);
spin_unlock(&kvm->arch.pvclock_gtod_sync_lock);
}
EXPORT_SYMBOL_GPL(kvm_write_tsc);
#ifdef CONFIG_X86_64
static cycle_t read_tsc(void)
{
cycle_t ret;
u64 last;
/*
* Empirically, a fence (of type that depends on the CPU)
* before rdtsc is enough to ensure that rdtsc is ordered
* with respect to loads. The various CPU manuals are unclear
* as to whether rdtsc can be reordered with later loads,
* but no one has ever seen it happen.
*/
rdtsc_barrier();
ret = (cycle_t)vget_cycles();
last = pvclock_gtod_data.clock.cycle_last;
if (likely(ret >= last))
return ret;
/*
* GCC likes to generate cmov here, but this branch is extremely
* predictable (it's just a funciton of time and the likely is
* very likely) and there's a data dependence, so force GCC
* to generate a branch instead. I don't barrier() because
* we don't actually need a barrier, and if this function
* ever gets inlined it will generate worse code.
*/
asm volatile ("");
return last;
}
static inline u64 vgettsc(cycle_t *cycle_now)
{
long v;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
*cycle_now = read_tsc();
v = (*cycle_now - gtod->clock.cycle_last) & gtod->clock.mask;
return v * gtod->clock.mult;
}
static int do_monotonic(struct timespec *ts, cycle_t *cycle_now)
{
unsigned long seq;
u64 ns;
int mode;
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
ts->tv_nsec = 0;
do {
seq = read_seqcount_begin(>od->seq);
mode = gtod->clock.vclock_mode;
ts->tv_sec = gtod->monotonic_time_sec;
ns = gtod->monotonic_time_snsec;
ns += vgettsc(cycle_now);
ns >>= gtod->clock.shift;
} while (unlikely(read_seqcount_retry(>od->seq, seq)));
timespec_add_ns(ts, ns);
return mode;
}
/* returns true if host is using tsc clocksource */
static bool kvm_get_time_and_clockread(s64 *kernel_ns, cycle_t *cycle_now)
{
struct timespec ts;
/* checked again under seqlock below */
if (pvclock_gtod_data.clock.vclock_mode != VCLOCK_TSC)
return false;
if (do_monotonic(&ts, cycle_now) != VCLOCK_TSC)
return false;
monotonic_to_bootbased(&ts);
*kernel_ns = timespec_to_ns(&ts);
return true;
}
#endif
/*
*
* Assuming a stable TSC across physical CPUS, and a stable TSC
* across virtual CPUs, the following condition is possible.
* Each numbered line represents an event visible to both
* CPUs at the next numbered event.
*
* "timespecX" represents host monotonic time. "tscX" represents
* RDTSC value.
*
* VCPU0 on CPU0 | VCPU1 on CPU1
*
* 1. read timespec0,tsc0
* 2. | timespec1 = timespec0 + N
* | tsc1 = tsc0 + M
* 3. transition to guest | transition to guest
* 4. ret0 = timespec0 + (rdtsc - tsc0) |
* 5. | ret1 = timespec1 + (rdtsc - tsc1)
* | ret1 = timespec0 + N + (rdtsc - (tsc0 + M))
*
* Since ret0 update is visible to VCPU1 at time 5, to obey monotonicity:
*
* - ret0 < ret1
* - timespec0 + (rdtsc - tsc0) < timespec0 + N + (rdtsc - (tsc0 + M))
* ...
* - 0 < N - M => M < N
*
* That is, when timespec0 != timespec1, M < N. Unfortunately that is not
* always the case (the difference between two distinct xtime instances
* might be smaller then the difference between corresponding TSC reads,
* when updating guest vcpus pvclock areas).
*
* To avoid that problem, do not allow visibility of distinct
* system_timestamp/tsc_timestamp values simultaneously: use a master
* copy of host monotonic time values. Update that master copy
* in lockstep.
*
* Rely on synchronization of host TSCs and guest TSCs for monotonicity.
*
*/
static void pvclock_update_vm_gtod_copy(struct kvm *kvm)
{
#ifdef CONFIG_X86_64
struct kvm_arch *ka = &kvm->arch;
int vclock_mode;
bool host_tsc_clocksource, vcpus_matched;
vcpus_matched = (ka->nr_vcpus_matched_tsc + 1 ==
atomic_read(&kvm->online_vcpus));
/*
* If the host uses TSC clock, then passthrough TSC as stable
* to the guest.
*/
host_tsc_clocksource = kvm_get_time_and_clockread(
&ka->master_kernel_ns,
&ka->master_cycle_now);
ka->use_master_clock = host_tsc_clocksource & vcpus_matched;
if (ka->use_master_clock)
atomic_set(&kvm_guest_has_master_clock, 1);
vclock_mode = pvclock_gtod_data.clock.vclock_mode;
trace_kvm_update_master_clock(ka->use_master_clock, vclock_mode,
vcpus_matched);
#endif
}
static void kvm_gen_update_masterclock(struct kvm *kvm)
{
#ifdef CONFIG_X86_64
int i;
struct kvm_vcpu *vcpu;
struct kvm_arch *ka = &kvm->arch;
spin_lock(&ka->pvclock_gtod_sync_lock);
kvm_make_mclock_inprogress_request(kvm);
/* no guest entries from this point */
pvclock_update_vm_gtod_copy(kvm);
kvm_for_each_vcpu(i, vcpu, kvm)
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
/* guest entries allowed */
kvm_for_each_vcpu(i, vcpu, kvm)
clear_bit(KVM_REQ_MCLOCK_INPROGRESS, &vcpu->requests);
spin_unlock(&ka->pvclock_gtod_sync_lock);
#endif
}
static int kvm_guest_time_update(struct kvm_vcpu *v)
{
unsigned long flags, this_tsc_khz;
struct kvm_vcpu_arch *vcpu = &v->arch;
struct kvm_arch *ka = &v->kvm->arch;
s64 kernel_ns, max_kernel_ns;
u64 tsc_timestamp, host_tsc;
struct pvclock_vcpu_time_info guest_hv_clock;
u8 pvclock_flags;
bool use_master_clock;
kernel_ns = 0;
host_tsc = 0;
/*
* If the host uses TSC clock, then passthrough TSC as stable
* to the guest.
*/
spin_lock(&ka->pvclock_gtod_sync_lock);
use_master_clock = ka->use_master_clock;
if (use_master_clock) {
host_tsc = ka->master_cycle_now;
kernel_ns = ka->master_kernel_ns;
}
spin_unlock(&ka->pvclock_gtod_sync_lock);
/* Keep irq disabled to prevent changes to the clock */
local_irq_save(flags);
this_tsc_khz = __get_cpu_var(cpu_tsc_khz);
if (unlikely(this_tsc_khz == 0)) {
local_irq_restore(flags);
kvm_make_request(KVM_REQ_CLOCK_UPDATE, v);
return 1;
}
if (!use_master_clock) {
host_tsc = native_read_tsc();
kernel_ns = get_kernel_ns();
}
tsc_timestamp = kvm_x86_ops->read_l1_tsc(v, host_tsc);
/*
* We may have to catch up the TSC to match elapsed wall clock
* time for two reasons, even if kvmclock is used.
* 1) CPU could have been running below the maximum TSC rate
* 2) Broken TSC compensation resets the base at each VCPU
* entry to avoid unknown leaps of TSC even when running
* again on the same CPU. This may cause apparent elapsed
* time to disappear, and the guest to stand still or run
* very slowly.
*/
if (vcpu->tsc_catchup) {
u64 tsc = compute_guest_tsc(v, kernel_ns);
if (tsc > tsc_timestamp) {
adjust_tsc_offset_guest(v, tsc - tsc_timestamp);
tsc_timestamp = tsc;
}
}
local_irq_restore(flags);
if (!vcpu->pv_time_enabled)
return 0;
/*
* Time as measured by the TSC may go backwards when resetting the base
* tsc_timestamp. The reason for this is that the TSC resolution is
* higher than the resolution of the other clock scales. Thus, many
* possible measurments of the TSC correspond to one measurement of any
* other clock, and so a spread of values is possible. This is not a
* problem for the computation of the nanosecond clock; with TSC rates
* around 1GHZ, there can only be a few cycles which correspond to one
* nanosecond value, and any path through this code will inevitably
* take longer than that. However, with the kernel_ns value itself,
* the precision may be much lower, down to HZ granularity. If the
* first sampling of TSC against kernel_ns ends in the low part of the
* range, and the second in the high end of the range, we can get:
*
* (TSC - offset_low) * S + kns_old > (TSC - offset_high) * S + kns_new
*
* As the sampling errors potentially range in the thousands of cycles,
* it is possible such a time value has already been observed by the
* guest. To protect against this, we must compute the system time as
* observed by the guest and ensure the new system time is greater.
*/
max_kernel_ns = 0;
if (vcpu->hv_clock.tsc_timestamp) {
max_kernel_ns = vcpu->last_guest_tsc -
vcpu->hv_clock.tsc_timestamp;
max_kernel_ns = pvclock_scale_delta(max_kernel_ns,
vcpu->hv_clock.tsc_to_system_mul,
vcpu->hv_clock.tsc_shift);
max_kernel_ns += vcpu->last_kernel_ns;
}
if (unlikely(vcpu->hw_tsc_khz != this_tsc_khz)) {
kvm_get_time_scale(NSEC_PER_SEC / 1000, this_tsc_khz,
&vcpu->hv_clock.tsc_shift,
&vcpu->hv_clock.tsc_to_system_mul);
vcpu->hw_tsc_khz = this_tsc_khz;
}
/* with a master <monotonic time, tsc value> tuple,
* pvclock clock reads always increase at the (scaled) rate
* of guest TSC - no need to deal with sampling errors.
*/
if (!use_master_clock) {
if (max_kernel_ns > kernel_ns)
kernel_ns = max_kernel_ns;
}
/* With all the info we got, fill in the values */
vcpu->hv_clock.tsc_timestamp = tsc_timestamp;
vcpu->hv_clock.system_time = kernel_ns + v->kvm->arch.kvmclock_offset;
vcpu->last_kernel_ns = kernel_ns;
vcpu->last_guest_tsc = tsc_timestamp;
/*
* The interface expects us to write an even number signaling that the
* update is finished. Since the guest won't see the intermediate
* state, we just increase by 2 at the end.
*/
vcpu->hv_clock.version += 2;
if (unlikely(kvm_read_guest_cached(v->kvm, &vcpu->pv_time,
&guest_hv_clock, sizeof(guest_hv_clock))))
return 0;
/* retain PVCLOCK_GUEST_STOPPED if set in guest copy */
pvclock_flags = (guest_hv_clock.flags & PVCLOCK_GUEST_STOPPED);
if (vcpu->pvclock_set_guest_stopped_request) {
pvclock_flags |= PVCLOCK_GUEST_STOPPED;
vcpu->pvclock_set_guest_stopped_request = false;
}
/* If the host uses TSC clocksource, then it is stable */
if (use_master_clock)
pvclock_flags |= PVCLOCK_TSC_STABLE_BIT;
vcpu->hv_clock.flags = pvclock_flags;
kvm_write_guest_cached(v->kvm, &vcpu->pv_time,
&vcpu->hv_clock,
sizeof(vcpu->hv_clock));
return 0;
}
/*
* kvmclock updates which are isolated to a given vcpu, such as
* vcpu->cpu migration, should not allow system_timestamp from
* the rest of the vcpus to remain static. Otherwise ntp frequency
* correction applies to one vcpu's system_timestamp but not
* the others.
*
* So in those cases, request a kvmclock update for all vcpus.
* The worst case for a remote vcpu to update its kvmclock
* is then bounded by maximum nohz sleep latency.
*/
static void kvm_gen_kvmclock_update(struct kvm_vcpu *v)
{
int i;
struct kvm *kvm = v->kvm;
struct kvm_vcpu *vcpu;
kvm_for_each_vcpu(i, vcpu, kvm) {
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
kvm_vcpu_kick(vcpu);
}
}
static bool msr_mtrr_valid(unsigned msr)
{
switch (msr) {
case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1:
case MSR_MTRRfix64K_00000:
case MSR_MTRRfix16K_80000:
case MSR_MTRRfix16K_A0000:
case MSR_MTRRfix4K_C0000:
case MSR_MTRRfix4K_C8000:
case MSR_MTRRfix4K_D0000:
case MSR_MTRRfix4K_D8000:
case MSR_MTRRfix4K_E0000:
case MSR_MTRRfix4K_E8000:
case MSR_MTRRfix4K_F0000:
case MSR_MTRRfix4K_F8000:
case MSR_MTRRdefType:
case MSR_IA32_CR_PAT:
return true;
case 0x2f8:
return true;
}
return false;
}
static bool valid_pat_type(unsigned t)
{
return t < 8 && (1 << t) & 0xf3; /* 0, 1, 4, 5, 6, 7 */
}
static bool valid_mtrr_type(unsigned t)
{
return t < 8 && (1 << t) & 0x73; /* 0, 1, 4, 5, 6 */
}
static bool mtrr_valid(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
int i;
if (!msr_mtrr_valid(msr))
return false;
if (msr == MSR_IA32_CR_PAT) {
for (i = 0; i < 8; i++)
if (!valid_pat_type((data >> (i * 8)) & 0xff))
return false;
return true;
} else if (msr == MSR_MTRRdefType) {
if (data & ~0xcff)
return false;
return valid_mtrr_type(data & 0xff);
} else if (msr >= MSR_MTRRfix64K_00000 && msr <= MSR_MTRRfix4K_F8000) {
for (i = 0; i < 8 ; i++)
if (!valid_mtrr_type((data >> (i * 8)) & 0xff))
return false;
return true;
}
/* variable MTRRs */
return valid_mtrr_type(data & 0xff);
}
static int set_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
if (!mtrr_valid(vcpu, msr, data))
return 1;
if (msr == MSR_MTRRdefType) {
vcpu->arch.mtrr_state.def_type = data;
vcpu->arch.mtrr_state.enabled = (data & 0xc00) >> 10;
} else if (msr == MSR_MTRRfix64K_00000)
p[0] = data;
else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
p[1 + msr - MSR_MTRRfix16K_80000] = data;
else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
p[3 + msr - MSR_MTRRfix4K_C0000] = data;
else if (msr == MSR_IA32_CR_PAT)
vcpu->arch.pat = data;
else { /* Variable MTRRs */
int idx, is_mtrr_mask;
u64 *pt;
idx = (msr - 0x200) / 2;
is_mtrr_mask = msr - 0x200 - 2 * idx;
if (!is_mtrr_mask)
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
else
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
*pt = data;
}
kvm_mmu_reset_context(vcpu);
return 0;
}
static int set_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
switch (msr) {
case MSR_IA32_MCG_STATUS:
vcpu->arch.mcg_status = data;
break;
case MSR_IA32_MCG_CTL:
if (!(mcg_cap & MCG_CTL_P))
return 1;
if (data != 0 && data != ~(u64)0)
return -1;
vcpu->arch.mcg_ctl = data;
break;
default:
if (msr >= MSR_IA32_MC0_CTL &&
msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
u32 offset = msr - MSR_IA32_MC0_CTL;
/* only 0 or all 1s can be written to IA32_MCi_CTL
* some Linux kernels though clear bit 10 in bank 4 to
* workaround a BIOS/GART TBL issue on AMD K8s, ignore
* this to avoid an uncatched #GP in the guest
*/
if ((offset & 0x3) == 0 &&
data != 0 && (data | (1 << 10)) != ~(u64)0)
return -1;
vcpu->arch.mce_banks[offset] = data;
break;
}
return 1;
}
return 0;
}
static int xen_hvm_config(struct kvm_vcpu *vcpu, u64 data)
{
struct kvm *kvm = vcpu->kvm;
int lm = is_long_mode(vcpu);
u8 *blob_addr = lm ? (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_64
: (u8 *)(long)kvm->arch.xen_hvm_config.blob_addr_32;
u8 blob_size = lm ? kvm->arch.xen_hvm_config.blob_size_64
: kvm->arch.xen_hvm_config.blob_size_32;
u32 page_num = data & ~PAGE_MASK;
u64 page_addr = data & PAGE_MASK;
u8 *page;
int r;
r = -E2BIG;
if (page_num >= blob_size)
goto out;
r = -ENOMEM;
page = memdup_user(blob_addr + (page_num * PAGE_SIZE), PAGE_SIZE);
if (IS_ERR(page)) {
r = PTR_ERR(page);
goto out;
}
if (kvm_write_guest(kvm, page_addr, page, PAGE_SIZE))
goto out_free;
r = 0;
out_free:
kfree(page);
out:
return r;
}
static bool kvm_hv_hypercall_enabled(struct kvm *kvm)
{
return kvm->arch.hv_hypercall & HV_X64_MSR_HYPERCALL_ENABLE;
}
static bool kvm_hv_msr_partition_wide(u32 msr)
{
bool r = false;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
case HV_X64_MSR_HYPERCALL:
r = true;
break;
}
return r;
}
static int set_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
struct kvm *kvm = vcpu->kvm;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
kvm->arch.hv_guest_os_id = data;
/* setting guest os id to zero disables hypercall page */
if (!kvm->arch.hv_guest_os_id)
kvm->arch.hv_hypercall &= ~HV_X64_MSR_HYPERCALL_ENABLE;
break;
case HV_X64_MSR_HYPERCALL: {
u64 gfn;
unsigned long addr;
u8 instructions[4];
/* if guest os id is not set hypercall should remain disabled */
if (!kvm->arch.hv_guest_os_id)
break;
if (!(data & HV_X64_MSR_HYPERCALL_ENABLE)) {
kvm->arch.hv_hypercall = data;
break;
}
gfn = data >> HV_X64_MSR_HYPERCALL_PAGE_ADDRESS_SHIFT;
addr = gfn_to_hva(kvm, gfn);
if (kvm_is_error_hva(addr))
return 1;
kvm_x86_ops->patch_hypercall(vcpu, instructions);
((unsigned char *)instructions)[3] = 0xc3; /* ret */
if (__copy_to_user((void __user *)addr, instructions, 4))
return 1;
kvm->arch.hv_hypercall = data;
break;
}
default:
vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
"data 0x%llx\n", msr, data);
return 1;
}
return 0;
}
static int set_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 data)
{
switch (msr) {
case HV_X64_MSR_APIC_ASSIST_PAGE: {
unsigned long addr;
if (!(data & HV_X64_MSR_APIC_ASSIST_PAGE_ENABLE)) {
vcpu->arch.hv_vapic = data;
break;
}
addr = gfn_to_hva(vcpu->kvm, data >>
HV_X64_MSR_APIC_ASSIST_PAGE_ADDRESS_SHIFT);
if (kvm_is_error_hva(addr))
return 1;
if (__clear_user((void __user *)addr, PAGE_SIZE))
return 1;
vcpu->arch.hv_vapic = data;
break;
}
case HV_X64_MSR_EOI:
return kvm_hv_vapic_msr_write(vcpu, APIC_EOI, data);
case HV_X64_MSR_ICR:
return kvm_hv_vapic_msr_write(vcpu, APIC_ICR, data);
case HV_X64_MSR_TPR:
return kvm_hv_vapic_msr_write(vcpu, APIC_TASKPRI, data);
default:
vcpu_unimpl(vcpu, "HYPER-V unimplemented wrmsr: 0x%x "
"data 0x%llx\n", msr, data);
return 1;
}
return 0;
}
static int kvm_pv_enable_async_pf(struct kvm_vcpu *vcpu, u64 data)
{
gpa_t gpa = data & ~0x3f;
/* Bits 2:5 are reserved, Should be zero */
if (data & 0x3c)
return 1;
vcpu->arch.apf.msr_val = data;
if (!(data & KVM_ASYNC_PF_ENABLED)) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
return 0;
}
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.apf.data, gpa,
sizeof(u32)))
return 1;
vcpu->arch.apf.send_user_only = !(data & KVM_ASYNC_PF_SEND_ALWAYS);
kvm_async_pf_wakeup_all(vcpu);
return 0;
}
static void kvmclock_reset(struct kvm_vcpu *vcpu)
{
vcpu->arch.pv_time_enabled = false;
}
static void accumulate_steal_time(struct kvm_vcpu *vcpu)
{
u64 delta;
if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
return;
delta = current->sched_info.run_delay - vcpu->arch.st.last_steal;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
vcpu->arch.st.accum_steal = delta;
}
static void record_steal_time(struct kvm_vcpu *vcpu)
{
if (!(vcpu->arch.st.msr_val & KVM_MSR_ENABLED))
return;
if (unlikely(kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
&vcpu->arch.st.steal, sizeof(struct kvm_steal_time))))
return;
vcpu->arch.st.steal.steal += vcpu->arch.st.accum_steal;
vcpu->arch.st.steal.version += 2;
vcpu->arch.st.accum_steal = 0;
kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.st.stime,
&vcpu->arch.st.steal, sizeof(struct kvm_steal_time));
}
int kvm_set_msr_common(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
{
bool pr = false;
u32 msr = msr_info->index;
u64 data = msr_info->data;
switch (msr) {
case MSR_AMD64_NB_CFG:
case MSR_IA32_UCODE_REV:
case MSR_IA32_UCODE_WRITE:
case MSR_VM_HSAVE_PA:
case MSR_AMD64_PATCH_LOADER:
case MSR_AMD64_BU_CFG2:
break;
case MSR_EFER:
return set_efer(vcpu, data);
case MSR_K7_HWCR:
data &= ~(u64)0x40; /* ignore flush filter disable */
data &= ~(u64)0x100; /* ignore ignne emulation enable */
data &= ~(u64)0x8; /* ignore TLB cache disable */
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented HWCR wrmsr: 0x%llx\n",
data);
return 1;
}
break;
case MSR_FAM10H_MMIO_CONF_BASE:
if (data != 0) {
vcpu_unimpl(vcpu, "unimplemented MMIO_CONF_BASE wrmsr: "
"0x%llx\n", data);
return 1;
}
break;
case MSR_IA32_DEBUGCTLMSR:
if (!data) {
/* We support the non-activated case already */
break;
} else if (data & ~(DEBUGCTLMSR_LBR | DEBUGCTLMSR_BTF)) {
/* Values other than LBR and BTF are vendor-specific,
thus reserved and should throw a #GP */
return 1;
}
vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTLMSR 0x%llx, nop\n",
__func__, data);
break;
case 0x200 ... 0x2ff:
return set_msr_mtrr(vcpu, msr, data);
case MSR_IA32_APICBASE:
kvm_set_apic_base(vcpu, data);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_write(vcpu, msr, data);
case MSR_IA32_TSCDEADLINE:
kvm_set_lapic_tscdeadline_msr(vcpu, data);
break;
case MSR_IA32_TSC_ADJUST:
if (guest_cpuid_has_tsc_adjust(vcpu)) {
if (!msr_info->host_initiated) {
u64 adj = data - vcpu->arch.ia32_tsc_adjust_msr;
kvm_x86_ops->adjust_tsc_offset(vcpu, adj, true);
}
vcpu->arch.ia32_tsc_adjust_msr = data;
}
break;
case MSR_IA32_MISC_ENABLE:
vcpu->arch.ia32_misc_enable_msr = data;
break;
case MSR_KVM_WALL_CLOCK_NEW:
case MSR_KVM_WALL_CLOCK:
vcpu->kvm->arch.wall_clock = data;
kvm_write_wall_clock(vcpu->kvm, data);
break;
case MSR_KVM_SYSTEM_TIME_NEW:
case MSR_KVM_SYSTEM_TIME: {
u64 gpa_offset;
kvmclock_reset(vcpu);
vcpu->arch.time = data;
kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
/* we verify if the enable bit is set... */
if (!(data & 1))
break;
gpa_offset = data & ~(PAGE_MASK | 1);
if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
&vcpu->arch.pv_time, data & ~1ULL,
sizeof(struct pvclock_vcpu_time_info)))
vcpu->arch.pv_time_enabled = false;
else
vcpu->arch.pv_time_enabled = true;
break;
}
case MSR_KVM_ASYNC_PF_EN:
if (kvm_pv_enable_async_pf(vcpu, data))
return 1;
break;
case MSR_KVM_STEAL_TIME:
if (unlikely(!sched_info_on()))
return 1;
if (data & KVM_STEAL_RESERVED_MASK)
return 1;
if (kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.st.stime,
data & KVM_STEAL_VALID_BITS,
sizeof(struct kvm_steal_time)))
return 1;
vcpu->arch.st.msr_val = data;
if (!(data & KVM_MSR_ENABLED))
break;
vcpu->arch.st.last_steal = current->sched_info.run_delay;
preempt_disable();
accumulate_steal_time(vcpu);
preempt_enable();
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
break;
case MSR_KVM_PV_EOI_EN:
if (kvm_lapic_enable_pv_eoi(vcpu, data))
return 1;
break;
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return set_msr_mce(vcpu, msr, data);
/* Performance counters are not protected by a CPUID bit,
* so we should check all of them in the generic path for the sake of
* cross vendor migration.
* Writing a zero into the event select MSRs disables them,
* which we perfectly emulate ;-). Any other value should be at least
* reported, some guests depend on them.
*/
case MSR_K7_EVNTSEL0:
case MSR_K7_EVNTSEL1:
case MSR_K7_EVNTSEL2:
case MSR_K7_EVNTSEL3:
if (data != 0)
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
/* at least RHEL 4 unconditionally writes to the perfctr registers,
* so we ignore writes to make it happy.
*/
case MSR_K7_PERFCTR0:
case MSR_K7_PERFCTR1:
case MSR_K7_PERFCTR2:
case MSR_K7_PERFCTR3:
vcpu_unimpl(vcpu, "unimplemented perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
pr = true;
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr_info);
if (pr || data != 0)
vcpu_unimpl(vcpu, "disabled perfctr wrmsr: "
"0x%x data 0x%llx\n", msr, data);
break;
case MSR_K7_CLK_CTL:
/*
* Ignore all writes to this no longer documented MSR.
* Writes are only relevant for old K7 processors,
* all pre-dating SVM, but a recommended workaround from
* AMD for these chips. It is possible to specify the
* affected processor models on the command line, hence
* the need to ignore the workaround.
*/
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = set_msr_hyperv_pw(vcpu, msr, data);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return set_msr_hyperv(vcpu, msr, data);
break;
case MSR_IA32_BBL_CR_CTL3:
/* Drop writes to this legacy MSR -- see rdmsr
* counterpart for further detail.
*/
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n", msr, data);
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.length = data;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
vcpu->arch.osvw.status = data;
break;
default:
if (msr && (msr == vcpu->kvm->arch.xen_hvm_config.msr))
return xen_hvm_config(vcpu, data);
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_set_msr(vcpu, msr_info);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled wrmsr: 0x%x data %llx\n",
msr, data);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored wrmsr: 0x%x data %llx\n",
msr, data);
break;
}
}
return 0;
}
EXPORT_SYMBOL_GPL(kvm_set_msr_common);
/*
* Reads an msr value (of 'msr_index') into 'pdata'.
* Returns 0 on success, non-0 otherwise.
* Assumes vcpu_load() was already called.
*/
int kvm_get_msr(struct kvm_vcpu *vcpu, u32 msr_index, u64 *pdata)
{
return kvm_x86_ops->get_msr(vcpu, msr_index, pdata);
}
static int get_msr_mtrr(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 *p = (u64 *)&vcpu->arch.mtrr_state.fixed_ranges;
if (!msr_mtrr_valid(msr))
return 1;
if (msr == MSR_MTRRdefType)
*pdata = vcpu->arch.mtrr_state.def_type +
(vcpu->arch.mtrr_state.enabled << 10);
else if (msr == MSR_MTRRfix64K_00000)
*pdata = p[0];
else if (msr == MSR_MTRRfix16K_80000 || msr == MSR_MTRRfix16K_A0000)
*pdata = p[1 + msr - MSR_MTRRfix16K_80000];
else if (msr >= MSR_MTRRfix4K_C0000 && msr <= MSR_MTRRfix4K_F8000)
*pdata = p[3 + msr - MSR_MTRRfix4K_C0000];
else if (msr == MSR_IA32_CR_PAT)
*pdata = vcpu->arch.pat;
else { /* Variable MTRRs */
int idx, is_mtrr_mask;
u64 *pt;
idx = (msr - 0x200) / 2;
is_mtrr_mask = msr - 0x200 - 2 * idx;
if (!is_mtrr_mask)
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].base_lo;
else
pt =
(u64 *)&vcpu->arch.mtrr_state.var_ranges[idx].mask_lo;
*pdata = *pt;
}
return 0;
}
static int get_msr_mce(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data;
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
switch (msr) {
case MSR_IA32_P5_MC_ADDR:
case MSR_IA32_P5_MC_TYPE:
data = 0;
break;
case MSR_IA32_MCG_CAP:
data = vcpu->arch.mcg_cap;
break;
case MSR_IA32_MCG_CTL:
if (!(mcg_cap & MCG_CTL_P))
return 1;
data = vcpu->arch.mcg_ctl;
break;
case MSR_IA32_MCG_STATUS:
data = vcpu->arch.mcg_status;
break;
default:
if (msr >= MSR_IA32_MC0_CTL &&
msr < MSR_IA32_MC0_CTL + 4 * bank_num) {
u32 offset = msr - MSR_IA32_MC0_CTL;
data = vcpu->arch.mce_banks[offset];
break;
}
return 1;
}
*pdata = data;
return 0;
}
static int get_msr_hyperv_pw(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data = 0;
struct kvm *kvm = vcpu->kvm;
switch (msr) {
case HV_X64_MSR_GUEST_OS_ID:
data = kvm->arch.hv_guest_os_id;
break;
case HV_X64_MSR_HYPERCALL:
data = kvm->arch.hv_hypercall;
break;
default:
vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
return 1;
}
*pdata = data;
return 0;
}
static int get_msr_hyperv(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data = 0;
switch (msr) {
case HV_X64_MSR_VP_INDEX: {
int r;
struct kvm_vcpu *v;
kvm_for_each_vcpu(r, v, vcpu->kvm)
if (v == vcpu)
data = r;
break;
}
case HV_X64_MSR_EOI:
return kvm_hv_vapic_msr_read(vcpu, APIC_EOI, pdata);
case HV_X64_MSR_ICR:
return kvm_hv_vapic_msr_read(vcpu, APIC_ICR, pdata);
case HV_X64_MSR_TPR:
return kvm_hv_vapic_msr_read(vcpu, APIC_TASKPRI, pdata);
case HV_X64_MSR_APIC_ASSIST_PAGE:
data = vcpu->arch.hv_vapic;
break;
default:
vcpu_unimpl(vcpu, "Hyper-V unhandled rdmsr: 0x%x\n", msr);
return 1;
}
*pdata = data;
return 0;
}
int kvm_get_msr_common(struct kvm_vcpu *vcpu, u32 msr, u64 *pdata)
{
u64 data;
switch (msr) {
case MSR_IA32_PLATFORM_ID:
case MSR_IA32_EBL_CR_POWERON:
case MSR_IA32_DEBUGCTLMSR:
case MSR_IA32_LASTBRANCHFROMIP:
case MSR_IA32_LASTBRANCHTOIP:
case MSR_IA32_LASTINTFROMIP:
case MSR_IA32_LASTINTTOIP:
case MSR_K8_SYSCFG:
case MSR_K7_HWCR:
case MSR_VM_HSAVE_PA:
case MSR_K7_EVNTSEL0:
case MSR_K7_PERFCTR0:
case MSR_K8_INT_PENDING_MSG:
case MSR_AMD64_NB_CFG:
case MSR_FAM10H_MMIO_CONF_BASE:
case MSR_AMD64_BU_CFG2:
data = 0;
break;
case MSR_P6_PERFCTR0:
case MSR_P6_PERFCTR1:
case MSR_P6_EVNTSEL0:
case MSR_P6_EVNTSEL1:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
data = 0;
break;
case MSR_IA32_UCODE_REV:
data = 0x100000000ULL;
break;
case MSR_MTRRcap:
data = 0x500 | KVM_NR_VAR_MTRR;
break;
case 0x200 ... 0x2ff:
return get_msr_mtrr(vcpu, msr, pdata);
case 0xcd: /* fsb frequency */
data = 3;
break;
/*
* MSR_EBC_FREQUENCY_ID
* Conservative value valid for even the basic CPU models.
* Models 0,1: 000 in bits 23:21 indicating a bus speed of
* 100MHz, model 2 000 in bits 18:16 indicating 100MHz,
* and 266MHz for model 3, or 4. Set Core Clock
* Frequency to System Bus Frequency Ratio to 1 (bits
* 31:24) even though these are only valid for CPU
* models > 2, however guests may end up dividing or
* multiplying by zero otherwise.
*/
case MSR_EBC_FREQUENCY_ID:
data = 1 << 24;
break;
case MSR_IA32_APICBASE:
data = kvm_get_apic_base(vcpu);
break;
case APIC_BASE_MSR ... APIC_BASE_MSR + 0x3ff:
return kvm_x2apic_msr_read(vcpu, msr, pdata);
break;
case MSR_IA32_TSCDEADLINE:
data = kvm_get_lapic_tscdeadline_msr(vcpu);
break;
case MSR_IA32_TSC_ADJUST:
data = (u64)vcpu->arch.ia32_tsc_adjust_msr;
break;
case MSR_IA32_MISC_ENABLE:
data = vcpu->arch.ia32_misc_enable_msr;
break;
case MSR_IA32_PERF_STATUS:
/* TSC increment by tick */
data = 1000ULL;
/* CPU multiplier */
data |= (((uint64_t)4ULL) << 40);
break;
case MSR_EFER:
data = vcpu->arch.efer;
break;
case MSR_KVM_WALL_CLOCK:
case MSR_KVM_WALL_CLOCK_NEW:
data = vcpu->kvm->arch.wall_clock;
break;
case MSR_KVM_SYSTEM_TIME:
case MSR_KVM_SYSTEM_TIME_NEW:
data = vcpu->arch.time;
break;
case MSR_KVM_ASYNC_PF_EN:
data = vcpu->arch.apf.msr_val;
break;
case MSR_KVM_STEAL_TIME:
data = vcpu->arch.st.msr_val;
break;
case MSR_KVM_PV_EOI_EN:
data = vcpu->arch.pv_eoi.msr_val;
break;
case MSR_IA32_P5_MC_ADDR:
case MSR_IA32_P5_MC_TYPE:
case MSR_IA32_MCG_CAP:
case MSR_IA32_MCG_CTL:
case MSR_IA32_MCG_STATUS:
case MSR_IA32_MC0_CTL ... MSR_IA32_MC0_CTL + 4 * KVM_MAX_MCE_BANKS - 1:
return get_msr_mce(vcpu, msr, pdata);
case MSR_K7_CLK_CTL:
/*
* Provide expected ramp-up count for K7. All other
* are set to zero, indicating minimum divisors for
* every field.
*
* This prevents guest kernels on AMD host with CPU
* type 6, model 8 and higher from exploding due to
* the rdmsr failing.
*/
data = 0x20000000;
break;
case HV_X64_MSR_GUEST_OS_ID ... HV_X64_MSR_SINT15:
if (kvm_hv_msr_partition_wide(msr)) {
int r;
mutex_lock(&vcpu->kvm->lock);
r = get_msr_hyperv_pw(vcpu, msr, pdata);
mutex_unlock(&vcpu->kvm->lock);
return r;
} else
return get_msr_hyperv(vcpu, msr, pdata);
break;
case MSR_IA32_BBL_CR_CTL3:
/* This legacy MSR exists but isn't fully documented in current
* silicon. It is however accessed by winxp in very narrow
* scenarios where it sets bit #19, itself documented as
* a "reserved" bit. Best effort attempt to source coherent
* read data here should the balance of the register be
* interpreted by the guest:
*
* L2 cache control register 3: 64GB range, 256KB size,
* enabled, latency 0x1, configured
*/
data = 0xbe702111;
break;
case MSR_AMD64_OSVW_ID_LENGTH:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.length;
break;
case MSR_AMD64_OSVW_STATUS:
if (!guest_cpuid_has_osvw(vcpu))
return 1;
data = vcpu->arch.osvw.status;
break;
default:
if (kvm_pmu_msr(vcpu, msr))
return kvm_pmu_get_msr(vcpu, msr, pdata);
if (!ignore_msrs) {
vcpu_unimpl(vcpu, "unhandled rdmsr: 0x%x\n", msr);
return 1;
} else {
vcpu_unimpl(vcpu, "ignored rdmsr: 0x%x\n", msr);
data = 0;
}
break;
}
*pdata = data;
return 0;
}
EXPORT_SYMBOL_GPL(kvm_get_msr_common);
/*
* Read or write a bunch of msrs. All parameters are kernel addresses.
*
* @return number of msrs set successfully.
*/
static int __msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs,
struct kvm_msr_entry *entries,
int (*do_msr)(struct kvm_vcpu *vcpu,
unsigned index, u64 *data))
{
int i, idx;
idx = srcu_read_lock(&vcpu->kvm->srcu);
for (i = 0; i < msrs->nmsrs; ++i)
if (do_msr(vcpu, entries[i].index, &entries[i].data))
break;
srcu_read_unlock(&vcpu->kvm->srcu, idx);
return i;
}
/*
* Read or write a bunch of msrs. Parameters are user addresses.
*
* @return number of msrs set successfully.
*/
static int msr_io(struct kvm_vcpu *vcpu, struct kvm_msrs __user *user_msrs,
int (*do_msr)(struct kvm_vcpu *vcpu,
unsigned index, u64 *data),
int writeback)
{
struct kvm_msrs msrs;
struct kvm_msr_entry *entries;
int r, n;
unsigned size;
r = -EFAULT;
if (copy_from_user(&msrs, user_msrs, sizeof msrs))
goto out;
r = -E2BIG;
if (msrs.nmsrs >= MAX_IO_MSRS)
goto out;
size = sizeof(struct kvm_msr_entry) * msrs.nmsrs;
entries = memdup_user(user_msrs->entries, size);
if (IS_ERR(entries)) {
r = PTR_ERR(entries);
goto out;
}
r = n = __msr_io(vcpu, &msrs, entries, do_msr);
if (r < 0)
goto out_free;
r = -EFAULT;
if (writeback && copy_to_user(user_msrs->entries, entries, size))
goto out_free;
r = n;
out_free:
kfree(entries);
out:
return r;
}
int kvm_dev_ioctl_check_extension(long ext)
{
int r;
switch (ext) {
case KVM_CAP_IRQCHIP:
case KVM_CAP_HLT:
case KVM_CAP_MMU_SHADOW_CACHE_CONTROL:
case KVM_CAP_SET_TSS_ADDR:
case KVM_CAP_EXT_CPUID:
case KVM_CAP_EXT_EMUL_CPUID:
case KVM_CAP_CLOCKSOURCE:
case KVM_CAP_PIT:
case KVM_CAP_NOP_IO_DELAY:
case KVM_CAP_MP_STATE:
case KVM_CAP_SYNC_MMU:
case KVM_CAP_USER_NMI:
case KVM_CAP_REINJECT_CONTROL:
case KVM_CAP_IRQ_INJECT_STATUS:
case KVM_CAP_IRQFD:
case KVM_CAP_IOEVENTFD:
case KVM_CAP_PIT2:
case KVM_CAP_PIT_STATE2:
case KVM_CAP_SET_IDENTITY_MAP_ADDR:
case KVM_CAP_XEN_HVM:
case KVM_CAP_ADJUST_CLOCK:
case KVM_CAP_VCPU_EVENTS:
case KVM_CAP_HYPERV:
case KVM_CAP_HYPERV_VAPIC:
case KVM_CAP_HYPERV_SPIN:
case KVM_CAP_PCI_SEGMENT:
case KVM_CAP_DEBUGREGS:
case KVM_CAP_X86_ROBUST_SINGLESTEP:
case KVM_CAP_XSAVE:
case KVM_CAP_ASYNC_PF:
case KVM_CAP_GET_TSC_KHZ:
case KVM_CAP_KVMCLOCK_CTRL:
case KVM_CAP_READONLY_MEM:
#ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
case KVM_CAP_ASSIGN_DEV_IRQ:
case KVM_CAP_PCI_2_3:
#endif
r = 1;
break;
case KVM_CAP_COALESCED_MMIO:
r = KVM_COALESCED_MMIO_PAGE_OFFSET;
break;
case KVM_CAP_VAPIC:
r = !kvm_x86_ops->cpu_has_accelerated_tpr();
break;
case KVM_CAP_NR_VCPUS:
r = KVM_SOFT_MAX_VCPUS;
break;
case KVM_CAP_MAX_VCPUS:
r = KVM_MAX_VCPUS;
break;
case KVM_CAP_NR_MEMSLOTS:
r = KVM_USER_MEM_SLOTS;
break;
case KVM_CAP_PV_MMU: /* obsolete */
r = 0;
break;
#ifdef CONFIG_KVM_DEVICE_ASSIGNMENT
case KVM_CAP_IOMMU:
r = iommu_present(&pci_bus_type);
break;
#endif
case KVM_CAP_MCE:
r = KVM_MAX_MCE_BANKS;
break;
case KVM_CAP_XCRS:
r = cpu_has_xsave;
break;
case KVM_CAP_TSC_CONTROL:
r = kvm_has_tsc_control;
break;
case KVM_CAP_TSC_DEADLINE_TIMER:
r = boot_cpu_has(X86_FEATURE_TSC_DEADLINE_TIMER);
break;
default:
r = 0;
break;
}
return r;
}
long kvm_arch_dev_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
void __user *argp = (void __user *)arg;
long r;
switch (ioctl) {
case KVM_GET_MSR_INDEX_LIST: {
struct kvm_msr_list __user *user_msr_list = argp;
struct kvm_msr_list msr_list;
unsigned n;
r = -EFAULT;
if (copy_from_user(&msr_list, user_msr_list, sizeof msr_list))
goto out;
n = msr_list.nmsrs;
msr_list.nmsrs = num_msrs_to_save + ARRAY_SIZE(emulated_msrs);
if (copy_to_user(user_msr_list, &msr_list, sizeof msr_list))
goto out;
r = -E2BIG;
if (n < msr_list.nmsrs)
goto out;
r = -EFAULT;
if (copy_to_user(user_msr_list->indices, &msrs_to_save,
num_msrs_to_save * sizeof(u32)))
goto out;
if (copy_to_user(user_msr_list->indices + num_msrs_to_save,
&emulated_msrs,
ARRAY_SIZE(emulated_msrs) * sizeof(u32)))
goto out;
r = 0;
break;
}
case KVM_GET_SUPPORTED_CPUID:
case KVM_GET_EMULATED_CPUID: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_dev_ioctl_get_cpuid(&cpuid, cpuid_arg->entries,
ioctl);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
goto out;
r = 0;
break;
}
case KVM_X86_GET_MCE_CAP_SUPPORTED: {
u64 mce_cap;
mce_cap = KVM_MCE_CAP_SUPPORTED;
r = -EFAULT;
if (copy_to_user(argp, &mce_cap, sizeof mce_cap))
goto out;
r = 0;
break;
}
default:
r = -EINVAL;
}
out:
return r;
}
static void wbinvd_ipi(void *garbage)
{
wbinvd();
}
static bool need_emulate_wbinvd(struct kvm_vcpu *vcpu)
{
return kvm_arch_has_noncoherent_dma(vcpu->kvm);
}
void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
{
/* Address WBINVD may be executed by guest */
if (need_emulate_wbinvd(vcpu)) {
if (kvm_x86_ops->has_wbinvd_exit())
cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
else if (vcpu->cpu != -1 && vcpu->cpu != cpu)
smp_call_function_single(vcpu->cpu,
wbinvd_ipi, NULL, 1);
}
kvm_x86_ops->vcpu_load(vcpu, cpu);
/* Apply any externally detected TSC adjustments (due to suspend) */
if (unlikely(vcpu->arch.tsc_offset_adjustment)) {
adjust_tsc_offset_host(vcpu, vcpu->arch.tsc_offset_adjustment);
vcpu->arch.tsc_offset_adjustment = 0;
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
}
if (unlikely(vcpu->cpu != cpu) || check_tsc_unstable()) {
s64 tsc_delta = !vcpu->arch.last_host_tsc ? 0 :
native_read_tsc() - vcpu->arch.last_host_tsc;
if (tsc_delta < 0)
mark_tsc_unstable("KVM discovered backwards TSC");
if (check_tsc_unstable()) {
u64 offset = kvm_x86_ops->compute_tsc_offset(vcpu,
vcpu->arch.last_guest_tsc);
kvm_x86_ops->write_tsc_offset(vcpu, offset);
vcpu->arch.tsc_catchup = 1;
}
/*
* On a host with synchronized TSC, there is no need to update
* kvmclock on vcpu->cpu migration
*/
if (!vcpu->kvm->arch.use_master_clock || vcpu->cpu == -1)
kvm_make_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu);
if (vcpu->cpu != cpu)
kvm_migrate_timers(vcpu);
vcpu->cpu = cpu;
}
accumulate_steal_time(vcpu);
kvm_make_request(KVM_REQ_STEAL_UPDATE, vcpu);
}
void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu)
{
kvm_x86_ops->vcpu_put(vcpu);
kvm_put_guest_fpu(vcpu);
vcpu->arch.last_host_tsc = native_read_tsc();
}
static int kvm_vcpu_ioctl_get_lapic(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
kvm_x86_ops->sync_pir_to_irr(vcpu);
memcpy(s->regs, vcpu->arch.apic->regs, sizeof *s);
return 0;
}
static int kvm_vcpu_ioctl_set_lapic(struct kvm_vcpu *vcpu,
struct kvm_lapic_state *s)
{
kvm_apic_post_state_restore(vcpu, s);
update_cr8_intercept(vcpu);
return 0;
}
static int kvm_vcpu_ioctl_interrupt(struct kvm_vcpu *vcpu,
struct kvm_interrupt *irq)
{
if (irq->irq >= KVM_NR_INTERRUPTS)
return -EINVAL;
if (irqchip_in_kernel(vcpu->kvm))
return -ENXIO;
kvm_queue_interrupt(vcpu, irq->irq, false);
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
static int kvm_vcpu_ioctl_nmi(struct kvm_vcpu *vcpu)
{
kvm_inject_nmi(vcpu);
return 0;
}
static int vcpu_ioctl_tpr_access_reporting(struct kvm_vcpu *vcpu,
struct kvm_tpr_access_ctl *tac)
{
if (tac->flags)
return -EINVAL;
vcpu->arch.tpr_access_reporting = !!tac->enabled;
return 0;
}
static int kvm_vcpu_ioctl_x86_setup_mce(struct kvm_vcpu *vcpu,
u64 mcg_cap)
{
int r;
unsigned bank_num = mcg_cap & 0xff, bank;
r = -EINVAL;
if (!bank_num || bank_num >= KVM_MAX_MCE_BANKS)
goto out;
if (mcg_cap & ~(KVM_MCE_CAP_SUPPORTED | 0xff | 0xff0000))
goto out;
r = 0;
vcpu->arch.mcg_cap = mcg_cap;
/* Init IA32_MCG_CTL to all 1s */
if (mcg_cap & MCG_CTL_P)
vcpu->arch.mcg_ctl = ~(u64)0;
/* Init IA32_MCi_CTL to all 1s */
for (bank = 0; bank < bank_num; bank++)
vcpu->arch.mce_banks[bank*4] = ~(u64)0;
out:
return r;
}
static int kvm_vcpu_ioctl_x86_set_mce(struct kvm_vcpu *vcpu,
struct kvm_x86_mce *mce)
{
u64 mcg_cap = vcpu->arch.mcg_cap;
unsigned bank_num = mcg_cap & 0xff;
u64 *banks = vcpu->arch.mce_banks;
if (mce->bank >= bank_num || !(mce->status & MCI_STATUS_VAL))
return -EINVAL;
/*
* if IA32_MCG_CTL is not all 1s, the uncorrected error
* reporting is disabled
*/
if ((mce->status & MCI_STATUS_UC) && (mcg_cap & MCG_CTL_P) &&
vcpu->arch.mcg_ctl != ~(u64)0)
return 0;
banks += 4 * mce->bank;
/*
* if IA32_MCi_CTL is not all 1s, the uncorrected error
* reporting is disabled for the bank
*/
if ((mce->status & MCI_STATUS_UC) && banks[0] != ~(u64)0)
return 0;
if (mce->status & MCI_STATUS_UC) {
if ((vcpu->arch.mcg_status & MCG_STATUS_MCIP) ||
!kvm_read_cr4_bits(vcpu, X86_CR4_MCE)) {
kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
return 0;
}
if (banks[1] & MCI_STATUS_VAL)
mce->status |= MCI_STATUS_OVER;
banks[2] = mce->addr;
banks[3] = mce->misc;
vcpu->arch.mcg_status = mce->mcg_status;
banks[1] = mce->status;
kvm_queue_exception(vcpu, MC_VECTOR);
} else if (!(banks[1] & MCI_STATUS_VAL)
|| !(banks[1] & MCI_STATUS_UC)) {
if (banks[1] & MCI_STATUS_VAL)
mce->status |= MCI_STATUS_OVER;
banks[2] = mce->addr;
banks[3] = mce->misc;
banks[1] = mce->status;
} else
banks[1] |= MCI_STATUS_OVER;
return 0;
}
static void kvm_vcpu_ioctl_x86_get_vcpu_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
process_nmi(vcpu);
events->exception.injected =
vcpu->arch.exception.pending &&
!kvm_exception_is_soft(vcpu->arch.exception.nr);
events->exception.nr = vcpu->arch.exception.nr;
events->exception.has_error_code = vcpu->arch.exception.has_error_code;
events->exception.pad = 0;
events->exception.error_code = vcpu->arch.exception.error_code;
events->interrupt.injected =
vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft;
events->interrupt.nr = vcpu->arch.interrupt.nr;
events->interrupt.soft = 0;
events->interrupt.shadow =
kvm_x86_ops->get_interrupt_shadow(vcpu,
KVM_X86_SHADOW_INT_MOV_SS | KVM_X86_SHADOW_INT_STI);
events->nmi.injected = vcpu->arch.nmi_injected;
events->nmi.pending = vcpu->arch.nmi_pending != 0;
events->nmi.masked = kvm_x86_ops->get_nmi_mask(vcpu);
events->nmi.pad = 0;
events->sipi_vector = 0; /* never valid when reporting to user space */
events->flags = (KVM_VCPUEVENT_VALID_NMI_PENDING
| KVM_VCPUEVENT_VALID_SHADOW);
memset(&events->reserved, 0, sizeof(events->reserved));
}
static int kvm_vcpu_ioctl_x86_set_vcpu_events(struct kvm_vcpu *vcpu,
struct kvm_vcpu_events *events)
{
if (events->flags & ~(KVM_VCPUEVENT_VALID_NMI_PENDING
| KVM_VCPUEVENT_VALID_SIPI_VECTOR
| KVM_VCPUEVENT_VALID_SHADOW))
return -EINVAL;
process_nmi(vcpu);
vcpu->arch.exception.pending = events->exception.injected;
vcpu->arch.exception.nr = events->exception.nr;
vcpu->arch.exception.has_error_code = events->exception.has_error_code;
vcpu->arch.exception.error_code = events->exception.error_code;
vcpu->arch.interrupt.pending = events->interrupt.injected;
vcpu->arch.interrupt.nr = events->interrupt.nr;
vcpu->arch.interrupt.soft = events->interrupt.soft;
if (events->flags & KVM_VCPUEVENT_VALID_SHADOW)
kvm_x86_ops->set_interrupt_shadow(vcpu,
events->interrupt.shadow);
vcpu->arch.nmi_injected = events->nmi.injected;
if (events->flags & KVM_VCPUEVENT_VALID_NMI_PENDING)
vcpu->arch.nmi_pending = events->nmi.pending;
kvm_x86_ops->set_nmi_mask(vcpu, events->nmi.masked);
if (events->flags & KVM_VCPUEVENT_VALID_SIPI_VECTOR &&
kvm_vcpu_has_lapic(vcpu))
vcpu->arch.apic->sipi_vector = events->sipi_vector;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
static void kvm_vcpu_ioctl_x86_get_debugregs(struct kvm_vcpu *vcpu,
struct kvm_debugregs *dbgregs)
{
memcpy(dbgregs->db, vcpu->arch.db, sizeof(vcpu->arch.db));
dbgregs->dr6 = vcpu->arch.dr6;
dbgregs->dr7 = vcpu->arch.dr7;
dbgregs->flags = 0;
memset(&dbgregs->reserved, 0, sizeof(dbgregs->reserved));
}
static int kvm_vcpu_ioctl_x86_set_debugregs(struct kvm_vcpu *vcpu,
struct kvm_debugregs *dbgregs)
{
if (dbgregs->flags)
return -EINVAL;
memcpy(vcpu->arch.db, dbgregs->db, sizeof(vcpu->arch.db));
vcpu->arch.dr6 = dbgregs->dr6;
vcpu->arch.dr7 = dbgregs->dr7;
return 0;
}
static void kvm_vcpu_ioctl_x86_get_xsave(struct kvm_vcpu *vcpu,
struct kvm_xsave *guest_xsave)
{
if (cpu_has_xsave) {
memcpy(guest_xsave->region,
&vcpu->arch.guest_fpu.state->xsave,
vcpu->arch.guest_xstate_size);
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] &=
vcpu->arch.guest_supported_xcr0 | XSTATE_FPSSE;
} else {
memcpy(guest_xsave->region,
&vcpu->arch.guest_fpu.state->fxsave,
sizeof(struct i387_fxsave_struct));
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)] =
XSTATE_FPSSE;
}
}
static int kvm_vcpu_ioctl_x86_set_xsave(struct kvm_vcpu *vcpu,
struct kvm_xsave *guest_xsave)
{
u64 xstate_bv =
*(u64 *)&guest_xsave->region[XSAVE_HDR_OFFSET / sizeof(u32)];
if (cpu_has_xsave) {
/*
* Here we allow setting states that are not present in
* CPUID leaf 0xD, index 0, EDX:EAX. This is for compatibility
* with old userspace.
*/
if (xstate_bv & ~KVM_SUPPORTED_XCR0)
return -EINVAL;
if (xstate_bv & ~host_xcr0)
return -EINVAL;
memcpy(&vcpu->arch.guest_fpu.state->xsave,
guest_xsave->region, vcpu->arch.guest_xstate_size);
} else {
if (xstate_bv & ~XSTATE_FPSSE)
return -EINVAL;
memcpy(&vcpu->arch.guest_fpu.state->fxsave,
guest_xsave->region, sizeof(struct i387_fxsave_struct));
}
return 0;
}
static void kvm_vcpu_ioctl_x86_get_xcrs(struct kvm_vcpu *vcpu,
struct kvm_xcrs *guest_xcrs)
{
if (!cpu_has_xsave) {
guest_xcrs->nr_xcrs = 0;
return;
}
guest_xcrs->nr_xcrs = 1;
guest_xcrs->flags = 0;
guest_xcrs->xcrs[0].xcr = XCR_XFEATURE_ENABLED_MASK;
guest_xcrs->xcrs[0].value = vcpu->arch.xcr0;
}
static int kvm_vcpu_ioctl_x86_set_xcrs(struct kvm_vcpu *vcpu,
struct kvm_xcrs *guest_xcrs)
{
int i, r = 0;
if (!cpu_has_xsave)
return -EINVAL;
if (guest_xcrs->nr_xcrs > KVM_MAX_XCRS || guest_xcrs->flags)
return -EINVAL;
for (i = 0; i < guest_xcrs->nr_xcrs; i++)
/* Only support XCR0 currently */
if (guest_xcrs->xcrs[i].xcr == XCR_XFEATURE_ENABLED_MASK) {
r = __kvm_set_xcr(vcpu, XCR_XFEATURE_ENABLED_MASK,
guest_xcrs->xcrs[i].value);
break;
}
if (r)
r = -EINVAL;
return r;
}
/*
* kvm_set_guest_paused() indicates to the guest kernel that it has been
* stopped by the hypervisor. This function will be called from the host only.
* EINVAL is returned when the host attempts to set the flag for a guest that
* does not support pv clocks.
*/
static int kvm_set_guest_paused(struct kvm_vcpu *vcpu)
{
if (!vcpu->arch.pv_time_enabled)
return -EINVAL;
vcpu->arch.pvclock_set_guest_stopped_request = true;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
return 0;
}
long kvm_arch_vcpu_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm_vcpu *vcpu = filp->private_data;
void __user *argp = (void __user *)arg;
int r;
union {
struct kvm_lapic_state *lapic;
struct kvm_xsave *xsave;
struct kvm_xcrs *xcrs;
void *buffer;
} u;
u.buffer = NULL;
switch (ioctl) {
case KVM_GET_LAPIC: {
r = -EINVAL;
if (!vcpu->arch.apic)
goto out;
u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL);
r = -ENOMEM;
if (!u.lapic)
goto out;
r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state)))
goto out;
r = 0;
break;
}
case KVM_SET_LAPIC: {
r = -EINVAL;
if (!vcpu->arch.apic)
goto out;
u.lapic = memdup_user(argp, sizeof(*u.lapic));
if (IS_ERR(u.lapic))
return PTR_ERR(u.lapic);
r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic);
break;
}
case KVM_INTERRUPT: {
struct kvm_interrupt irq;
r = -EFAULT;
if (copy_from_user(&irq, argp, sizeof irq))
goto out;
r = kvm_vcpu_ioctl_interrupt(vcpu, &irq);
break;
}
case KVM_NMI: {
r = kvm_vcpu_ioctl_nmi(vcpu);
break;
}
case KVM_SET_CPUID: {
struct kvm_cpuid __user *cpuid_arg = argp;
struct kvm_cpuid cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries);
break;
}
case KVM_SET_CPUID2: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid,
cpuid_arg->entries);
break;
}
case KVM_GET_CPUID2: {
struct kvm_cpuid2 __user *cpuid_arg = argp;
struct kvm_cpuid2 cpuid;
r = -EFAULT;
if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid))
goto out;
r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid,
cpuid_arg->entries);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid))
goto out;
r = 0;
break;
}
case KVM_GET_MSRS:
r = msr_io(vcpu, argp, kvm_get_msr, 1);
break;
case KVM_SET_MSRS:
r = msr_io(vcpu, argp, do_set_msr, 0);
break;
case KVM_TPR_ACCESS_REPORTING: {
struct kvm_tpr_access_ctl tac;
r = -EFAULT;
if (copy_from_user(&tac, argp, sizeof tac))
goto out;
r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &tac, sizeof tac))
goto out;
r = 0;
break;
};
case KVM_SET_VAPIC_ADDR: {
struct kvm_vapic_addr va;
r = -EINVAL;
if (!irqchip_in_kernel(vcpu->kvm))
goto out;
r = -EFAULT;
if (copy_from_user(&va, argp, sizeof va))
goto out;
r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr);
break;
}
case KVM_X86_SETUP_MCE: {
u64 mcg_cap;
r = -EFAULT;
if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap))
goto out;
r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap);
break;
}
case KVM_X86_SET_MCE: {
struct kvm_x86_mce mce;
r = -EFAULT;
if (copy_from_user(&mce, argp, sizeof mce))
goto out;
r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce);
break;
}
case KVM_GET_VCPU_EVENTS: {
struct kvm_vcpu_events events;
kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events);
r = -EFAULT;
if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events)))
break;
r = 0;
break;
}
case KVM_SET_VCPU_EVENTS: {
struct kvm_vcpu_events events;
r = -EFAULT;
if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events)))
break;
r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events);
break;
}
case KVM_GET_DEBUGREGS: {
struct kvm_debugregs dbgregs;
kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs);
r = -EFAULT;
if (copy_to_user(argp, &dbgregs,
sizeof(struct kvm_debugregs)))
break;
r = 0;
break;
}
case KVM_SET_DEBUGREGS: {
struct kvm_debugregs dbgregs;
r = -EFAULT;
if (copy_from_user(&dbgregs, argp,
sizeof(struct kvm_debugregs)))
break;
r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs);
break;
}
case KVM_GET_XSAVE: {
u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL);
r = -ENOMEM;
if (!u.xsave)
break;
kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave);
r = -EFAULT;
if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave)))
break;
r = 0;
break;
}
case KVM_SET_XSAVE: {
u.xsave = memdup_user(argp, sizeof(*u.xsave));
if (IS_ERR(u.xsave))
return PTR_ERR(u.xsave);
r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave);
break;
}
case KVM_GET_XCRS: {
u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL);
r = -ENOMEM;
if (!u.xcrs)
break;
kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs);
r = -EFAULT;
if (copy_to_user(argp, u.xcrs,
sizeof(struct kvm_xcrs)))
break;
r = 0;
break;
}
case KVM_SET_XCRS: {
u.xcrs = memdup_user(argp, sizeof(*u.xcrs));
if (IS_ERR(u.xcrs))
return PTR_ERR(u.xcrs);
r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs);
break;
}
case KVM_SET_TSC_KHZ: {
u32 user_tsc_khz;
r = -EINVAL;
user_tsc_khz = (u32)arg;
if (user_tsc_khz >= kvm_max_guest_tsc_khz)
goto out;
if (user_tsc_khz == 0)
user_tsc_khz = tsc_khz;
kvm_set_tsc_khz(vcpu, user_tsc_khz);
r = 0;
goto out;
}
case KVM_GET_TSC_KHZ: {
r = vcpu->arch.virtual_tsc_khz;
goto out;
}
case KVM_KVMCLOCK_CTRL: {
r = kvm_set_guest_paused(vcpu);
goto out;
}
default:
r = -EINVAL;
}
out:
kfree(u.buffer);
return r;
}
int kvm_arch_vcpu_fault(struct kvm_vcpu *vcpu, struct vm_fault *vmf)
{
return VM_FAULT_SIGBUS;
}
static int kvm_vm_ioctl_set_tss_addr(struct kvm *kvm, unsigned long addr)
{
int ret;
if (addr > (unsigned int)(-3 * PAGE_SIZE))
return -EINVAL;
ret = kvm_x86_ops->set_tss_addr(kvm, addr);
return ret;
}
static int kvm_vm_ioctl_set_identity_map_addr(struct kvm *kvm,
u64 ident_addr)
{
kvm->arch.ept_identity_map_addr = ident_addr;
return 0;
}
static int kvm_vm_ioctl_set_nr_mmu_pages(struct kvm *kvm,
u32 kvm_nr_mmu_pages)
{
if (kvm_nr_mmu_pages < KVM_MIN_ALLOC_MMU_PAGES)
return -EINVAL;
mutex_lock(&kvm->slots_lock);
kvm_mmu_change_mmu_pages(kvm, kvm_nr_mmu_pages);
kvm->arch.n_requested_mmu_pages = kvm_nr_mmu_pages;
mutex_unlock(&kvm->slots_lock);
return 0;
}
static int kvm_vm_ioctl_get_nr_mmu_pages(struct kvm *kvm)
{
return kvm->arch.n_max_mmu_pages;
}
static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
{
int r;
r = 0;
switch (chip->chip_id) {
case KVM_IRQCHIP_PIC_MASTER:
memcpy(&chip->chip.pic,
&pic_irqchip(kvm)->pics[0],
sizeof(struct kvm_pic_state));
break;
case KVM_IRQCHIP_PIC_SLAVE:
memcpy(&chip->chip.pic,
&pic_irqchip(kvm)->pics[1],
sizeof(struct kvm_pic_state));
break;
case KVM_IRQCHIP_IOAPIC:
r = kvm_get_ioapic(kvm, &chip->chip.ioapic);
break;
default:
r = -EINVAL;
break;
}
return r;
}
static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip)
{
int r;
r = 0;
switch (chip->chip_id) {
case KVM_IRQCHIP_PIC_MASTER:
spin_lock(&pic_irqchip(kvm)->lock);
memcpy(&pic_irqchip(kvm)->pics[0],
&chip->chip.pic,
sizeof(struct kvm_pic_state));
spin_unlock(&pic_irqchip(kvm)->lock);
break;
case KVM_IRQCHIP_PIC_SLAVE:
spin_lock(&pic_irqchip(kvm)->lock);
memcpy(&pic_irqchip(kvm)->pics[1],
&chip->chip.pic,
sizeof(struct kvm_pic_state));
spin_unlock(&pic_irqchip(kvm)->lock);
break;
case KVM_IRQCHIP_IOAPIC:
r = kvm_set_ioapic(kvm, &chip->chip.ioapic);
break;
default:
r = -EINVAL;
break;
}
kvm_pic_update_irq(pic_irqchip(kvm));
return r;
}
static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(ps, &kvm->arch.vpit->pit_state, sizeof(struct kvm_pit_state));
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int r = 0;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
memcpy(ps->channels, &kvm->arch.vpit->pit_state.channels,
sizeof(ps->channels));
ps->flags = kvm->arch.vpit->pit_state.flags;
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
memset(&ps->reserved, 0, sizeof(ps->reserved));
return r;
}
static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps)
{
int r = 0, start = 0;
u32 prev_legacy, cur_legacy;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
prev_legacy = kvm->arch.vpit->pit_state.flags & KVM_PIT_FLAGS_HPET_LEGACY;
cur_legacy = ps->flags & KVM_PIT_FLAGS_HPET_LEGACY;
if (!prev_legacy && cur_legacy)
start = 1;
memcpy(&kvm->arch.vpit->pit_state.channels, &ps->channels,
sizeof(kvm->arch.vpit->pit_state.channels));
kvm->arch.vpit->pit_state.flags = ps->flags;
kvm_pit_load_count(kvm, 0, kvm->arch.vpit->pit_state.channels[0].count, start);
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return r;
}
static int kvm_vm_ioctl_reinject(struct kvm *kvm,
struct kvm_reinject_control *control)
{
if (!kvm->arch.vpit)
return -ENXIO;
mutex_lock(&kvm->arch.vpit->pit_state.lock);
kvm->arch.vpit->pit_state.reinject = control->pit_reinject;
mutex_unlock(&kvm->arch.vpit->pit_state.lock);
return 0;
}
/**
* kvm_vm_ioctl_get_dirty_log - get and clear the log of dirty pages in a slot
* @kvm: kvm instance
* @log: slot id and address to which we copy the log
*
* We need to keep it in mind that VCPU threads can write to the bitmap
* concurrently. So, to avoid losing data, we keep the following order for
* each bit:
*
* 1. Take a snapshot of the bit and clear it if needed.
* 2. Write protect the corresponding page.
* 3. Flush TLB's if needed.
* 4. Copy the snapshot to the userspace.
*
* Between 2 and 3, the guest may write to the page using the remaining TLB
* entry. This is not a problem because the page will be reported dirty at
* step 4 using the snapshot taken before and step 3 ensures that successive
* writes will be logged for the next call.
*/
int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log)
{
int r;
struct kvm_memory_slot *memslot;
unsigned long n, i;
unsigned long *dirty_bitmap;
unsigned long *dirty_bitmap_buffer;
bool is_dirty = false;
mutex_lock(&kvm->slots_lock);
r = -EINVAL;
if (log->slot >= KVM_USER_MEM_SLOTS)
goto out;
memslot = id_to_memslot(kvm->memslots, log->slot);
dirty_bitmap = memslot->dirty_bitmap;
r = -ENOENT;
if (!dirty_bitmap)
goto out;
n = kvm_dirty_bitmap_bytes(memslot);
dirty_bitmap_buffer = dirty_bitmap + n / sizeof(long);
memset(dirty_bitmap_buffer, 0, n);
spin_lock(&kvm->mmu_lock);
for (i = 0; i < n / sizeof(long); i++) {
unsigned long mask;
gfn_t offset;
if (!dirty_bitmap[i])
continue;
is_dirty = true;
mask = xchg(&dirty_bitmap[i], 0);
dirty_bitmap_buffer[i] = mask;
offset = i * BITS_PER_LONG;
kvm_mmu_write_protect_pt_masked(kvm, memslot, offset, mask);
}
if (is_dirty)
kvm_flush_remote_tlbs(kvm);
spin_unlock(&kvm->mmu_lock);
r = -EFAULT;
if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
goto out;
r = 0;
out:
mutex_unlock(&kvm->slots_lock);
return r;
}
int kvm_vm_ioctl_irq_line(struct kvm *kvm, struct kvm_irq_level *irq_event,
bool line_status)
{
if (!irqchip_in_kernel(kvm))
return -ENXIO;
irq_event->status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID,
irq_event->irq, irq_event->level,
line_status);
return 0;
}
long kvm_arch_vm_ioctl(struct file *filp,
unsigned int ioctl, unsigned long arg)
{
struct kvm *kvm = filp->private_data;
void __user *argp = (void __user *)arg;
int r = -ENOTTY;
/*
* This union makes it completely explicit to gcc-3.x
* that these two variables' stack usage should be
* combined, not added together.
*/
union {
struct kvm_pit_state ps;
struct kvm_pit_state2 ps2;
struct kvm_pit_config pit_config;
} u;
switch (ioctl) {
case KVM_SET_TSS_ADDR:
r = kvm_vm_ioctl_set_tss_addr(kvm, arg);
break;
case KVM_SET_IDENTITY_MAP_ADDR: {
u64 ident_addr;
r = -EFAULT;
if (copy_from_user(&ident_addr, argp, sizeof ident_addr))
goto out;
r = kvm_vm_ioctl_set_identity_map_addr(kvm, ident_addr);
break;
}
case KVM_SET_NR_MMU_PAGES:
r = kvm_vm_ioctl_set_nr_mmu_pages(kvm, arg);
break;
case KVM_GET_NR_MMU_PAGES:
r = kvm_vm_ioctl_get_nr_mmu_pages(kvm);
break;
case KVM_CREATE_IRQCHIP: {
struct kvm_pic *vpic;
mutex_lock(&kvm->lock);
r = -EEXIST;
if (kvm->arch.vpic)
goto create_irqchip_unlock;
r = -EINVAL;
if (atomic_read(&kvm->online_vcpus))
goto create_irqchip_unlock;
r = -ENOMEM;
vpic = kvm_create_pic(kvm);
if (vpic) {
r = kvm_ioapic_init(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_master);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_slave);
kvm_io_bus_unregister_dev(kvm, KVM_PIO_BUS,
&vpic->dev_eclr);
mutex_unlock(&kvm->slots_lock);
kfree(vpic);
goto create_irqchip_unlock;
}
} else
goto create_irqchip_unlock;
smp_wmb();
kvm->arch.vpic = vpic;
smp_wmb();
r = kvm_setup_default_irq_routing(kvm);
if (r) {
mutex_lock(&kvm->slots_lock);
mutex_lock(&kvm->irq_lock);
kvm_ioapic_destroy(kvm);
kvm_destroy_pic(kvm);
mutex_unlock(&kvm->irq_lock);
mutex_unlock(&kvm->slots_lock);
}
create_irqchip_unlock:
mutex_unlock(&kvm->lock);
break;
}
case KVM_CREATE_PIT:
u.pit_config.flags = KVM_PIT_SPEAKER_DUMMY;
goto create_pit;
case KVM_CREATE_PIT2:
r = -EFAULT;
if (copy_from_user(&u.pit_config, argp,
sizeof(struct kvm_pit_config)))
goto out;
create_pit:
mutex_lock(&kvm->slots_lock);
r = -EEXIST;
if (kvm->arch.vpit)
goto create_pit_unlock;
r = -ENOMEM;
kvm->arch.vpit = kvm_create_pit(kvm, u.pit_config.flags);
if (kvm->arch.vpit)
r = 0;
create_pit_unlock:
mutex_unlock(&kvm->slots_lock);
break;
case KVM_GET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto get_irqchip_out;
r = kvm_vm_ioctl_get_irqchip(kvm, chip);
if (r)
goto get_irqchip_out;
r = -EFAULT;
if (copy_to_user(argp, chip, sizeof *chip))
goto get_irqchip_out;
r = 0;
get_irqchip_out:
kfree(chip);
break;
}
case KVM_SET_IRQCHIP: {
/* 0: PIC master, 1: PIC slave, 2: IOAPIC */
struct kvm_irqchip *chip;
chip = memdup_user(argp, sizeof(*chip));
if (IS_ERR(chip)) {
r = PTR_ERR(chip);
goto out;
}
r = -ENXIO;
if (!irqchip_in_kernel(kvm))
goto set_irqchip_out;
r = kvm_vm_ioctl_set_irqchip(kvm, chip);
if (r)
goto set_irqchip_out;
r = 0;
set_irqchip_out:
kfree(chip);
break;
}
case KVM_GET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof(struct kvm_pit_state)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit(kvm, &u.ps);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps, sizeof(struct kvm_pit_state)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT: {
r = -EFAULT;
if (copy_from_user(&u.ps, argp, sizeof u.ps))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit(kvm, &u.ps);
break;
}
case KVM_GET_PIT2: {
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_get_pit2(kvm, &u.ps2);
if (r)
goto out;
r = -EFAULT;
if (copy_to_user(argp, &u.ps2, sizeof(u.ps2)))
goto out;
r = 0;
break;
}
case KVM_SET_PIT2: {
r = -EFAULT;
if (copy_from_user(&u.ps2, argp, sizeof(u.ps2)))
goto out;
r = -ENXIO;
if (!kvm->arch.vpit)
goto out;
r = kvm_vm_ioctl_set_pit2(kvm, &u.ps2);
break;
}
case KVM_REINJECT_CONTROL: {
struct kvm_reinject_control control;
r = -EFAULT;
if (copy_from_user(&control, argp, sizeof(control)))
goto out;
r = kvm_vm_ioctl_reinject(kvm, &control);
break;
}
case KVM_XEN_HVM_CONFIG: {
r = -EFAULT;
if (copy_from_user(&kvm->arch.xen_hvm_config, argp,
sizeof(struct kvm_xen_hvm_config)))
goto out;
r = -EINVAL;
if (kvm->arch.xen_hvm_config.flags)
goto out;
r = 0;
break;
}
case KVM_SET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
s64 delta;
r = -EFAULT;
if (copy_from_user(&user_ns, argp, sizeof(user_ns)))
goto out;
r = -EINVAL;
if (user_ns.flags)
goto out;
r = 0;
local_irq_disable();
now_ns = get_kernel_ns();
delta = user_ns.clock - now_ns;
local_irq_enable();
kvm->arch.kvmclock_offset = delta;
kvm_gen_update_masterclock(kvm);
break;
}
case KVM_GET_CLOCK: {
struct kvm_clock_data user_ns;
u64 now_ns;
local_irq_disable();
now_ns = get_kernel_ns();
user_ns.clock = kvm->arch.kvmclock_offset + now_ns;
local_irq_enable();
user_ns.flags = 0;
memset(&user_ns.pad, 0, sizeof(user_ns.pad));
r = -EFAULT;
if (copy_to_user(argp, &user_ns, sizeof(user_ns)))
goto out;
r = 0;
break;
}
default:
;
}
out:
return r;
}
static void kvm_init_msr_list(void)
{
u32 dummy[2];
unsigned i, j;
/* skip the first msrs in the list. KVM-specific */
for (i = j = KVM_SAVE_MSRS_BEGIN; i < ARRAY_SIZE(msrs_to_save); i++) {
if (rdmsr_safe(msrs_to_save[i], &dummy[0], &dummy[1]) < 0)
continue;
if (j < i)
msrs_to_save[j] = msrs_to_save[i];
j++;
}
num_msrs_to_save = j;
}
static int vcpu_mmio_write(struct kvm_vcpu *vcpu, gpa_t addr, int len,
const void *v)
{
int handled = 0;
int n;
do {
n = min(len, 8);
if (!(vcpu->arch.apic &&
!kvm_iodevice_write(&vcpu->arch.apic->dev, addr, n, v))
&& kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
break;
handled += n;
addr += n;
len -= n;
v += n;
} while (len);
return handled;
}
static int vcpu_mmio_read(struct kvm_vcpu *vcpu, gpa_t addr, int len, void *v)
{
int handled = 0;
int n;
do {
n = min(len, 8);
if (!(vcpu->arch.apic &&
!kvm_iodevice_read(&vcpu->arch.apic->dev, addr, n, v))
&& kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, addr, n, v))
break;
trace_kvm_mmio(KVM_TRACE_MMIO_READ, n, addr, *(u64 *)v);
handled += n;
addr += n;
len -= n;
v += n;
} while (len);
return handled;
}
static void kvm_set_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
kvm_x86_ops->set_segment(vcpu, var, seg);
}
void kvm_get_segment(struct kvm_vcpu *vcpu,
struct kvm_segment *var, int seg)
{
kvm_x86_ops->get_segment(vcpu, var, seg);
}
gpa_t translate_nested_gpa(struct kvm_vcpu *vcpu, gpa_t gpa, u32 access)
{
gpa_t t_gpa;
struct x86_exception exception;
BUG_ON(!mmu_is_nested(vcpu));
/* NPT walks are always user-walks */
access |= PFERR_USER_MASK;
t_gpa = vcpu->arch.mmu.gva_to_gpa(vcpu, gpa, access, &exception);
return t_gpa;
}
gpa_t kvm_mmu_gva_to_gpa_read(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
gpa_t kvm_mmu_gva_to_gpa_fetch(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
access |= PFERR_FETCH_MASK;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
gpa_t kvm_mmu_gva_to_gpa_write(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
access |= PFERR_WRITE_MASK;
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
}
/* uses this to access any guest's mapped memory without checking CPL */
gpa_t kvm_mmu_gva_to_gpa_system(struct kvm_vcpu *vcpu, gva_t gva,
struct x86_exception *exception)
{
return vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, 0, exception);
}
static int kvm_read_guest_virt_helper(gva_t addr, void *val, unsigned int bytes,
struct kvm_vcpu *vcpu, u32 access,
struct x86_exception *exception)
{
void *data = val;
int r = X86EMUL_CONTINUE;
while (bytes) {
gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr, access,
exception);
unsigned offset = addr & (PAGE_SIZE-1);
unsigned toread = min(bytes, (unsigned)PAGE_SIZE - offset);
int ret;
if (gpa == UNMAPPED_GVA)
return X86EMUL_PROPAGATE_FAULT;
ret = kvm_read_guest(vcpu->kvm, gpa, data, toread);
if (ret < 0) {
r = X86EMUL_IO_NEEDED;
goto out;
}
bytes -= toread;
data += toread;
addr += toread;
}
out:
return r;
}
/* used for instruction fetching */
static int kvm_fetch_guest_virt(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu,
access | PFERR_FETCH_MASK,
exception);
}
int kvm_read_guest_virt(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
u32 access = (kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0;
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, access,
exception);
}
EXPORT_SYMBOL_GPL(kvm_read_guest_virt);
static int kvm_read_guest_virt_system(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val, unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
return kvm_read_guest_virt_helper(addr, val, bytes, vcpu, 0, exception);
}
int kvm_write_guest_virt_system(struct x86_emulate_ctxt *ctxt,
gva_t addr, void *val,
unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
void *data = val;
int r = X86EMUL_CONTINUE;
while (bytes) {
gpa_t gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, addr,
PFERR_WRITE_MASK,
exception);
unsigned offset = addr & (PAGE_SIZE-1);
unsigned towrite = min(bytes, (unsigned)PAGE_SIZE - offset);
int ret;
if (gpa == UNMAPPED_GVA)
return X86EMUL_PROPAGATE_FAULT;
ret = kvm_write_guest(vcpu->kvm, gpa, data, towrite);
if (ret < 0) {
r = X86EMUL_IO_NEEDED;
goto out;
}
bytes -= towrite;
data += towrite;
addr += towrite;
}
out:
return r;
}
EXPORT_SYMBOL_GPL(kvm_write_guest_virt_system);
static int vcpu_mmio_gva_to_gpa(struct kvm_vcpu *vcpu, unsigned long gva,
gpa_t *gpa, struct x86_exception *exception,
bool write)
{
u32 access = ((kvm_x86_ops->get_cpl(vcpu) == 3) ? PFERR_USER_MASK : 0)
| (write ? PFERR_WRITE_MASK : 0);
if (vcpu_match_mmio_gva(vcpu, gva)
&& !permission_fault(vcpu->arch.walk_mmu, vcpu->arch.access, access)) {
*gpa = vcpu->arch.mmio_gfn << PAGE_SHIFT |
(gva & (PAGE_SIZE - 1));
trace_vcpu_match_mmio(gva, *gpa, write, false);
return 1;
}
*gpa = vcpu->arch.walk_mmu->gva_to_gpa(vcpu, gva, access, exception);
if (*gpa == UNMAPPED_GVA)
return -1;
/* For APIC access vmexit */
if ((*gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
return 1;
if (vcpu_match_mmio_gpa(vcpu, *gpa)) {
trace_vcpu_match_mmio(gva, *gpa, write, true);
return 1;
}
return 0;
}
int emulator_write_phys(struct kvm_vcpu *vcpu, gpa_t gpa,
const void *val, int bytes)
{
int ret;
ret = kvm_write_guest(vcpu->kvm, gpa, val, bytes);
if (ret < 0)
return 0;
kvm_mmu_pte_write(vcpu, gpa, val, bytes);
return 1;
}
struct read_write_emulator_ops {
int (*read_write_prepare)(struct kvm_vcpu *vcpu, void *val,
int bytes);
int (*read_write_emulate)(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes);
int (*read_write_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
int bytes, void *val);
int (*read_write_exit_mmio)(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes);
bool write;
};
static int read_prepare(struct kvm_vcpu *vcpu, void *val, int bytes)
{
if (vcpu->mmio_read_completed) {
trace_kvm_mmio(KVM_TRACE_MMIO_READ, bytes,
vcpu->mmio_fragments[0].gpa, *(u64 *)val);
vcpu->mmio_read_completed = 0;
return 1;
}
return 0;
}
static int read_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
return !kvm_read_guest(vcpu->kvm, gpa, val, bytes);
}
static int write_emulate(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
return emulator_write_phys(vcpu, gpa, val, bytes);
}
static int write_mmio(struct kvm_vcpu *vcpu, gpa_t gpa, int bytes, void *val)
{
trace_kvm_mmio(KVM_TRACE_MMIO_WRITE, bytes, gpa, *(u64 *)val);
return vcpu_mmio_write(vcpu, gpa, bytes, val);
}
static int read_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
trace_kvm_mmio(KVM_TRACE_MMIO_READ_UNSATISFIED, bytes, gpa, 0);
return X86EMUL_IO_NEEDED;
}
static int write_exit_mmio(struct kvm_vcpu *vcpu, gpa_t gpa,
void *val, int bytes)
{
struct kvm_mmio_fragment *frag = &vcpu->mmio_fragments[0];
memcpy(vcpu->run->mmio.data, frag->data, min(8u, frag->len));
return X86EMUL_CONTINUE;
}
static const struct read_write_emulator_ops read_emultor = {
.read_write_prepare = read_prepare,
.read_write_emulate = read_emulate,
.read_write_mmio = vcpu_mmio_read,
.read_write_exit_mmio = read_exit_mmio,
};
static const struct read_write_emulator_ops write_emultor = {
.read_write_emulate = write_emulate,
.read_write_mmio = write_mmio,
.read_write_exit_mmio = write_exit_mmio,
.write = true,
};
static int emulator_read_write_onepage(unsigned long addr, void *val,
unsigned int bytes,
struct x86_exception *exception,
struct kvm_vcpu *vcpu,
const struct read_write_emulator_ops *ops)
{
gpa_t gpa;
int handled, ret;
bool write = ops->write;
struct kvm_mmio_fragment *frag;
ret = vcpu_mmio_gva_to_gpa(vcpu, addr, &gpa, exception, write);
if (ret < 0)
return X86EMUL_PROPAGATE_FAULT;
/* For APIC access vmexit */
if (ret)
goto mmio;
if (ops->read_write_emulate(vcpu, gpa, val, bytes))
return X86EMUL_CONTINUE;
mmio:
/*
* Is this MMIO handled locally?
*/
handled = ops->read_write_mmio(vcpu, gpa, bytes, val);
if (handled == bytes)
return X86EMUL_CONTINUE;
gpa += handled;
bytes -= handled;
val += handled;
WARN_ON(vcpu->mmio_nr_fragments >= KVM_MAX_MMIO_FRAGMENTS);
frag = &vcpu->mmio_fragments[vcpu->mmio_nr_fragments++];
frag->gpa = gpa;
frag->data = val;
frag->len = bytes;
return X86EMUL_CONTINUE;
}
int emulator_read_write(struct x86_emulate_ctxt *ctxt, unsigned long addr,
void *val, unsigned int bytes,
struct x86_exception *exception,
const struct read_write_emulator_ops *ops)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
gpa_t gpa;
int rc;
if (ops->read_write_prepare &&
ops->read_write_prepare(vcpu, val, bytes))
return X86EMUL_CONTINUE;
vcpu->mmio_nr_fragments = 0;
/* Crossing a page boundary? */
if (((addr + bytes - 1) ^ addr) & PAGE_MASK) {
int now;
now = -addr & ~PAGE_MASK;
rc = emulator_read_write_onepage(addr, val, now, exception,
vcpu, ops);
if (rc != X86EMUL_CONTINUE)
return rc;
addr += now;
val += now;
bytes -= now;
}
rc = emulator_read_write_onepage(addr, val, bytes, exception,
vcpu, ops);
if (rc != X86EMUL_CONTINUE)
return rc;
if (!vcpu->mmio_nr_fragments)
return rc;
gpa = vcpu->mmio_fragments[0].gpa;
vcpu->mmio_needed = 1;
vcpu->mmio_cur_fragment = 0;
vcpu->run->mmio.len = min(8u, vcpu->mmio_fragments[0].len);
vcpu->run->mmio.is_write = vcpu->mmio_is_write = ops->write;
vcpu->run->exit_reason = KVM_EXIT_MMIO;
vcpu->run->mmio.phys_addr = gpa;
return ops->read_write_exit_mmio(vcpu, gpa, val, bytes);
}
static int emulator_read_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
void *val,
unsigned int bytes,
struct x86_exception *exception)
{
return emulator_read_write(ctxt, addr, val, bytes,
exception, &read_emultor);
}
int emulator_write_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
const void *val,
unsigned int bytes,
struct x86_exception *exception)
{
return emulator_read_write(ctxt, addr, (void *)val, bytes,
exception, &write_emultor);
}
#define CMPXCHG_TYPE(t, ptr, old, new) \
(cmpxchg((t *)(ptr), *(t *)(old), *(t *)(new)) == *(t *)(old))
#ifdef CONFIG_X86_64
# define CMPXCHG64(ptr, old, new) CMPXCHG_TYPE(u64, ptr, old, new)
#else
# define CMPXCHG64(ptr, old, new) \
(cmpxchg64((u64 *)(ptr), *(u64 *)(old), *(u64 *)(new)) == *(u64 *)(old))
#endif
static int emulator_cmpxchg_emulated(struct x86_emulate_ctxt *ctxt,
unsigned long addr,
const void *old,
const void *new,
unsigned int bytes,
struct x86_exception *exception)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
gpa_t gpa;
struct page *page;
char *kaddr;
bool exchanged;
/* guests cmpxchg8b have to be emulated atomically */
if (bytes > 8 || (bytes & (bytes - 1)))
goto emul_write;
gpa = kvm_mmu_gva_to_gpa_write(vcpu, addr, NULL);
if (gpa == UNMAPPED_GVA ||
(gpa & PAGE_MASK) == APIC_DEFAULT_PHYS_BASE)
goto emul_write;
if (((gpa + bytes - 1) & PAGE_MASK) != (gpa & PAGE_MASK))
goto emul_write;
page = gfn_to_page(vcpu->kvm, gpa >> PAGE_SHIFT);
if (is_error_page(page))
goto emul_write;
kaddr = kmap_atomic(page);
kaddr += offset_in_page(gpa);
switch (bytes) {
case 1:
exchanged = CMPXCHG_TYPE(u8, kaddr, old, new);
break;
case 2:
exchanged = CMPXCHG_TYPE(u16, kaddr, old, new);
break;
case 4:
exchanged = CMPXCHG_TYPE(u32, kaddr, old, new);
break;
case 8:
exchanged = CMPXCHG64(kaddr, old, new);
break;
default:
BUG();
}
kunmap_atomic(kaddr);
kvm_release_page_dirty(page);
if (!exchanged)
return X86EMUL_CMPXCHG_FAILED;
kvm_mmu_pte_write(vcpu, gpa, new, bytes);
return X86EMUL_CONTINUE;
emul_write:
printk_once(KERN_WARNING "kvm: emulating exchange as write\n");
return emulator_write_emulated(ctxt, addr, new, bytes, exception);
}
static int kernel_pio(struct kvm_vcpu *vcpu, void *pd)
{
/* TODO: String I/O for in kernel device */
int r;
if (vcpu->arch.pio.in)
r = kvm_io_bus_read(vcpu->kvm, KVM_PIO_BUS, vcpu->arch.pio.port,
vcpu->arch.pio.size, pd);
else
r = kvm_io_bus_write(vcpu->kvm, KVM_PIO_BUS,
vcpu->arch.pio.port, vcpu->arch.pio.size,
pd);
return r;
}
static int emulator_pio_in_out(struct kvm_vcpu *vcpu, int size,
unsigned short port, void *val,
unsigned int count, bool in)
{
trace_kvm_pio(!in, port, size, count);
vcpu->arch.pio.port = port;
vcpu->arch.pio.in = in;
vcpu->arch.pio.count = count;
vcpu->arch.pio.size = size;
if (!kernel_pio(vcpu, vcpu->arch.pio_data)) {
vcpu->arch.pio.count = 0;
return 1;
}
vcpu->run->exit_reason = KVM_EXIT_IO;
vcpu->run->io.direction = in ? KVM_EXIT_IO_IN : KVM_EXIT_IO_OUT;
vcpu->run->io.size = size;
vcpu->run->io.data_offset = KVM_PIO_PAGE_OFFSET * PAGE_SIZE;
vcpu->run->io.count = count;
vcpu->run->io.port = port;
return 0;
}
static int emulator_pio_in_emulated(struct x86_emulate_ctxt *ctxt,
int size, unsigned short port, void *val,
unsigned int count)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
int ret;
if (vcpu->arch.pio.count)
goto data_avail;
ret = emulator_pio_in_out(vcpu, size, port, val, count, true);
if (ret) {
data_avail:
memcpy(val, vcpu->arch.pio_data, size * count);
vcpu->arch.pio.count = 0;
return 1;
}
return 0;
}
static int emulator_pio_out_emulated(struct x86_emulate_ctxt *ctxt,
int size, unsigned short port,
const void *val, unsigned int count)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
memcpy(vcpu->arch.pio_data, val, size * count);
return emulator_pio_in_out(vcpu, size, port, (void *)val, count, false);
}
static unsigned long get_segment_base(struct kvm_vcpu *vcpu, int seg)
{
return kvm_x86_ops->get_segment_base(vcpu, seg);
}
static void emulator_invlpg(struct x86_emulate_ctxt *ctxt, ulong address)
{
kvm_mmu_invlpg(emul_to_vcpu(ctxt), address);
}
int kvm_emulate_wbinvd(struct kvm_vcpu *vcpu)
{
if (!need_emulate_wbinvd(vcpu))
return X86EMUL_CONTINUE;
if (kvm_x86_ops->has_wbinvd_exit()) {
int cpu = get_cpu();
cpumask_set_cpu(cpu, vcpu->arch.wbinvd_dirty_mask);
smp_call_function_many(vcpu->arch.wbinvd_dirty_mask,
wbinvd_ipi, NULL, 1);
put_cpu();
cpumask_clear(vcpu->arch.wbinvd_dirty_mask);
} else
wbinvd();
return X86EMUL_CONTINUE;
}
EXPORT_SYMBOL_GPL(kvm_emulate_wbinvd);
static void emulator_wbinvd(struct x86_emulate_ctxt *ctxt)
{
kvm_emulate_wbinvd(emul_to_vcpu(ctxt));
}
int emulator_get_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long *dest)
{
return _kvm_get_dr(emul_to_vcpu(ctxt), dr, dest);
}
int emulator_set_dr(struct x86_emulate_ctxt *ctxt, int dr, unsigned long value)
{
return __kvm_set_dr(emul_to_vcpu(ctxt), dr, value);
}
static u64 mk_cr_64(u64 curr_cr, u32 new_val)
{
return (curr_cr & ~((1ULL << 32) - 1)) | new_val;
}
static unsigned long emulator_get_cr(struct x86_emulate_ctxt *ctxt, int cr)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
unsigned long value;
switch (cr) {
case 0:
value = kvm_read_cr0(vcpu);
break;
case 2:
value = vcpu->arch.cr2;
break;
case 3:
value = kvm_read_cr3(vcpu);
break;
case 4:
value = kvm_read_cr4(vcpu);
break;
case 8:
value = kvm_get_cr8(vcpu);
break;
default:
kvm_err("%s: unexpected cr %u\n", __func__, cr);
return 0;
}
return value;
}
static int emulator_set_cr(struct x86_emulate_ctxt *ctxt, int cr, ulong val)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
int res = 0;
switch (cr) {
case 0:
res = kvm_set_cr0(vcpu, mk_cr_64(kvm_read_cr0(vcpu), val));
break;
case 2:
vcpu->arch.cr2 = val;
break;
case 3:
res = kvm_set_cr3(vcpu, val);
break;
case 4:
res = kvm_set_cr4(vcpu, mk_cr_64(kvm_read_cr4(vcpu), val));
break;
case 8:
res = kvm_set_cr8(vcpu, val);
break;
default:
kvm_err("%s: unexpected cr %u\n", __func__, cr);
res = -1;
}
return res;
}
static void emulator_set_rflags(struct x86_emulate_ctxt *ctxt, ulong val)
{
kvm_set_rflags(emul_to_vcpu(ctxt), val);
}
static int emulator_get_cpl(struct x86_emulate_ctxt *ctxt)
{
return kvm_x86_ops->get_cpl(emul_to_vcpu(ctxt));
}
static void emulator_get_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->get_gdt(emul_to_vcpu(ctxt), dt);
}
static void emulator_get_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->get_idt(emul_to_vcpu(ctxt), dt);
}
static void emulator_set_gdt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->set_gdt(emul_to_vcpu(ctxt), dt);
}
static void emulator_set_idt(struct x86_emulate_ctxt *ctxt, struct desc_ptr *dt)
{
kvm_x86_ops->set_idt(emul_to_vcpu(ctxt), dt);
}
static unsigned long emulator_get_cached_segment_base(
struct x86_emulate_ctxt *ctxt, int seg)
{
return get_segment_base(emul_to_vcpu(ctxt), seg);
}
static bool emulator_get_segment(struct x86_emulate_ctxt *ctxt, u16 *selector,
struct desc_struct *desc, u32 *base3,
int seg)
{
struct kvm_segment var;
kvm_get_segment(emul_to_vcpu(ctxt), &var, seg);
*selector = var.selector;
if (var.unusable) {
memset(desc, 0, sizeof(*desc));
return false;
}
if (var.g)
var.limit >>= 12;
set_desc_limit(desc, var.limit);
set_desc_base(desc, (unsigned long)var.base);
#ifdef CONFIG_X86_64
if (base3)
*base3 = var.base >> 32;
#endif
desc->type = var.type;
desc->s = var.s;
desc->dpl = var.dpl;
desc->p = var.present;
desc->avl = var.avl;
desc->l = var.l;
desc->d = var.db;
desc->g = var.g;
return true;
}
static void emulator_set_segment(struct x86_emulate_ctxt *ctxt, u16 selector,
struct desc_struct *desc, u32 base3,
int seg)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
struct kvm_segment var;
var.selector = selector;
var.base = get_desc_base(desc);
#ifdef CONFIG_X86_64
var.base |= ((u64)base3) << 32;
#endif
var.limit = get_desc_limit(desc);
if (desc->g)
var.limit = (var.limit << 12) | 0xfff;
var.type = desc->type;
var.present = desc->p;
var.dpl = desc->dpl;
var.db = desc->d;
var.s = desc->s;
var.l = desc->l;
var.g = desc->g;
var.avl = desc->avl;
var.present = desc->p;
var.unusable = !var.present;
var.padding = 0;
kvm_set_segment(vcpu, &var, seg);
return;
}
static int emulator_get_msr(struct x86_emulate_ctxt *ctxt,
u32 msr_index, u64 *pdata)
{
return kvm_get_msr(emul_to_vcpu(ctxt), msr_index, pdata);
}
static int emulator_set_msr(struct x86_emulate_ctxt *ctxt,
u32 msr_index, u64 data)
{
struct msr_data msr;
msr.data = data;
msr.index = msr_index;
msr.host_initiated = false;
return kvm_set_msr(emul_to_vcpu(ctxt), &msr);
}
static int emulator_read_pmc(struct x86_emulate_ctxt *ctxt,
u32 pmc, u64 *pdata)
{
return kvm_pmu_read_pmc(emul_to_vcpu(ctxt), pmc, pdata);
}
static void emulator_halt(struct x86_emulate_ctxt *ctxt)
{
emul_to_vcpu(ctxt)->arch.halt_request = 1;
}
static void emulator_get_fpu(struct x86_emulate_ctxt *ctxt)
{
preempt_disable();
kvm_load_guest_fpu(emul_to_vcpu(ctxt));
/*
* CR0.TS may reference the host fpu state, not the guest fpu state,
* so it may be clear at this point.
*/
clts();
}
static void emulator_put_fpu(struct x86_emulate_ctxt *ctxt)
{
preempt_enable();
}
static int emulator_intercept(struct x86_emulate_ctxt *ctxt,
struct x86_instruction_info *info,
enum x86_intercept_stage stage)
{
return kvm_x86_ops->check_intercept(emul_to_vcpu(ctxt), info, stage);
}
static void emulator_get_cpuid(struct x86_emulate_ctxt *ctxt,
u32 *eax, u32 *ebx, u32 *ecx, u32 *edx)
{
kvm_cpuid(emul_to_vcpu(ctxt), eax, ebx, ecx, edx);
}
static ulong emulator_read_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg)
{
return kvm_register_read(emul_to_vcpu(ctxt), reg);
}
static void emulator_write_gpr(struct x86_emulate_ctxt *ctxt, unsigned reg, ulong val)
{
kvm_register_write(emul_to_vcpu(ctxt), reg, val);
}
static const struct x86_emulate_ops emulate_ops = {
.read_gpr = emulator_read_gpr,
.write_gpr = emulator_write_gpr,
.read_std = kvm_read_guest_virt_system,
.write_std = kvm_write_guest_virt_system,
.fetch = kvm_fetch_guest_virt,
.read_emulated = emulator_read_emulated,
.write_emulated = emulator_write_emulated,
.cmpxchg_emulated = emulator_cmpxchg_emulated,
.invlpg = emulator_invlpg,
.pio_in_emulated = emulator_pio_in_emulated,
.pio_out_emulated = emulator_pio_out_emulated,
.get_segment = emulator_get_segment,
.set_segment = emulator_set_segment,
.get_cached_segment_base = emulator_get_cached_segment_base,
.get_gdt = emulator_get_gdt,
.get_idt = emulator_get_idt,
.set_gdt = emulator_set_gdt,
.set_idt = emulator_set_idt,
.get_cr = emulator_get_cr,
.set_cr = emulator_set_cr,
.set_rflags = emulator_set_rflags,
.cpl = emulator_get_cpl,
.get_dr = emulator_get_dr,
.set_dr = emulator_set_dr,
.set_msr = emulator_set_msr,
.get_msr = emulator_get_msr,
.read_pmc = emulator_read_pmc,
.halt = emulator_halt,
.wbinvd = emulator_wbinvd,
.fix_hypercall = emulator_fix_hypercall,
.get_fpu = emulator_get_fpu,
.put_fpu = emulator_put_fpu,
.intercept = emulator_intercept,
.get_cpuid = emulator_get_cpuid,
};
static void toggle_interruptibility(struct kvm_vcpu *vcpu, u32 mask)
{
u32 int_shadow = kvm_x86_ops->get_interrupt_shadow(vcpu, mask);
/*
* an sti; sti; sequence only disable interrupts for the first
* instruction. So, if the last instruction, be it emulated or
* not, left the system with the INT_STI flag enabled, it
* means that the last instruction is an sti. We should not
* leave the flag on in this case. The same goes for mov ss
*/
if (!(int_shadow & mask))
kvm_x86_ops->set_interrupt_shadow(vcpu, mask);
}
static void inject_emulated_exception(struct kvm_vcpu *vcpu)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
if (ctxt->exception.vector == PF_VECTOR)
kvm_propagate_fault(vcpu, &ctxt->exception);
else if (ctxt->exception.error_code_valid)
kvm_queue_exception_e(vcpu, ctxt->exception.vector,
ctxt->exception.error_code);
else
kvm_queue_exception(vcpu, ctxt->exception.vector);
}
static void init_decode_cache(struct x86_emulate_ctxt *ctxt)
{
memset(&ctxt->opcode_len, 0,
(void *)&ctxt->_regs - (void *)&ctxt->opcode_len);
ctxt->fetch.start = 0;
ctxt->fetch.end = 0;
ctxt->io_read.pos = 0;
ctxt->io_read.end = 0;
ctxt->mem_read.pos = 0;
ctxt->mem_read.end = 0;
}
static void init_emulate_ctxt(struct kvm_vcpu *vcpu)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int cs_db, cs_l;
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
ctxt->eflags = kvm_get_rflags(vcpu);
ctxt->eip = kvm_rip_read(vcpu);
ctxt->mode = (!is_protmode(vcpu)) ? X86EMUL_MODE_REAL :
(ctxt->eflags & X86_EFLAGS_VM) ? X86EMUL_MODE_VM86 :
cs_l ? X86EMUL_MODE_PROT64 :
cs_db ? X86EMUL_MODE_PROT32 :
X86EMUL_MODE_PROT16;
ctxt->guest_mode = is_guest_mode(vcpu);
init_decode_cache(ctxt);
vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
}
int kvm_inject_realmode_interrupt(struct kvm_vcpu *vcpu, int irq, int inc_eip)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int ret;
init_emulate_ctxt(vcpu);
ctxt->op_bytes = 2;
ctxt->ad_bytes = 2;
ctxt->_eip = ctxt->eip + inc_eip;
ret = emulate_int_real(ctxt, irq);
if (ret != X86EMUL_CONTINUE)
return EMULATE_FAIL;
ctxt->eip = ctxt->_eip;
kvm_rip_write(vcpu, ctxt->eip);
kvm_set_rflags(vcpu, ctxt->eflags);
if (irq == NMI_VECTOR)
vcpu->arch.nmi_pending = 0;
else
vcpu->arch.interrupt.pending = false;
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvm_inject_realmode_interrupt);
static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
static bool reexecute_instruction(struct kvm_vcpu *vcpu, gva_t cr2,
bool write_fault_to_shadow_pgtable,
int emulation_type)
{
gpa_t gpa = cr2;
pfn_t pfn;
if (emulation_type & EMULTYPE_NO_REEXECUTE)
return false;
if (!vcpu->arch.mmu.direct_map) {
/*
* Write permission should be allowed since only
* write access need to be emulated.
*/
gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
/*
* If the mapping is invalid in guest, let cpu retry
* it to generate fault.
*/
if (gpa == UNMAPPED_GVA)
return true;
}
/*
* Do not retry the unhandleable instruction if it faults on the
* readonly host memory, otherwise it will goto a infinite loop:
* retry instruction -> write #PF -> emulation fail -> retry
* instruction -> ...
*/
pfn = gfn_to_pfn(vcpu->kvm, gpa_to_gfn(gpa));
/*
* If the instruction failed on the error pfn, it can not be fixed,
* report the error to userspace.
*/
if (is_error_noslot_pfn(pfn))
return false;
kvm_release_pfn_clean(pfn);
/* The instructions are well-emulated on direct mmu. */
if (vcpu->arch.mmu.direct_map) {
unsigned int indirect_shadow_pages;
spin_lock(&vcpu->kvm->mmu_lock);
indirect_shadow_pages = vcpu->kvm->arch.indirect_shadow_pages;
spin_unlock(&vcpu->kvm->mmu_lock);
if (indirect_shadow_pages)
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
return true;
}
/*
* if emulation was due to access to shadowed page table
* and it failed try to unshadow page and re-enter the
* guest to let CPU execute the instruction.
*/
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
/*
* If the access faults on its page table, it can not
* be fixed by unprotecting shadow page and it should
* be reported to userspace.
*/
return !write_fault_to_shadow_pgtable;
}
static bool retry_instruction(struct x86_emulate_ctxt *ctxt,
unsigned long cr2, int emulation_type)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
unsigned long last_retry_eip, last_retry_addr, gpa = cr2;
last_retry_eip = vcpu->arch.last_retry_eip;
last_retry_addr = vcpu->arch.last_retry_addr;
/*
* If the emulation is caused by #PF and it is non-page_table
* writing instruction, it means the VM-EXIT is caused by shadow
* page protected, we can zap the shadow page and retry this
* instruction directly.
*
* Note: if the guest uses a non-page-table modifying instruction
* on the PDE that points to the instruction, then we will unmap
* the instruction and go to an infinite loop. So, we cache the
* last retried eip and the last fault address, if we meet the eip
* and the address again, we can break out of the potential infinite
* loop.
*/
vcpu->arch.last_retry_eip = vcpu->arch.last_retry_addr = 0;
if (!(emulation_type & EMULTYPE_RETRY))
return false;
if (x86_page_table_writing_insn(ctxt))
return false;
if (ctxt->eip == last_retry_eip && last_retry_addr == cr2)
return false;
vcpu->arch.last_retry_eip = ctxt->eip;
vcpu->arch.last_retry_addr = cr2;
if (!vcpu->arch.mmu.direct_map)
gpa = kvm_mmu_gva_to_gpa_write(vcpu, cr2, NULL);
kvm_mmu_unprotect_page(vcpu->kvm, gpa_to_gfn(gpa));
return true;
}
static int complete_emulated_mmio(struct kvm_vcpu *vcpu);
static int complete_emulated_pio(struct kvm_vcpu *vcpu);
static int kvm_vcpu_check_hw_bp(unsigned long addr, u32 type, u32 dr7,
unsigned long *db)
{
u32 dr6 = 0;
int i;
u32 enable, rwlen;
enable = dr7;
rwlen = dr7 >> 16;
for (i = 0; i < 4; i++, enable >>= 2, rwlen >>= 4)
if ((enable & 3) && (rwlen & 15) == type && db[i] == addr)
dr6 |= (1 << i);
return dr6;
}
static void kvm_vcpu_check_singlestep(struct kvm_vcpu *vcpu, int *r)
{
struct kvm_run *kvm_run = vcpu->run;
/*
* Use the "raw" value to see if TF was passed to the processor.
* Note that the new value of the flags has not been saved yet.
*
* This is correct even for TF set by the guest, because "the
* processor will not generate this exception after the instruction
* that sets the TF flag".
*/
unsigned long rflags = kvm_x86_ops->get_rflags(vcpu);
if (unlikely(rflags & X86_EFLAGS_TF)) {
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) {
kvm_run->debug.arch.dr6 = DR6_BS | DR6_FIXED_1;
kvm_run->debug.arch.pc = vcpu->arch.singlestep_rip;
kvm_run->debug.arch.exception = DB_VECTOR;
kvm_run->exit_reason = KVM_EXIT_DEBUG;
*r = EMULATE_USER_EXIT;
} else {
vcpu->arch.emulate_ctxt.eflags &= ~X86_EFLAGS_TF;
/*
* "Certain debug exceptions may clear bit 0-3. The
* remaining contents of the DR6 register are never
* cleared by the processor".
*/
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= DR6_BS;
kvm_queue_exception(vcpu, DB_VECTOR);
}
}
}
static bool kvm_vcpu_check_breakpoint(struct kvm_vcpu *vcpu, int *r)
{
struct kvm_run *kvm_run = vcpu->run;
unsigned long eip = vcpu->arch.emulate_ctxt.eip;
u32 dr6 = 0;
if (unlikely(vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) &&
(vcpu->arch.guest_debug_dr7 & DR7_BP_EN_MASK)) {
dr6 = kvm_vcpu_check_hw_bp(eip, 0,
vcpu->arch.guest_debug_dr7,
vcpu->arch.eff_db);
if (dr6 != 0) {
kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1;
kvm_run->debug.arch.pc = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
kvm_run->debug.arch.exception = DB_VECTOR;
kvm_run->exit_reason = KVM_EXIT_DEBUG;
*r = EMULATE_USER_EXIT;
return true;
}
}
if (unlikely(vcpu->arch.dr7 & DR7_BP_EN_MASK)) {
dr6 = kvm_vcpu_check_hw_bp(eip, 0,
vcpu->arch.dr7,
vcpu->arch.db);
if (dr6 != 0) {
vcpu->arch.dr6 &= ~15;
vcpu->arch.dr6 |= dr6;
kvm_queue_exception(vcpu, DB_VECTOR);
*r = EMULATE_DONE;
return true;
}
}
return false;
}
int x86_emulate_instruction(struct kvm_vcpu *vcpu,
unsigned long cr2,
int emulation_type,
void *insn,
int insn_len)
{
int r;
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
bool writeback = true;
bool write_fault_to_spt = vcpu->arch.write_fault_to_shadow_pgtable;
/*
* Clear write_fault_to_shadow_pgtable here to ensure it is
* never reused.
*/
vcpu->arch.write_fault_to_shadow_pgtable = false;
kvm_clear_exception_queue(vcpu);
if (!(emulation_type & EMULTYPE_NO_DECODE)) {
init_emulate_ctxt(vcpu);
/*
* We will reenter on the same instruction since
* we do not set complete_userspace_io. This does not
* handle watchpoints yet, those would be handled in
* the emulate_ops.
*/
if (kvm_vcpu_check_breakpoint(vcpu, &r))
return r;
ctxt->interruptibility = 0;
ctxt->have_exception = false;
ctxt->perm_ok = false;
ctxt->ud = emulation_type & EMULTYPE_TRAP_UD;
r = x86_decode_insn(ctxt, insn, insn_len);
trace_kvm_emulate_insn_start(vcpu);
++vcpu->stat.insn_emulation;
if (r != EMULATION_OK) {
if (emulation_type & EMULTYPE_TRAP_UD)
return EMULATE_FAIL;
if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
emulation_type))
return EMULATE_DONE;
if (emulation_type & EMULTYPE_SKIP)
return EMULATE_FAIL;
return handle_emulation_failure(vcpu);
}
}
if (emulation_type & EMULTYPE_SKIP) {
kvm_rip_write(vcpu, ctxt->_eip);
return EMULATE_DONE;
}
if (retry_instruction(ctxt, cr2, emulation_type))
return EMULATE_DONE;
/* this is needed for vmware backdoor interface to work since it
changes registers values during IO operation */
if (vcpu->arch.emulate_regs_need_sync_from_vcpu) {
vcpu->arch.emulate_regs_need_sync_from_vcpu = false;
emulator_invalidate_register_cache(ctxt);
}
restart:
r = x86_emulate_insn(ctxt);
if (r == EMULATION_INTERCEPTED)
return EMULATE_DONE;
if (r == EMULATION_FAILED) {
if (reexecute_instruction(vcpu, cr2, write_fault_to_spt,
emulation_type))
return EMULATE_DONE;
return handle_emulation_failure(vcpu);
}
if (ctxt->have_exception) {
inject_emulated_exception(vcpu);
r = EMULATE_DONE;
} else if (vcpu->arch.pio.count) {
if (!vcpu->arch.pio.in) {
/* FIXME: return into emulator if single-stepping. */
vcpu->arch.pio.count = 0;
} else {
writeback = false;
vcpu->arch.complete_userspace_io = complete_emulated_pio;
}
r = EMULATE_USER_EXIT;
} else if (vcpu->mmio_needed) {
if (!vcpu->mmio_is_write)
writeback = false;
r = EMULATE_USER_EXIT;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
} else if (r == EMULATION_RESTART)
goto restart;
else
r = EMULATE_DONE;
if (writeback) {
toggle_interruptibility(vcpu, ctxt->interruptibility);
kvm_make_request(KVM_REQ_EVENT, vcpu);
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
kvm_rip_write(vcpu, ctxt->eip);
if (r == EMULATE_DONE)
kvm_vcpu_check_singlestep(vcpu, &r);
kvm_set_rflags(vcpu, ctxt->eflags);
} else
vcpu->arch.emulate_regs_need_sync_to_vcpu = true;
return r;
}
EXPORT_SYMBOL_GPL(x86_emulate_instruction);
int kvm_fast_pio_out(struct kvm_vcpu *vcpu, int size, unsigned short port)
{
unsigned long val = kvm_register_read(vcpu, VCPU_REGS_RAX);
int ret = emulator_pio_out_emulated(&vcpu->arch.emulate_ctxt,
size, port, &val, 1);
/* do not return to emulator after return from userspace */
vcpu->arch.pio.count = 0;
return ret;
}
EXPORT_SYMBOL_GPL(kvm_fast_pio_out);
static void tsc_bad(void *info)
{
__this_cpu_write(cpu_tsc_khz, 0);
}
static void tsc_khz_changed(void *data)
{
struct cpufreq_freqs *freq = data;
unsigned long khz = 0;
if (data)
khz = freq->new;
else if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
khz = cpufreq_quick_get(raw_smp_processor_id());
if (!khz)
khz = tsc_khz;
__this_cpu_write(cpu_tsc_khz, khz);
}
static int kvmclock_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
void *data)
{
struct cpufreq_freqs *freq = data;
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i, send_ipi = 0;
/*
* We allow guests to temporarily run on slowing clocks,
* provided we notify them after, or to run on accelerating
* clocks, provided we notify them before. Thus time never
* goes backwards.
*
* However, we have a problem. We can't atomically update
* the frequency of a given CPU from this function; it is
* merely a notifier, which can be called from any CPU.
* Changing the TSC frequency at arbitrary points in time
* requires a recomputation of local variables related to
* the TSC for each VCPU. We must flag these local variables
* to be updated and be sure the update takes place with the
* new frequency before any guests proceed.
*
* Unfortunately, the combination of hotplug CPU and frequency
* change creates an intractable locking scenario; the order
* of when these callouts happen is undefined with respect to
* CPU hotplug, and they can race with each other. As such,
* merely setting per_cpu(cpu_tsc_khz) = X during a hotadd is
* undefined; you can actually have a CPU frequency change take
* place in between the computation of X and the setting of the
* variable. To protect against this problem, all updates of
* the per_cpu tsc_khz variable are done in an interrupt
* protected IPI, and all callers wishing to update the value
* must wait for a synchronous IPI to complete (which is trivial
* if the caller is on the CPU already). This establishes the
* necessary total order on variable updates.
*
* Note that because a guest time update may take place
* anytime after the setting of the VCPU's request bit, the
* correct TSC value must be set before the request. However,
* to ensure the update actually makes it to any guest which
* starts running in hardware virtualization between the set
* and the acquisition of the spinlock, we must also ping the
* CPU after setting the request bit.
*
*/
if (val == CPUFREQ_PRECHANGE && freq->old > freq->new)
return 0;
if (val == CPUFREQ_POSTCHANGE && freq->old < freq->new)
return 0;
smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (vcpu->cpu != freq->cpu)
continue;
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
if (vcpu->cpu != smp_processor_id())
send_ipi = 1;
}
}
spin_unlock(&kvm_lock);
if (freq->old < freq->new && send_ipi) {
/*
* We upscale the frequency. Must make the guest
* doesn't see old kvmclock values while running with
* the new frequency, otherwise we risk the guest sees
* time go backwards.
*
* In case we update the frequency for another cpu
* (which might be in guest context) send an interrupt
* to kick the cpu out of guest context. Next time
* guest context is entered kvmclock will be updated,
* so the guest will not see stale values.
*/
smp_call_function_single(freq->cpu, tsc_khz_changed, freq, 1);
}
return 0;
}
static struct notifier_block kvmclock_cpufreq_notifier_block = {
.notifier_call = kvmclock_cpufreq_notifier
};
static int kvmclock_cpu_notifier(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
switch (action) {
case CPU_ONLINE:
case CPU_DOWN_FAILED:
smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
break;
case CPU_DOWN_PREPARE:
smp_call_function_single(cpu, tsc_bad, NULL, 1);
break;
}
return NOTIFY_OK;
}
static struct notifier_block kvmclock_cpu_notifier_block = {
.notifier_call = kvmclock_cpu_notifier,
.priority = -INT_MAX
};
static void kvm_timer_init(void)
{
int cpu;
max_tsc_khz = tsc_khz;
register_hotcpu_notifier(&kvmclock_cpu_notifier_block);
if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC)) {
#ifdef CONFIG_CPU_FREQ
struct cpufreq_policy policy;
memset(&policy, 0, sizeof(policy));
cpu = get_cpu();
cpufreq_get_policy(&policy, cpu);
if (policy.cpuinfo.max_freq)
max_tsc_khz = policy.cpuinfo.max_freq;
put_cpu();
#endif
cpufreq_register_notifier(&kvmclock_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
}
pr_debug("kvm: max_tsc_khz = %ld\n", max_tsc_khz);
for_each_online_cpu(cpu)
smp_call_function_single(cpu, tsc_khz_changed, NULL, 1);
}
static DEFINE_PER_CPU(struct kvm_vcpu *, current_vcpu);
int kvm_is_in_guest(void)
{
return __this_cpu_read(current_vcpu) != NULL;
}
static int kvm_is_user_mode(void)
{
int user_mode = 3;
if (__this_cpu_read(current_vcpu))
user_mode = kvm_x86_ops->get_cpl(__this_cpu_read(current_vcpu));
return user_mode != 0;
}
static unsigned long kvm_get_guest_ip(void)
{
unsigned long ip = 0;
if (__this_cpu_read(current_vcpu))
ip = kvm_rip_read(__this_cpu_read(current_vcpu));
return ip;
}
static struct perf_guest_info_callbacks kvm_guest_cbs = {
.is_in_guest = kvm_is_in_guest,
.is_user_mode = kvm_is_user_mode,
.get_guest_ip = kvm_get_guest_ip,
};
void kvm_before_handle_nmi(struct kvm_vcpu *vcpu)
{
__this_cpu_write(current_vcpu, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_before_handle_nmi);
void kvm_after_handle_nmi(struct kvm_vcpu *vcpu)
{
__this_cpu_write(current_vcpu, NULL);
}
EXPORT_SYMBOL_GPL(kvm_after_handle_nmi);
static void kvm_set_mmio_spte_mask(void)
{
u64 mask;
int maxphyaddr = boot_cpu_data.x86_phys_bits;
/*
* Set the reserved bits and the present bit of an paging-structure
* entry to generate page fault with PFER.RSV = 1.
*/
/* Mask the reserved physical address bits. */
mask = ((1ull << (51 - maxphyaddr + 1)) - 1) << maxphyaddr;
/* Bit 62 is always reserved for 32bit host. */
mask |= 0x3ull << 62;
/* Set the present bit. */
mask |= 1ull;
#ifdef CONFIG_X86_64
/*
* If reserved bit is not supported, clear the present bit to disable
* mmio page fault.
*/
if (maxphyaddr == 52)
mask &= ~1ull;
#endif
kvm_mmu_set_mmio_spte_mask(mask);
}
#ifdef CONFIG_X86_64
static void pvclock_gtod_update_fn(struct work_struct *work)
{
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
spin_lock(&kvm_lock);
list_for_each_entry(kvm, &vm_list, vm_list)
kvm_for_each_vcpu(i, vcpu, kvm)
set_bit(KVM_REQ_MASTERCLOCK_UPDATE, &vcpu->requests);
atomic_set(&kvm_guest_has_master_clock, 0);
spin_unlock(&kvm_lock);
}
static DECLARE_WORK(pvclock_gtod_work, pvclock_gtod_update_fn);
/*
* Notification about pvclock gtod data update.
*/
static int pvclock_gtod_notify(struct notifier_block *nb, unsigned long unused,
void *priv)
{
struct pvclock_gtod_data *gtod = &pvclock_gtod_data;
struct timekeeper *tk = priv;
update_pvclock_gtod(tk);
/* disable master clock if host does not trust, or does not
* use, TSC clocksource
*/
if (gtod->clock.vclock_mode != VCLOCK_TSC &&
atomic_read(&kvm_guest_has_master_clock) != 0)
queue_work(system_long_wq, &pvclock_gtod_work);
return 0;
}
static struct notifier_block pvclock_gtod_notifier = {
.notifier_call = pvclock_gtod_notify,
};
#endif
int kvm_arch_init(void *opaque)
{
int r;
struct kvm_x86_ops *ops = opaque;
if (kvm_x86_ops) {
printk(KERN_ERR "kvm: already loaded the other module\n");
r = -EEXIST;
goto out;
}
if (!ops->cpu_has_kvm_support()) {
printk(KERN_ERR "kvm: no hardware support\n");
r = -EOPNOTSUPP;
goto out;
}
if (ops->disabled_by_bios()) {
printk(KERN_ERR "kvm: disabled by bios\n");
r = -EOPNOTSUPP;
goto out;
}
r = -ENOMEM;
shared_msrs = alloc_percpu(struct kvm_shared_msrs);
if (!shared_msrs) {
printk(KERN_ERR "kvm: failed to allocate percpu kvm_shared_msrs\n");
goto out;
}
r = kvm_mmu_module_init();
if (r)
goto out_free_percpu;
kvm_set_mmio_spte_mask();
kvm_init_msr_list();
kvm_x86_ops = ops;
kvm_mmu_set_mask_ptes(PT_USER_MASK, PT_ACCESSED_MASK,
PT_DIRTY_MASK, PT64_NX_MASK, 0);
kvm_timer_init();
perf_register_guest_info_callbacks(&kvm_guest_cbs);
if (cpu_has_xsave)
host_xcr0 = xgetbv(XCR_XFEATURE_ENABLED_MASK);
kvm_lapic_init();
#ifdef CONFIG_X86_64
pvclock_gtod_register_notifier(&pvclock_gtod_notifier);
#endif
return 0;
out_free_percpu:
free_percpu(shared_msrs);
out:
return r;
}
void kvm_arch_exit(void)
{
perf_unregister_guest_info_callbacks(&kvm_guest_cbs);
if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
cpufreq_unregister_notifier(&kvmclock_cpufreq_notifier_block,
CPUFREQ_TRANSITION_NOTIFIER);
unregister_hotcpu_notifier(&kvmclock_cpu_notifier_block);
#ifdef CONFIG_X86_64
pvclock_gtod_unregister_notifier(&pvclock_gtod_notifier);
#endif
kvm_x86_ops = NULL;
kvm_mmu_module_exit();
free_percpu(shared_msrs);
}
int kvm_emulate_halt(struct kvm_vcpu *vcpu)
{
++vcpu->stat.halt_exits;
if (irqchip_in_kernel(vcpu->kvm)) {
vcpu->arch.mp_state = KVM_MP_STATE_HALTED;
return 1;
} else {
vcpu->run->exit_reason = KVM_EXIT_HLT;
return 0;
}
}
EXPORT_SYMBOL_GPL(kvm_emulate_halt);
int kvm_hv_hypercall(struct kvm_vcpu *vcpu)
{
u64 param, ingpa, outgpa, ret;
uint16_t code, rep_idx, rep_cnt, res = HV_STATUS_SUCCESS, rep_done = 0;
bool fast, longmode;
int cs_db, cs_l;
/*
* hypercall generates UD from non zero cpl and real mode
* per HYPER-V spec
*/
if (kvm_x86_ops->get_cpl(vcpu) != 0 || !is_protmode(vcpu)) {
kvm_queue_exception(vcpu, UD_VECTOR);
return 0;
}
kvm_x86_ops->get_cs_db_l_bits(vcpu, &cs_db, &cs_l);
longmode = is_long_mode(vcpu) && cs_l == 1;
if (!longmode) {
param = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDX) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RAX) & 0xffffffff);
ingpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RBX) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RCX) & 0xffffffff);
outgpa = ((u64)kvm_register_read(vcpu, VCPU_REGS_RDI) << 32) |
(kvm_register_read(vcpu, VCPU_REGS_RSI) & 0xffffffff);
}
#ifdef CONFIG_X86_64
else {
param = kvm_register_read(vcpu, VCPU_REGS_RCX);
ingpa = kvm_register_read(vcpu, VCPU_REGS_RDX);
outgpa = kvm_register_read(vcpu, VCPU_REGS_R8);
}
#endif
code = param & 0xffff;
fast = (param >> 16) & 0x1;
rep_cnt = (param >> 32) & 0xfff;
rep_idx = (param >> 48) & 0xfff;
trace_kvm_hv_hypercall(code, fast, rep_cnt, rep_idx, ingpa, outgpa);
switch (code) {
case HV_X64_HV_NOTIFY_LONG_SPIN_WAIT:
kvm_vcpu_on_spin(vcpu);
break;
default:
res = HV_STATUS_INVALID_HYPERCALL_CODE;
break;
}
ret = res | (((u64)rep_done & 0xfff) << 32);
if (longmode) {
kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
} else {
kvm_register_write(vcpu, VCPU_REGS_RDX, ret >> 32);
kvm_register_write(vcpu, VCPU_REGS_RAX, ret & 0xffffffff);
}
return 1;
}
/*
* kvm_pv_kick_cpu_op: Kick a vcpu.
*
* @apicid - apicid of vcpu to be kicked.
*/
static void kvm_pv_kick_cpu_op(struct kvm *kvm, unsigned long flags, int apicid)
{
struct kvm_lapic_irq lapic_irq;
lapic_irq.shorthand = 0;
lapic_irq.dest_mode = 0;
lapic_irq.dest_id = apicid;
lapic_irq.delivery_mode = APIC_DM_REMRD;
kvm_irq_delivery_to_apic(kvm, 0, &lapic_irq, NULL);
}
int kvm_emulate_hypercall(struct kvm_vcpu *vcpu)
{
unsigned long nr, a0, a1, a2, a3, ret;
int r = 1;
if (kvm_hv_hypercall_enabled(vcpu->kvm))
return kvm_hv_hypercall(vcpu);
nr = kvm_register_read(vcpu, VCPU_REGS_RAX);
a0 = kvm_register_read(vcpu, VCPU_REGS_RBX);
a1 = kvm_register_read(vcpu, VCPU_REGS_RCX);
a2 = kvm_register_read(vcpu, VCPU_REGS_RDX);
a3 = kvm_register_read(vcpu, VCPU_REGS_RSI);
trace_kvm_hypercall(nr, a0, a1, a2, a3);
if (!is_long_mode(vcpu)) {
nr &= 0xFFFFFFFF;
a0 &= 0xFFFFFFFF;
a1 &= 0xFFFFFFFF;
a2 &= 0xFFFFFFFF;
a3 &= 0xFFFFFFFF;
}
if (kvm_x86_ops->get_cpl(vcpu) != 0) {
ret = -KVM_EPERM;
goto out;
}
switch (nr) {
case KVM_HC_VAPIC_POLL_IRQ:
ret = 0;
break;
case KVM_HC_KICK_CPU:
kvm_pv_kick_cpu_op(vcpu->kvm, a0, a1);
ret = 0;
break;
default:
ret = -KVM_ENOSYS;
break;
}
out:
kvm_register_write(vcpu, VCPU_REGS_RAX, ret);
++vcpu->stat.hypercalls;
return r;
}
EXPORT_SYMBOL_GPL(kvm_emulate_hypercall);
static int emulator_fix_hypercall(struct x86_emulate_ctxt *ctxt)
{
struct kvm_vcpu *vcpu = emul_to_vcpu(ctxt);
char instruction[3];
unsigned long rip = kvm_rip_read(vcpu);
kvm_x86_ops->patch_hypercall(vcpu, instruction);
return emulator_write_emulated(ctxt, rip, instruction, 3, NULL);
}
/*
* Check if userspace requested an interrupt window, and that the
* interrupt window is open.
*
* No need to exit to userspace if we already have an interrupt queued.
*/
static int dm_request_for_irq_injection(struct kvm_vcpu *vcpu)
{
return (!irqchip_in_kernel(vcpu->kvm) && !kvm_cpu_has_interrupt(vcpu) &&
vcpu->run->request_interrupt_window &&
kvm_arch_interrupt_allowed(vcpu));
}
static void post_kvm_run_save(struct kvm_vcpu *vcpu)
{
struct kvm_run *kvm_run = vcpu->run;
kvm_run->if_flag = (kvm_get_rflags(vcpu) & X86_EFLAGS_IF) != 0;
kvm_run->cr8 = kvm_get_cr8(vcpu);
kvm_run->apic_base = kvm_get_apic_base(vcpu);
if (irqchip_in_kernel(vcpu->kvm))
kvm_run->ready_for_interrupt_injection = 1;
else
kvm_run->ready_for_interrupt_injection =
kvm_arch_interrupt_allowed(vcpu) &&
!kvm_cpu_has_interrupt(vcpu) &&
!kvm_event_needs_reinjection(vcpu);
}
static void update_cr8_intercept(struct kvm_vcpu *vcpu)
{
int max_irr, tpr;
if (!kvm_x86_ops->update_cr8_intercept)
return;
if (!vcpu->arch.apic)
return;
if (!vcpu->arch.apic->vapic_addr)
max_irr = kvm_lapic_find_highest_irr(vcpu);
else
max_irr = -1;
if (max_irr != -1)
max_irr >>= 4;
tpr = kvm_lapic_get_cr8(vcpu);
kvm_x86_ops->update_cr8_intercept(vcpu, tpr, max_irr);
}
static void inject_pending_event(struct kvm_vcpu *vcpu)
{
/* try to reinject previous events if any */
if (vcpu->arch.exception.pending) {
trace_kvm_inj_exception(vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code);
kvm_x86_ops->queue_exception(vcpu, vcpu->arch.exception.nr,
vcpu->arch.exception.has_error_code,
vcpu->arch.exception.error_code,
vcpu->arch.exception.reinject);
return;
}
if (vcpu->arch.nmi_injected) {
kvm_x86_ops->set_nmi(vcpu);
return;
}
if (vcpu->arch.interrupt.pending) {
kvm_x86_ops->set_irq(vcpu);
return;
}
/* try to inject new event if pending */
if (vcpu->arch.nmi_pending) {
if (kvm_x86_ops->nmi_allowed(vcpu)) {
--vcpu->arch.nmi_pending;
vcpu->arch.nmi_injected = true;
kvm_x86_ops->set_nmi(vcpu);
}
} else if (kvm_cpu_has_injectable_intr(vcpu)) {
if (kvm_x86_ops->interrupt_allowed(vcpu)) {
kvm_queue_interrupt(vcpu, kvm_cpu_get_interrupt(vcpu),
false);
kvm_x86_ops->set_irq(vcpu);
}
}
}
static void process_nmi(struct kvm_vcpu *vcpu)
{
unsigned limit = 2;
/*
* x86 is limited to one NMI running, and one NMI pending after it.
* If an NMI is already in progress, limit further NMIs to just one.
* Otherwise, allow two (and we'll inject the first one immediately).
*/
if (kvm_x86_ops->get_nmi_mask(vcpu) || vcpu->arch.nmi_injected)
limit = 1;
vcpu->arch.nmi_pending += atomic_xchg(&vcpu->arch.nmi_queued, 0);
vcpu->arch.nmi_pending = min(vcpu->arch.nmi_pending, limit);
kvm_make_request(KVM_REQ_EVENT, vcpu);
}
static void vcpu_scan_ioapic(struct kvm_vcpu *vcpu)
{
u64 eoi_exit_bitmap[4];
u32 tmr[8];
if (!kvm_apic_hw_enabled(vcpu->arch.apic))
return;
memset(eoi_exit_bitmap, 0, 32);
memset(tmr, 0, 32);
kvm_ioapic_scan_entry(vcpu, eoi_exit_bitmap, tmr);
kvm_x86_ops->load_eoi_exitmap(vcpu, eoi_exit_bitmap);
kvm_apic_update_tmr(vcpu, tmr);
}
static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
{
int r;
bool req_int_win = !irqchip_in_kernel(vcpu->kvm) &&
vcpu->run->request_interrupt_window;
bool req_immediate_exit = false;
if (vcpu->requests) {
if (kvm_check_request(KVM_REQ_MMU_RELOAD, vcpu))
kvm_mmu_unload(vcpu);
if (kvm_check_request(KVM_REQ_MIGRATE_TIMER, vcpu))
__kvm_migrate_timers(vcpu);
if (kvm_check_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu))
kvm_gen_update_masterclock(vcpu->kvm);
if (kvm_check_request(KVM_REQ_GLOBAL_CLOCK_UPDATE, vcpu))
kvm_gen_kvmclock_update(vcpu);
if (kvm_check_request(KVM_REQ_CLOCK_UPDATE, vcpu)) {
r = kvm_guest_time_update(vcpu);
if (unlikely(r))
goto out;
}
if (kvm_check_request(KVM_REQ_MMU_SYNC, vcpu))
kvm_mmu_sync_roots(vcpu);
if (kvm_check_request(KVM_REQ_TLB_FLUSH, vcpu))
kvm_x86_ops->tlb_flush(vcpu);
if (kvm_check_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_TPR_ACCESS;
r = 0;
goto out;
}
if (kvm_check_request(KVM_REQ_TRIPLE_FAULT, vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_SHUTDOWN;
r = 0;
goto out;
}
if (kvm_check_request(KVM_REQ_DEACTIVATE_FPU, vcpu)) {
vcpu->fpu_active = 0;
kvm_x86_ops->fpu_deactivate(vcpu);
}
if (kvm_check_request(KVM_REQ_APF_HALT, vcpu)) {
/* Page is swapped out. Do synthetic halt */
vcpu->arch.apf.halted = true;
r = 1;
goto out;
}
if (kvm_check_request(KVM_REQ_STEAL_UPDATE, vcpu))
record_steal_time(vcpu);
if (kvm_check_request(KVM_REQ_NMI, vcpu))
process_nmi(vcpu);
if (kvm_check_request(KVM_REQ_PMU, vcpu))
kvm_handle_pmu_event(vcpu);
if (kvm_check_request(KVM_REQ_PMI, vcpu))
kvm_deliver_pmi(vcpu);
if (kvm_check_request(KVM_REQ_SCAN_IOAPIC, vcpu))
vcpu_scan_ioapic(vcpu);
}
if (kvm_check_request(KVM_REQ_EVENT, vcpu) || req_int_win) {
kvm_apic_accept_events(vcpu);
if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
r = 1;
goto out;
}
inject_pending_event(vcpu);
/* enable NMI/IRQ window open exits if needed */
if (vcpu->arch.nmi_pending)
req_immediate_exit =
kvm_x86_ops->enable_nmi_window(vcpu) != 0;
else if (kvm_cpu_has_injectable_intr(vcpu) || req_int_win)
req_immediate_exit =
kvm_x86_ops->enable_irq_window(vcpu) != 0;
if (kvm_lapic_enabled(vcpu)) {
/*
* Update architecture specific hints for APIC
* virtual interrupt delivery.
*/
if (kvm_x86_ops->hwapic_irr_update)
kvm_x86_ops->hwapic_irr_update(vcpu,
kvm_lapic_find_highest_irr(vcpu));
update_cr8_intercept(vcpu);
kvm_lapic_sync_to_vapic(vcpu);
}
}
r = kvm_mmu_reload(vcpu);
if (unlikely(r)) {
goto cancel_injection;
}
preempt_disable();
kvm_x86_ops->prepare_guest_switch(vcpu);
if (vcpu->fpu_active)
kvm_load_guest_fpu(vcpu);
kvm_load_guest_xcr0(vcpu);
vcpu->mode = IN_GUEST_MODE;
srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
/* We should set ->mode before check ->requests,
* see the comment in make_all_cpus_request.
*/
smp_mb__after_srcu_read_unlock();
local_irq_disable();
if (vcpu->mode == EXITING_GUEST_MODE || vcpu->requests
|| need_resched() || signal_pending(current)) {
vcpu->mode = OUTSIDE_GUEST_MODE;
smp_wmb();
local_irq_enable();
preempt_enable();
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
r = 1;
goto cancel_injection;
}
if (req_immediate_exit)
smp_send_reschedule(vcpu->cpu);
kvm_guest_enter();
if (unlikely(vcpu->arch.switch_db_regs)) {
set_debugreg(0, 7);
set_debugreg(vcpu->arch.eff_db[0], 0);
set_debugreg(vcpu->arch.eff_db[1], 1);
set_debugreg(vcpu->arch.eff_db[2], 2);
set_debugreg(vcpu->arch.eff_db[3], 3);
}
trace_kvm_entry(vcpu->vcpu_id);
kvm_x86_ops->run(vcpu);
/*
* If the guest has used debug registers, at least dr7
* will be disabled while returning to the host.
* If we don't have active breakpoints in the host, we don't
* care about the messed up debug address registers. But if
* we have some of them active, restore the old state.
*/
if (hw_breakpoint_active())
hw_breakpoint_restore();
vcpu->arch.last_guest_tsc = kvm_x86_ops->read_l1_tsc(vcpu,
native_read_tsc());
vcpu->mode = OUTSIDE_GUEST_MODE;
smp_wmb();
/* Interrupt is enabled by handle_external_intr() */
kvm_x86_ops->handle_external_intr(vcpu);
++vcpu->stat.exits;
/*
* We must have an instruction between local_irq_enable() and
* kvm_guest_exit(), so the timer interrupt isn't delayed by
* the interrupt shadow. The stat.exits increment will do nicely.
* But we need to prevent reordering, hence this barrier():
*/
barrier();
kvm_guest_exit();
preempt_enable();
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
/*
* Profile KVM exit RIPs:
*/
if (unlikely(prof_on == KVM_PROFILING)) {
unsigned long rip = kvm_rip_read(vcpu);
profile_hit(KVM_PROFILING, (void *)rip);
}
if (unlikely(vcpu->arch.tsc_always_catchup))
kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu);
if (vcpu->arch.apic_attention)
kvm_lapic_sync_from_vapic(vcpu);
r = kvm_x86_ops->handle_exit(vcpu);
return r;
cancel_injection:
kvm_x86_ops->cancel_injection(vcpu);
if (unlikely(vcpu->arch.apic_attention))
kvm_lapic_sync_from_vapic(vcpu);
out:
return r;
}
static int __vcpu_run(struct kvm_vcpu *vcpu)
{
int r;
struct kvm *kvm = vcpu->kvm;
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
r = 1;
while (r > 0) {
if (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
!vcpu->arch.apf.halted)
r = vcpu_enter_guest(vcpu);
else {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
kvm_vcpu_block(vcpu);
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
if (kvm_check_request(KVM_REQ_UNHALT, vcpu)) {
kvm_apic_accept_events(vcpu);
switch(vcpu->arch.mp_state) {
case KVM_MP_STATE_HALTED:
vcpu->arch.pv.pv_unhalted = false;
vcpu->arch.mp_state =
KVM_MP_STATE_RUNNABLE;
case KVM_MP_STATE_RUNNABLE:
vcpu->arch.apf.halted = false;
break;
case KVM_MP_STATE_INIT_RECEIVED:
break;
default:
r = -EINTR;
break;
}
}
}
if (r <= 0)
break;
clear_bit(KVM_REQ_PENDING_TIMER, &vcpu->requests);
if (kvm_cpu_has_pending_timer(vcpu))
kvm_inject_pending_timer_irqs(vcpu);
if (dm_request_for_irq_injection(vcpu)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.request_irq_exits;
}
kvm_check_async_pf_completion(vcpu);
if (signal_pending(current)) {
r = -EINTR;
vcpu->run->exit_reason = KVM_EXIT_INTR;
++vcpu->stat.signal_exits;
}
if (need_resched()) {
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
kvm_resched(vcpu);
vcpu->srcu_idx = srcu_read_lock(&kvm->srcu);
}
}
srcu_read_unlock(&kvm->srcu, vcpu->srcu_idx);
return r;
}
static inline int complete_emulated_io(struct kvm_vcpu *vcpu)
{
int r;
vcpu->srcu_idx = srcu_read_lock(&vcpu->kvm->srcu);
r = emulate_instruction(vcpu, EMULTYPE_NO_DECODE);
srcu_read_unlock(&vcpu->kvm->srcu, vcpu->srcu_idx);
if (r != EMULATE_DONE)
return 0;
return 1;
}
static int complete_emulated_pio(struct kvm_vcpu *vcpu)
{
BUG_ON(!vcpu->arch.pio.count);
return complete_emulated_io(vcpu);
}
/*
* Implements the following, as a state machine:
*
* read:
* for each fragment
* for each mmio piece in the fragment
* write gpa, len
* exit
* copy data
* execute insn
*
* write:
* for each fragment
* for each mmio piece in the fragment
* write gpa, len
* copy data
* exit
*/
static int complete_emulated_mmio(struct kvm_vcpu *vcpu)
{
struct kvm_run *run = vcpu->run;
struct kvm_mmio_fragment *frag;
unsigned len;
BUG_ON(!vcpu->mmio_needed);
/* Complete previous fragment */
frag = &vcpu->mmio_fragments[vcpu->mmio_cur_fragment];
len = min(8u, frag->len);
if (!vcpu->mmio_is_write)
memcpy(frag->data, run->mmio.data, len);
if (frag->len <= 8) {
/* Switch to the next fragment. */
frag++;
vcpu->mmio_cur_fragment++;
} else {
/* Go forward to the next mmio piece. */
frag->data += len;
frag->gpa += len;
frag->len -= len;
}
if (vcpu->mmio_cur_fragment == vcpu->mmio_nr_fragments) {
vcpu->mmio_needed = 0;
/* FIXME: return into emulator if single-stepping. */
if (vcpu->mmio_is_write)
return 1;
vcpu->mmio_read_completed = 1;
return complete_emulated_io(vcpu);
}
run->exit_reason = KVM_EXIT_MMIO;
run->mmio.phys_addr = frag->gpa;
if (vcpu->mmio_is_write)
memcpy(run->mmio.data, frag->data, min(8u, frag->len));
run->mmio.len = min(8u, frag->len);
run->mmio.is_write = vcpu->mmio_is_write;
vcpu->arch.complete_userspace_io = complete_emulated_mmio;
return 0;
}
int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
{
int r;
sigset_t sigsaved;
if (!tsk_used_math(current) && init_fpu(current))
return -ENOMEM;
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved);
if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) {
kvm_vcpu_block(vcpu);
kvm_apic_accept_events(vcpu);
clear_bit(KVM_REQ_UNHALT, &vcpu->requests);
r = -EAGAIN;
goto out;
}
/* re-sync apic's tpr */
if (!irqchip_in_kernel(vcpu->kvm)) {
if (kvm_set_cr8(vcpu, kvm_run->cr8) != 0) {
r = -EINVAL;
goto out;
}
}
if (unlikely(vcpu->arch.complete_userspace_io)) {
int (*cui)(struct kvm_vcpu *) = vcpu->arch.complete_userspace_io;
vcpu->arch.complete_userspace_io = NULL;
r = cui(vcpu);
if (r <= 0)
goto out;
} else
WARN_ON(vcpu->arch.pio.count || vcpu->mmio_needed);
r = __vcpu_run(vcpu);
out:
post_kvm_run_save(vcpu);
if (vcpu->sigset_active)
sigprocmask(SIG_SETMASK, &sigsaved, NULL);
return r;
}
int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
if (vcpu->arch.emulate_regs_need_sync_to_vcpu) {
/*
* We are here if userspace calls get_regs() in the middle of
* instruction emulation. Registers state needs to be copied
* back from emulation context to vcpu. Userspace shouldn't do
* that usually, but some bad designed PV devices (vmware
* backdoor interface) need this to work
*/
emulator_writeback_register_cache(&vcpu->arch.emulate_ctxt);
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
}
regs->rax = kvm_register_read(vcpu, VCPU_REGS_RAX);
regs->rbx = kvm_register_read(vcpu, VCPU_REGS_RBX);
regs->rcx = kvm_register_read(vcpu, VCPU_REGS_RCX);
regs->rdx = kvm_register_read(vcpu, VCPU_REGS_RDX);
regs->rsi = kvm_register_read(vcpu, VCPU_REGS_RSI);
regs->rdi = kvm_register_read(vcpu, VCPU_REGS_RDI);
regs->rsp = kvm_register_read(vcpu, VCPU_REGS_RSP);
regs->rbp = kvm_register_read(vcpu, VCPU_REGS_RBP);
#ifdef CONFIG_X86_64
regs->r8 = kvm_register_read(vcpu, VCPU_REGS_R8);
regs->r9 = kvm_register_read(vcpu, VCPU_REGS_R9);
regs->r10 = kvm_register_read(vcpu, VCPU_REGS_R10);
regs->r11 = kvm_register_read(vcpu, VCPU_REGS_R11);
regs->r12 = kvm_register_read(vcpu, VCPU_REGS_R12);
regs->r13 = kvm_register_read(vcpu, VCPU_REGS_R13);
regs->r14 = kvm_register_read(vcpu, VCPU_REGS_R14);
regs->r15 = kvm_register_read(vcpu, VCPU_REGS_R15);
#endif
regs->rip = kvm_rip_read(vcpu);
regs->rflags = kvm_get_rflags(vcpu);
return 0;
}
int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
{
vcpu->arch.emulate_regs_need_sync_from_vcpu = true;
vcpu->arch.emulate_regs_need_sync_to_vcpu = false;
kvm_register_write(vcpu, VCPU_REGS_RAX, regs->rax);
kvm_register_write(vcpu, VCPU_REGS_RBX, regs->rbx);
kvm_register_write(vcpu, VCPU_REGS_RCX, regs->rcx);
kvm_register_write(vcpu, VCPU_REGS_RDX, regs->rdx);
kvm_register_write(vcpu, VCPU_REGS_RSI, regs->rsi);
kvm_register_write(vcpu, VCPU_REGS_RDI, regs->rdi);
kvm_register_write(vcpu, VCPU_REGS_RSP, regs->rsp);
kvm_register_write(vcpu, VCPU_REGS_RBP, regs->rbp);
#ifdef CONFIG_X86_64
kvm_register_write(vcpu, VCPU_REGS_R8, regs->r8);
kvm_register_write(vcpu, VCPU_REGS_R9, regs->r9);
kvm_register_write(vcpu, VCPU_REGS_R10, regs->r10);
kvm_register_write(vcpu, VCPU_REGS_R11, regs->r11);
kvm_register_write(vcpu, VCPU_REGS_R12, regs->r12);
kvm_register_write(vcpu, VCPU_REGS_R13, regs->r13);
kvm_register_write(vcpu, VCPU_REGS_R14, regs->r14);
kvm_register_write(vcpu, VCPU_REGS_R15, regs->r15);
#endif
kvm_rip_write(vcpu, regs->rip);
kvm_set_rflags(vcpu, regs->rflags);
vcpu->arch.exception.pending = false;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
void kvm_get_cs_db_l_bits(struct kvm_vcpu *vcpu, int *db, int *l)
{
struct kvm_segment cs;
kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
*db = cs.db;
*l = cs.l;
}
EXPORT_SYMBOL_GPL(kvm_get_cs_db_l_bits);
int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
struct desc_ptr dt;
kvm_get_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
kvm_get_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
kvm_get_segment(vcpu, &sregs->es, VCPU_SREG_ES);
kvm_get_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
kvm_get_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
kvm_get_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
kvm_get_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
kvm_get_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
kvm_x86_ops->get_idt(vcpu, &dt);
sregs->idt.limit = dt.size;
sregs->idt.base = dt.address;
kvm_x86_ops->get_gdt(vcpu, &dt);
sregs->gdt.limit = dt.size;
sregs->gdt.base = dt.address;
sregs->cr0 = kvm_read_cr0(vcpu);
sregs->cr2 = vcpu->arch.cr2;
sregs->cr3 = kvm_read_cr3(vcpu);
sregs->cr4 = kvm_read_cr4(vcpu);
sregs->cr8 = kvm_get_cr8(vcpu);
sregs->efer = vcpu->arch.efer;
sregs->apic_base = kvm_get_apic_base(vcpu);
memset(sregs->interrupt_bitmap, 0, sizeof sregs->interrupt_bitmap);
if (vcpu->arch.interrupt.pending && !vcpu->arch.interrupt.soft)
set_bit(vcpu->arch.interrupt.nr,
(unsigned long *)sregs->interrupt_bitmap);
return 0;
}
int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
kvm_apic_accept_events(vcpu);
if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED &&
vcpu->arch.pv.pv_unhalted)
mp_state->mp_state = KVM_MP_STATE_RUNNABLE;
else
mp_state->mp_state = vcpu->arch.mp_state;
return 0;
}
int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu,
struct kvm_mp_state *mp_state)
{
if (!kvm_vcpu_has_lapic(vcpu) &&
mp_state->mp_state != KVM_MP_STATE_RUNNABLE)
return -EINVAL;
if (mp_state->mp_state == KVM_MP_STATE_SIPI_RECEIVED) {
vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
set_bit(KVM_APIC_SIPI, &vcpu->arch.apic->pending_events);
} else
vcpu->arch.mp_state = mp_state->mp_state;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
int kvm_task_switch(struct kvm_vcpu *vcpu, u16 tss_selector, int idt_index,
int reason, bool has_error_code, u32 error_code)
{
struct x86_emulate_ctxt *ctxt = &vcpu->arch.emulate_ctxt;
int ret;
init_emulate_ctxt(vcpu);
ret = emulator_task_switch(ctxt, tss_selector, idt_index, reason,
has_error_code, error_code);
if (ret)
return EMULATE_FAIL;
kvm_rip_write(vcpu, ctxt->eip);
kvm_set_rflags(vcpu, ctxt->eflags);
kvm_make_request(KVM_REQ_EVENT, vcpu);
return EMULATE_DONE;
}
EXPORT_SYMBOL_GPL(kvm_task_switch);
int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu,
struct kvm_sregs *sregs)
{
int mmu_reset_needed = 0;
int pending_vec, max_bits, idx;
struct desc_ptr dt;
if (!guest_cpuid_has_xsave(vcpu) && (sregs->cr4 & X86_CR4_OSXSAVE))
return -EINVAL;
dt.size = sregs->idt.limit;
dt.address = sregs->idt.base;
kvm_x86_ops->set_idt(vcpu, &dt);
dt.size = sregs->gdt.limit;
dt.address = sregs->gdt.base;
kvm_x86_ops->set_gdt(vcpu, &dt);
vcpu->arch.cr2 = sregs->cr2;
mmu_reset_needed |= kvm_read_cr3(vcpu) != sregs->cr3;
vcpu->arch.cr3 = sregs->cr3;
__set_bit(VCPU_EXREG_CR3, (ulong *)&vcpu->arch.regs_avail);
kvm_set_cr8(vcpu, sregs->cr8);
mmu_reset_needed |= vcpu->arch.efer != sregs->efer;
kvm_x86_ops->set_efer(vcpu, sregs->efer);
kvm_set_apic_base(vcpu, sregs->apic_base);
mmu_reset_needed |= kvm_read_cr0(vcpu) != sregs->cr0;
kvm_x86_ops->set_cr0(vcpu, sregs->cr0);
vcpu->arch.cr0 = sregs->cr0;
mmu_reset_needed |= kvm_read_cr4(vcpu) != sregs->cr4;
kvm_x86_ops->set_cr4(vcpu, sregs->cr4);
if (sregs->cr4 & X86_CR4_OSXSAVE)
kvm_update_cpuid(vcpu);
idx = srcu_read_lock(&vcpu->kvm->srcu);
if (!is_long_mode(vcpu) && is_pae(vcpu)) {
load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
mmu_reset_needed = 1;
}
srcu_read_unlock(&vcpu->kvm->srcu, idx);
if (mmu_reset_needed)
kvm_mmu_reset_context(vcpu);
max_bits = KVM_NR_INTERRUPTS;
pending_vec = find_first_bit(
(const unsigned long *)sregs->interrupt_bitmap, max_bits);
if (pending_vec < max_bits) {
kvm_queue_interrupt(vcpu, pending_vec, false);
pr_debug("Set back pending irq %d\n", pending_vec);
}
kvm_set_segment(vcpu, &sregs->cs, VCPU_SREG_CS);
kvm_set_segment(vcpu, &sregs->ds, VCPU_SREG_DS);
kvm_set_segment(vcpu, &sregs->es, VCPU_SREG_ES);
kvm_set_segment(vcpu, &sregs->fs, VCPU_SREG_FS);
kvm_set_segment(vcpu, &sregs->gs, VCPU_SREG_GS);
kvm_set_segment(vcpu, &sregs->ss, VCPU_SREG_SS);
kvm_set_segment(vcpu, &sregs->tr, VCPU_SREG_TR);
kvm_set_segment(vcpu, &sregs->ldt, VCPU_SREG_LDTR);
update_cr8_intercept(vcpu);
/* Older userspace won't unhalt the vcpu on reset. */
if (kvm_vcpu_is_bsp(vcpu) && kvm_rip_read(vcpu) == 0xfff0 &&
sregs->cs.selector == 0xf000 && sregs->cs.base == 0xffff0000 &&
!is_protmode(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
kvm_make_request(KVM_REQ_EVENT, vcpu);
return 0;
}
int kvm_arch_vcpu_ioctl_set_guest_debug(struct kvm_vcpu *vcpu,
struct kvm_guest_debug *dbg)
{
unsigned long rflags;
int i, r;
if (dbg->control & (KVM_GUESTDBG_INJECT_DB | KVM_GUESTDBG_INJECT_BP)) {
r = -EBUSY;
if (vcpu->arch.exception.pending)
goto out;
if (dbg->control & KVM_GUESTDBG_INJECT_DB)
kvm_queue_exception(vcpu, DB_VECTOR);
else
kvm_queue_exception(vcpu, BP_VECTOR);
}
/*
* Read rflags as long as potentially injected trace flags are still
* filtered out.
*/
rflags = kvm_get_rflags(vcpu);
vcpu->guest_debug = dbg->control;
if (!(vcpu->guest_debug & KVM_GUESTDBG_ENABLE))
vcpu->guest_debug = 0;
if (vcpu->guest_debug & KVM_GUESTDBG_USE_HW_BP) {
for (i = 0; i < KVM_NR_DB_REGS; ++i)
vcpu->arch.eff_db[i] = dbg->arch.debugreg[i];
vcpu->arch.guest_debug_dr7 = dbg->arch.debugreg[7];
} else {
for (i = 0; i < KVM_NR_DB_REGS; i++)
vcpu->arch.eff_db[i] = vcpu->arch.db[i];
}
kvm_update_dr7(vcpu);
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
vcpu->arch.singlestep_rip = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
/*
* Trigger an rflags update that will inject or remove the trace
* flags.
*/
kvm_set_rflags(vcpu, rflags);
kvm_x86_ops->update_db_bp_intercept(vcpu);
r = 0;
out:
return r;
}
/*
* Translate a guest virtual address to a guest physical address.
*/
int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu,
struct kvm_translation *tr)
{
unsigned long vaddr = tr->linear_address;
gpa_t gpa;
int idx;
idx = srcu_read_lock(&vcpu->kvm->srcu);
gpa = kvm_mmu_gva_to_gpa_system(vcpu, vaddr, NULL);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
tr->physical_address = gpa;
tr->valid = gpa != UNMAPPED_GVA;
tr->writeable = 1;
tr->usermode = 0;
return 0;
}
int kvm_arch_vcpu_ioctl_get_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
struct i387_fxsave_struct *fxsave =
&vcpu->arch.guest_fpu.state->fxsave;
memcpy(fpu->fpr, fxsave->st_space, 128);
fpu->fcw = fxsave->cwd;
fpu->fsw = fxsave->swd;
fpu->ftwx = fxsave->twd;
fpu->last_opcode = fxsave->fop;
fpu->last_ip = fxsave->rip;
fpu->last_dp = fxsave->rdp;
memcpy(fpu->xmm, fxsave->xmm_space, sizeof fxsave->xmm_space);
return 0;
}
int kvm_arch_vcpu_ioctl_set_fpu(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
{
struct i387_fxsave_struct *fxsave =
&vcpu->arch.guest_fpu.state->fxsave;
memcpy(fxsave->st_space, fpu->fpr, 128);
fxsave->cwd = fpu->fcw;
fxsave->swd = fpu->fsw;
fxsave->twd = fpu->ftwx;
fxsave->fop = fpu->last_opcode;
fxsave->rip = fpu->last_ip;
fxsave->rdp = fpu->last_dp;
memcpy(fxsave->xmm_space, fpu->xmm, sizeof fxsave->xmm_space);
return 0;
}
int fx_init(struct kvm_vcpu *vcpu)
{
int err;
err = fpu_alloc(&vcpu->arch.guest_fpu);
if (err)
return err;
fpu_finit(&vcpu->arch.guest_fpu);
/*
* Ensure guest xcr0 is valid for loading
*/
vcpu->arch.xcr0 = XSTATE_FP;
vcpu->arch.cr0 |= X86_CR0_ET;
return 0;
}
EXPORT_SYMBOL_GPL(fx_init);
static void fx_free(struct kvm_vcpu *vcpu)
{
fpu_free(&vcpu->arch.guest_fpu);
}
void kvm_load_guest_fpu(struct kvm_vcpu *vcpu)
{
if (vcpu->guest_fpu_loaded)
return;
/*
* Restore all possible states in the guest,
* and assume host would use all available bits.
* Guest xcr0 would be loaded later.
*/
kvm_put_guest_xcr0(vcpu);
vcpu->guest_fpu_loaded = 1;
__kernel_fpu_begin();
fpu_restore_checking(&vcpu->arch.guest_fpu);
trace_kvm_fpu(1);
}
void kvm_put_guest_fpu(struct kvm_vcpu *vcpu)
{
kvm_put_guest_xcr0(vcpu);
if (!vcpu->guest_fpu_loaded)
return;
vcpu->guest_fpu_loaded = 0;
fpu_save_init(&vcpu->arch.guest_fpu);
__kernel_fpu_end();
++vcpu->stat.fpu_reload;
kvm_make_request(KVM_REQ_DEACTIVATE_FPU, vcpu);
trace_kvm_fpu(0);
}
void kvm_arch_vcpu_free(struct kvm_vcpu *vcpu)
{
kvmclock_reset(vcpu);
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fx_free(vcpu);
kvm_x86_ops->vcpu_free(vcpu);
}
struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm,
unsigned int id)
{
if (check_tsc_unstable() && atomic_read(&kvm->online_vcpus) != 0)
printk_once(KERN_WARNING
"kvm: SMP vm created on host with unstable TSC; "
"guest TSC will not be reliable\n");
return kvm_x86_ops->vcpu_create(kvm, id);
}
int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu)
{
int r;
vcpu->arch.mtrr_state.have_fixed = 1;
r = vcpu_load(vcpu);
if (r)
return r;
kvm_vcpu_reset(vcpu);
kvm_mmu_setup(vcpu);
vcpu_put(vcpu);
return r;
}
int kvm_arch_vcpu_postcreate(struct kvm_vcpu *vcpu)
{
int r;
struct msr_data msr;
r = vcpu_load(vcpu);
if (r)
return r;
msr.data = 0x0;
msr.index = MSR_IA32_TSC;
msr.host_initiated = true;
kvm_write_tsc(vcpu, &msr);
vcpu_put(vcpu);
return r;
}
void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu)
{
int r;
vcpu->arch.apf.msr_val = 0;
r = vcpu_load(vcpu);
BUG_ON(r);
kvm_mmu_unload(vcpu);
vcpu_put(vcpu);
fx_free(vcpu);
kvm_x86_ops->vcpu_free(vcpu);
}
void kvm_vcpu_reset(struct kvm_vcpu *vcpu)
{
atomic_set(&vcpu->arch.nmi_queued, 0);
vcpu->arch.nmi_pending = 0;
vcpu->arch.nmi_injected = false;
memset(vcpu->arch.db, 0, sizeof(vcpu->arch.db));
vcpu->arch.dr6 = DR6_FIXED_1;
vcpu->arch.dr7 = DR7_FIXED_1;
kvm_update_dr7(vcpu);
kvm_make_request(KVM_REQ_EVENT, vcpu);
vcpu->arch.apf.msr_val = 0;
vcpu->arch.st.msr_val = 0;
kvmclock_reset(vcpu);
kvm_clear_async_pf_completion_queue(vcpu);
kvm_async_pf_hash_reset(vcpu);
vcpu->arch.apf.halted = false;
kvm_pmu_reset(vcpu);
memset(vcpu->arch.regs, 0, sizeof(vcpu->arch.regs));
vcpu->arch.regs_avail = ~0;
vcpu->arch.regs_dirty = ~0;
kvm_x86_ops->vcpu_reset(vcpu);
}
void kvm_vcpu_deliver_sipi_vector(struct kvm_vcpu *vcpu, unsigned int vector)
{
struct kvm_segment cs;
kvm_get_segment(vcpu, &cs, VCPU_SREG_CS);
cs.selector = vector << 8;
cs.base = vector << 12;
kvm_set_segment(vcpu, &cs, VCPU_SREG_CS);
kvm_rip_write(vcpu, 0);
}
int kvm_arch_hardware_enable(void *garbage)
{
struct kvm *kvm;
struct kvm_vcpu *vcpu;
int i;
int ret;
u64 local_tsc;
u64 max_tsc = 0;
bool stable, backwards_tsc = false;
kvm_shared_msr_cpu_online();
ret = kvm_x86_ops->hardware_enable(garbage);
if (ret != 0)
return ret;
local_tsc = native_read_tsc();
stable = !check_tsc_unstable();
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
if (!stable && vcpu->cpu == smp_processor_id())
set_bit(KVM_REQ_CLOCK_UPDATE, &vcpu->requests);
if (stable && vcpu->arch.last_host_tsc > local_tsc) {
backwards_tsc = true;
if (vcpu->arch.last_host_tsc > max_tsc)
max_tsc = vcpu->arch.last_host_tsc;
}
}
}
/*
* Sometimes, even reliable TSCs go backwards. This happens on
* platforms that reset TSC during suspend or hibernate actions, but
* maintain synchronization. We must compensate. Fortunately, we can
* detect that condition here, which happens early in CPU bringup,
* before any KVM threads can be running. Unfortunately, we can't
* bring the TSCs fully up to date with real time, as we aren't yet far
* enough into CPU bringup that we know how much real time has actually
* elapsed; our helper function, get_kernel_ns() will be using boot
* variables that haven't been updated yet.
*
* So we simply find the maximum observed TSC above, then record the
* adjustment to TSC in each VCPU. When the VCPU later gets loaded,
* the adjustment will be applied. Note that we accumulate
* adjustments, in case multiple suspend cycles happen before some VCPU
* gets a chance to run again. In the event that no KVM threads get a
* chance to run, we will miss the entire elapsed period, as we'll have
* reset last_host_tsc, so VCPUs will not have the TSC adjusted and may
* loose cycle time. This isn't too big a deal, since the loss will be
* uniform across all VCPUs (not to mention the scenario is extremely
* unlikely). It is possible that a second hibernate recovery happens
* much faster than a first, causing the observed TSC here to be
* smaller; this would require additional padding adjustment, which is
* why we set last_host_tsc to the local tsc observed here.
*
* N.B. - this code below runs only on platforms with reliable TSC,
* as that is the only way backwards_tsc is set above. Also note
* that this runs for ALL vcpus, which is not a bug; all VCPUs should
* have the same delta_cyc adjustment applied if backwards_tsc
* is detected. Note further, this adjustment is only done once,
* as we reset last_host_tsc on all VCPUs to stop this from being
* called multiple times (one for each physical CPU bringup).
*
* Platforms with unreliable TSCs don't have to deal with this, they
* will be compensated by the logic in vcpu_load, which sets the TSC to
* catchup mode. This will catchup all VCPUs to real time, but cannot
* guarantee that they stay in perfect synchronization.
*/
if (backwards_tsc) {
u64 delta_cyc = max_tsc - local_tsc;
list_for_each_entry(kvm, &vm_list, vm_list) {
kvm_for_each_vcpu(i, vcpu, kvm) {
vcpu->arch.tsc_offset_adjustment += delta_cyc;
vcpu->arch.last_host_tsc = local_tsc;
set_bit(KVM_REQ_MASTERCLOCK_UPDATE,
&vcpu->requests);
}
/*
* We have to disable TSC offset matching.. if you were
* booting a VM while issuing an S4 host suspend....
* you may have some problem. Solving this issue is
* left as an exercise to the reader.
*/
kvm->arch.last_tsc_nsec = 0;
kvm->arch.last_tsc_write = 0;
}
}
return 0;
}
void kvm_arch_hardware_disable(void *garbage)
{
kvm_x86_ops->hardware_disable(garbage);
drop_user_return_notifiers(garbage);
}
int kvm_arch_hardware_setup(void)
{
return kvm_x86_ops->hardware_setup();
}
void kvm_arch_hardware_unsetup(void)
{
kvm_x86_ops->hardware_unsetup();
}
void kvm_arch_check_processor_compat(void *rtn)
{
kvm_x86_ops->check_processor_compatibility(rtn);
}
bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu)
{
return irqchip_in_kernel(vcpu->kvm) == (vcpu->arch.apic != NULL);
}
struct static_key kvm_no_apic_vcpu __read_mostly;
int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu)
{
struct page *page;
struct kvm *kvm;
int r;
BUG_ON(vcpu->kvm == NULL);
kvm = vcpu->kvm;
vcpu->arch.pv.pv_unhalted = false;
vcpu->arch.emulate_ctxt.ops = &emulate_ops;
if (!irqchip_in_kernel(kvm) || kvm_vcpu_is_bsp(vcpu))
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
else
vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED;
page = alloc_page(GFP_KERNEL | __GFP_ZERO);
if (!page) {
r = -ENOMEM;
goto fail;
}
vcpu->arch.pio_data = page_address(page);
kvm_set_tsc_khz(vcpu, max_tsc_khz);
r = kvm_mmu_create(vcpu);
if (r < 0)
goto fail_free_pio_data;
if (irqchip_in_kernel(kvm)) {
r = kvm_create_lapic(vcpu);
if (r < 0)
goto fail_mmu_destroy;
} else
static_key_slow_inc(&kvm_no_apic_vcpu);
vcpu->arch.mce_banks = kzalloc(KVM_MAX_MCE_BANKS * sizeof(u64) * 4,
GFP_KERNEL);
if (!vcpu->arch.mce_banks) {
r = -ENOMEM;
goto fail_free_lapic;
}
vcpu->arch.mcg_cap = KVM_MAX_MCE_BANKS;
if (!zalloc_cpumask_var(&vcpu->arch.wbinvd_dirty_mask, GFP_KERNEL)) {
r = -ENOMEM;
goto fail_free_mce_banks;
}
r = fx_init(vcpu);
if (r)
goto fail_free_wbinvd_dirty_mask;
vcpu->arch.ia32_tsc_adjust_msr = 0x0;
vcpu->arch.pv_time_enabled = false;
vcpu->arch.guest_supported_xcr0 = 0;
vcpu->arch.guest_xstate_size = XSAVE_HDR_SIZE + XSAVE_HDR_OFFSET;
kvm_async_pf_hash_reset(vcpu);
kvm_pmu_init(vcpu);
return 0;
fail_free_wbinvd_dirty_mask:
free_cpumask_var(vcpu->arch.wbinvd_dirty_mask);
fail_free_mce_banks:
kfree(vcpu->arch.mce_banks);
fail_free_lapic:
kvm_free_lapic(vcpu);
fail_mmu_destroy:
kvm_mmu_destroy(vcpu);
fail_free_pio_data:
free_page((unsigned long)vcpu->arch.pio_data);
fail:
return r;
}
void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu)
{
int idx;
kvm_pmu_destroy(vcpu);
kfree(vcpu->arch.mce_banks);
kvm_free_lapic(vcpu);
idx = srcu_read_lock(&vcpu->kvm->srcu);
kvm_mmu_destroy(vcpu);
srcu_read_unlock(&vcpu->kvm->srcu, idx);
free_page((unsigned long)vcpu->arch.pio_data);
if (!irqchip_in_kernel(vcpu->kvm))
static_key_slow_dec(&kvm_no_apic_vcpu);
}
int kvm_arch_init_vm(struct kvm *kvm, unsigned long type)
{
if (type)
return -EINVAL;
INIT_LIST_HEAD(&kvm->arch.active_mmu_pages);
INIT_LIST_HEAD(&kvm->arch.zapped_obsolete_pages);
INIT_LIST_HEAD(&kvm->arch.assigned_dev_head);
atomic_set(&kvm->arch.noncoherent_dma_count, 0);
/* Reserve bit 0 of irq_sources_bitmap for userspace irq source */
set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap);
/* Reserve bit 1 of irq_sources_bitmap for irqfd-resampler */
set_bit(KVM_IRQFD_RESAMPLE_IRQ_SOURCE_ID,
&kvm->arch.irq_sources_bitmap);
raw_spin_lock_init(&kvm->arch.tsc_write_lock);
mutex_init(&kvm->arch.apic_map_lock);
spin_lock_init(&kvm->arch.pvclock_gtod_sync_lock);
pvclock_update_vm_gtod_copy(kvm);
return 0;
}
static void kvm_unload_vcpu_mmu(struct kvm_vcpu *vcpu)
{
int r;
r = vcpu_load(vcpu);
BUG_ON(r);
kvm_mmu_unload(vcpu);
vcpu_put(vcpu);
}
static void kvm_free_vcpus(struct kvm *kvm)
{
unsigned int i;
struct kvm_vcpu *vcpu;
/*
* Unpin any mmu pages first.
*/
kvm_for_each_vcpu(i, vcpu, kvm) {
kvm_clear_async_pf_completion_queue(vcpu);
kvm_unload_vcpu_mmu(vcpu);
}
kvm_for_each_vcpu(i, vcpu, kvm)
kvm_arch_vcpu_free(vcpu);
mutex_lock(&kvm->lock);
for (i = 0; i < atomic_read(&kvm->online_vcpus); i++)
kvm->vcpus[i] = NULL;
atomic_set(&kvm->online_vcpus, 0);
mutex_unlock(&kvm->lock);
}
void kvm_arch_sync_events(struct kvm *kvm)
{
kvm_free_all_assigned_devices(kvm);
kvm_free_pit(kvm);
}
void kvm_arch_destroy_vm(struct kvm *kvm)
{
if (current->mm == kvm->mm) {
/*
* Free memory regions allocated on behalf of userspace,
* unless the the memory map has changed due to process exit
* or fd copying.
*/
struct kvm_userspace_memory_region mem;
memset(&mem, 0, sizeof(mem));
mem.slot = APIC_ACCESS_PAGE_PRIVATE_MEMSLOT;
kvm_set_memory_region(kvm, &mem);
mem.slot = IDENTITY_PAGETABLE_PRIVATE_MEMSLOT;
kvm_set_memory_region(kvm, &mem);
mem.slot = TSS_PRIVATE_MEMSLOT;
kvm_set_memory_region(kvm, &mem);
}
kvm_iommu_unmap_guest(kvm);
kfree(kvm->arch.vpic);
kfree(kvm->arch.vioapic);
kvm_free_vcpus(kvm);
if (kvm->arch.apic_access_page)
put_page(kvm->arch.apic_access_page);
if (kvm->arch.ept_identity_pagetable)
put_page(kvm->arch.ept_identity_pagetable);
kfree(rcu_dereference_check(kvm->arch.apic_map, 1));
}
void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
struct kvm_memory_slot *dont)
{
int i;
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
if (!dont || free->arch.rmap[i] != dont->arch.rmap[i]) {
kvm_kvfree(free->arch.rmap[i]);
free->arch.rmap[i] = NULL;
}
if (i == 0)
continue;
if (!dont || free->arch.lpage_info[i - 1] !=
dont->arch.lpage_info[i - 1]) {
kvm_kvfree(free->arch.lpage_info[i - 1]);
free->arch.lpage_info[i - 1] = NULL;
}
}
}
int kvm_arch_create_memslot(struct kvm *kvm, struct kvm_memory_slot *slot,
unsigned long npages)
{
int i;
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
unsigned long ugfn;
int lpages;
int level = i + 1;
lpages = gfn_to_index(slot->base_gfn + npages - 1,
slot->base_gfn, level) + 1;
slot->arch.rmap[i] =
kvm_kvzalloc(lpages * sizeof(*slot->arch.rmap[i]));
if (!slot->arch.rmap[i])
goto out_free;
if (i == 0)
continue;
slot->arch.lpage_info[i - 1] = kvm_kvzalloc(lpages *
sizeof(*slot->arch.lpage_info[i - 1]));
if (!slot->arch.lpage_info[i - 1])
goto out_free;
if (slot->base_gfn & (KVM_PAGES_PER_HPAGE(level) - 1))
slot->arch.lpage_info[i - 1][0].write_count = 1;
if ((slot->base_gfn + npages) & (KVM_PAGES_PER_HPAGE(level) - 1))
slot->arch.lpage_info[i - 1][lpages - 1].write_count = 1;
ugfn = slot->userspace_addr >> PAGE_SHIFT;
/*
* If the gfn and userspace address are not aligned wrt each
* other, or if explicitly asked to, disable large page
* support for this slot
*/
if ((slot->base_gfn ^ ugfn) & (KVM_PAGES_PER_HPAGE(level) - 1) ||
!kvm_largepages_enabled()) {
unsigned long j;
for (j = 0; j < lpages; ++j)
slot->arch.lpage_info[i - 1][j].write_count = 1;
}
}
return 0;
out_free:
for (i = 0; i < KVM_NR_PAGE_SIZES; ++i) {
kvm_kvfree(slot->arch.rmap[i]);
slot->arch.rmap[i] = NULL;
if (i == 0)
continue;
kvm_kvfree(slot->arch.lpage_info[i - 1]);
slot->arch.lpage_info[i - 1] = NULL;
}
return -ENOMEM;
}
void kvm_arch_memslots_updated(struct kvm *kvm)
{
/*
* memslots->generation has been incremented.
* mmio generation may have reached its maximum value.
*/
kvm_mmu_invalidate_mmio_sptes(kvm);
}
int kvm_arch_prepare_memory_region(struct kvm *kvm,
struct kvm_memory_slot *memslot,
struct kvm_userspace_memory_region *mem,
enum kvm_mr_change change)
{
/*
* Only private memory slots need to be mapped here since
* KVM_SET_MEMORY_REGION ioctl is no longer supported.
*/
if ((memslot->id >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_CREATE)) {
unsigned long userspace_addr;
/*
* MAP_SHARED to prevent internal slot pages from being moved
* by fork()/COW.
*/
userspace_addr = vm_mmap(NULL, 0, memslot->npages * PAGE_SIZE,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, 0);
if (IS_ERR((void *)userspace_addr))
return PTR_ERR((void *)userspace_addr);
memslot->userspace_addr = userspace_addr;
}
return 0;
}
void kvm_arch_commit_memory_region(struct kvm *kvm,
struct kvm_userspace_memory_region *mem,
const struct kvm_memory_slot *old,
enum kvm_mr_change change)
{
int nr_mmu_pages = 0;
if ((mem->slot >= KVM_USER_MEM_SLOTS) && (change == KVM_MR_DELETE)) {
int ret;
ret = vm_munmap(old->userspace_addr,
old->npages * PAGE_SIZE);
if (ret < 0)
printk(KERN_WARNING
"kvm_vm_ioctl_set_memory_region: "
"failed to munmap memory\n");
}
if (!kvm->arch.n_requested_mmu_pages)
nr_mmu_pages = kvm_mmu_calculate_mmu_pages(kvm);
if (nr_mmu_pages)
kvm_mmu_change_mmu_pages(kvm, nr_mmu_pages);
/*
* Write protect all pages for dirty logging.
* Existing largepage mappings are destroyed here and new ones will
* not be created until the end of the logging.
*/
if ((change != KVM_MR_DELETE) && (mem->flags & KVM_MEM_LOG_DIRTY_PAGES))
kvm_mmu_slot_remove_write_access(kvm, mem->slot);
}
void kvm_arch_flush_shadow_all(struct kvm *kvm)
{
kvm_mmu_invalidate_zap_all_pages(kvm);
}
void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
struct kvm_memory_slot *slot)
{
kvm_mmu_invalidate_zap_all_pages(kvm);
}
int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu)
{
return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE &&
!vcpu->arch.apf.halted)
|| !list_empty_careful(&vcpu->async_pf.done)
|| kvm_apic_has_events(vcpu)
|| vcpu->arch.pv.pv_unhalted
|| atomic_read(&vcpu->arch.nmi_queued) ||
(kvm_arch_interrupt_allowed(vcpu) &&
kvm_cpu_has_interrupt(vcpu));
}
int kvm_arch_vcpu_should_kick(struct kvm_vcpu *vcpu)
{
return kvm_vcpu_exiting_guest_mode(vcpu) == IN_GUEST_MODE;
}
int kvm_arch_interrupt_allowed(struct kvm_vcpu *vcpu)
{
return kvm_x86_ops->interrupt_allowed(vcpu);
}
bool kvm_is_linear_rip(struct kvm_vcpu *vcpu, unsigned long linear_rip)
{
unsigned long current_rip = kvm_rip_read(vcpu) +
get_segment_base(vcpu, VCPU_SREG_CS);
return current_rip == linear_rip;
}
EXPORT_SYMBOL_GPL(kvm_is_linear_rip);
unsigned long kvm_get_rflags(struct kvm_vcpu *vcpu)
{
unsigned long rflags;
rflags = kvm_x86_ops->get_rflags(vcpu);
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP)
rflags &= ~X86_EFLAGS_TF;
return rflags;
}
EXPORT_SYMBOL_GPL(kvm_get_rflags);
void kvm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
{
if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP &&
kvm_is_linear_rip(vcpu, vcpu->arch.singlestep_rip))
rflags |= X86_EFLAGS_TF;
kvm_x86_ops->set_rflags(vcpu, rflags);
kvm_make_request(KVM_REQ_EVENT, vcpu);
}
EXPORT_SYMBOL_GPL(kvm_set_rflags);
void kvm_arch_async_page_ready(struct kvm_vcpu *vcpu, struct kvm_async_pf *work)
{
int r;
if ((vcpu->arch.mmu.direct_map != work->arch.direct_map) ||
work->wakeup_all)
return;
r = kvm_mmu_reload(vcpu);
if (unlikely(r))
return;
if (!vcpu->arch.mmu.direct_map &&
work->arch.cr3 != vcpu->arch.mmu.get_cr3(vcpu))
return;
vcpu->arch.mmu.page_fault(vcpu, work->gva, 0, true);
}
static inline u32 kvm_async_pf_hash_fn(gfn_t gfn)
{
return hash_32(gfn & 0xffffffff, order_base_2(ASYNC_PF_PER_VCPU));
}
static inline u32 kvm_async_pf_next_probe(u32 key)
{
return (key + 1) & (roundup_pow_of_two(ASYNC_PF_PER_VCPU) - 1);
}
static void kvm_add_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
u32 key = kvm_async_pf_hash_fn(gfn);
while (vcpu->arch.apf.gfns[key] != ~0)
key = kvm_async_pf_next_probe(key);
vcpu->arch.apf.gfns[key] = gfn;
}
static u32 kvm_async_pf_gfn_slot(struct kvm_vcpu *vcpu, gfn_t gfn)
{
int i;
u32 key = kvm_async_pf_hash_fn(gfn);
for (i = 0; i < roundup_pow_of_two(ASYNC_PF_PER_VCPU) &&
(vcpu->arch.apf.gfns[key] != gfn &&
vcpu->arch.apf.gfns[key] != ~0); i++)
key = kvm_async_pf_next_probe(key);
return key;
}
bool kvm_find_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
return vcpu->arch.apf.gfns[kvm_async_pf_gfn_slot(vcpu, gfn)] == gfn;
}
static void kvm_del_async_pf_gfn(struct kvm_vcpu *vcpu, gfn_t gfn)
{
u32 i, j, k;
i = j = kvm_async_pf_gfn_slot(vcpu, gfn);
while (true) {
vcpu->arch.apf.gfns[i] = ~0;
do {
j = kvm_async_pf_next_probe(j);
if (vcpu->arch.apf.gfns[j] == ~0)
return;
k = kvm_async_pf_hash_fn(vcpu->arch.apf.gfns[j]);
/*
* k lies cyclically in ]i,j]
* | i.k.j |
* |....j i.k.| or |.k..j i...|
*/
} while ((i <= j) ? (i < k && k <= j) : (i < k || k <= j));
vcpu->arch.apf.gfns[i] = vcpu->arch.apf.gfns[j];
i = j;
}
}
static int apf_put_user(struct kvm_vcpu *vcpu, u32 val)
{
return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apf.data, &val,
sizeof(val));
}
void kvm_arch_async_page_not_present(struct kvm_vcpu *vcpu,
struct kvm_async_pf *work)
{
struct x86_exception fault;
trace_kvm_async_pf_not_present(work->arch.token, work->gva);
kvm_add_async_pf_gfn(vcpu, work->arch.gfn);
if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) ||
(vcpu->arch.apf.send_user_only &&
kvm_x86_ops->get_cpl(vcpu) == 0))
kvm_make_request(KVM_REQ_APF_HALT, vcpu);
else if (!apf_put_user(vcpu, KVM_PV_REASON_PAGE_NOT_PRESENT)) {
fault.vector = PF_VECTOR;
fault.error_code_valid = true;
fault.error_code = 0;
fault.nested_page_fault = false;
fault.address = work->arch.token;
kvm_inject_page_fault(vcpu, &fault);
}
}
void kvm_arch_async_page_present(struct kvm_vcpu *vcpu,
struct kvm_async_pf *work)
{
struct x86_exception fault;
trace_kvm_async_pf_ready(work->arch.token, work->gva);
if (work->wakeup_all)
work->arch.token = ~0; /* broadcast wakeup */
else
kvm_del_async_pf_gfn(vcpu, work->arch.gfn);
if ((vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED) &&
!apf_put_user(vcpu, KVM_PV_REASON_PAGE_READY)) {
fault.vector = PF_VECTOR;
fault.error_code_valid = true;
fault.error_code = 0;
fault.nested_page_fault = false;
fault.address = work->arch.token;
kvm_inject_page_fault(vcpu, &fault);
}
vcpu->arch.apf.halted = false;
vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
}
bool kvm_arch_can_inject_async_page_present(struct kvm_vcpu *vcpu)
{
if (!(vcpu->arch.apf.msr_val & KVM_ASYNC_PF_ENABLED))
return true;
else
return !kvm_event_needs_reinjection(vcpu) &&
kvm_x86_ops->interrupt_allowed(vcpu);
}
void kvm_arch_register_noncoherent_dma(struct kvm *kvm)
{
atomic_inc(&kvm->arch.noncoherent_dma_count);
}
EXPORT_SYMBOL_GPL(kvm_arch_register_noncoherent_dma);
void kvm_arch_unregister_noncoherent_dma(struct kvm *kvm)
{
atomic_dec(&kvm->arch.noncoherent_dma_count);
}
EXPORT_SYMBOL_GPL(kvm_arch_unregister_noncoherent_dma);
bool kvm_arch_has_noncoherent_dma(struct kvm *kvm)
{
return atomic_read(&kvm->arch.noncoherent_dma_count);
}
EXPORT_SYMBOL_GPL(kvm_arch_has_noncoherent_dma);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_exit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_inj_virq);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_page_fault);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_msr);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_cr);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmrun);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_vmexit_inject);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intr_vmexit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_invlpga);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_skinit);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_nested_intercepts);
EXPORT_TRACEPOINT_SYMBOL_GPL(kvm_write_tsc_offset);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5794_2 |
crossvul-cpp_data_bad_5114_0 | /* netscreen.c
*
* Juniper NetScreen snoop output parser
* Created by re-using a lot of code from cosine.c
* Copyright (c) 2007 by Sake Blok <sake@euronet.nl>
*
* Wiretap Library
* Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "wtap-int.h"
#include "netscreen.h"
#include "file_wrappers.h"
#include <stdlib.h>
#include <string.h>
/* XXX TODO:
*
* o Construct a list of interfaces, with interface names, give
* them link-layer types based on the interface name and packet
* data, and supply interface IDs with each packet (i.e., make
* this supply a pcap-ng-style set of interfaces and associate
* packets with interfaces). This is probably the right way
* to "Pass the interface names and the traffic direction to either
* the frame-structure, a pseudo-header or use PPI." See the
* message at
*
* http://www.wireshark.org/lists/wireshark-dev/200708/msg00029.html
*
* to see whether any further discussion is still needed. I suspect
* it doesn't; pcap-NG existed at the time, as per the final
* message in that thread:
*
* http://www.wireshark.org/lists/wireshark-dev/200708/msg00039.html
*
* but I don't think we fully *supported* it at that point. Now
* that we do, we have the infrastructure to support this, except
* that we currently have no way to translate interface IDs to
* interface names in the "frame" dissector or to supply interface
* information as part of the packet metadata from Wiretap modules.
* That should be fixed so that we can show interface information,
* such as the interface name, in packet dissections from, for example,
* pcap-NG captures.
*/
static gboolean info_line(const gchar *line);
static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr);
static gboolean netscreen_check_file_type(wtap *wth, int *err,
gchar **err_info);
static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset);
static gboolean netscreen_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info);
static int parse_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line,
char *cap_int, gboolean *cap_dir, char *cap_dst,
int *err, gchar **err_info);
static gboolean parse_netscreen_hex_dump(FILE_T fh, int pkt_len,
const char *cap_int, const char *cap_dst, struct wtap_pkthdr *phdr,
Buffer* buf, int *err, gchar **err_info);
static int parse_single_hex_dump_line(char* rec, guint8 *buf,
guint byte_offset);
/* Returns TRUE if the line appears to be a line with protocol info.
Otherwise it returns FALSE. */
static gboolean info_line(const gchar *line)
{
int i=NETSCREEN_SPACES_ON_INFO_LINE;
while (i-- > 0) {
if (g_ascii_isspace(*line)) {
line++;
continue;
} else {
return FALSE;
}
}
return TRUE;
}
/* Seeks to the beginning of the next packet, and returns the
byte offset. Copy the header line to hdr. Returns -1 on failure,
and sets "*err" to the error and sets "*err_info" to null or an
additional error string. */
static gint64 netscreen_seek_next_packet(wtap *wth, int *err, gchar **err_info,
char *hdr)
{
gint64 cur_off;
char buf[NETSCREEN_LINE_LENGTH];
while (1) {
cur_off = file_tell(wth->fh);
if (cur_off == -1) {
/* Error */
*err = file_error(wth->fh, err_info);
return -1;
}
if (file_gets(buf, sizeof(buf), wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
break;
}
if (strstr(buf, NETSCREEN_REC_MAGIC_STR1) ||
strstr(buf, NETSCREEN_REC_MAGIC_STR2)) {
g_strlcpy(hdr, buf, NETSCREEN_LINE_LENGTH);
return cur_off;
}
}
return -1;
}
/* Look through the first part of a file to see if this is
* NetScreen snoop output.
*
* Returns TRUE if it is, FALSE if it isn't or if we get an I/O error;
* if we get an I/O error, "*err" will be set to a non-zero value and
* "*err_info" is set to null or an additional error string.
*/
static gboolean netscreen_check_file_type(wtap *wth, int *err, gchar **err_info)
{
char buf[NETSCREEN_LINE_LENGTH];
guint reclen, line;
buf[NETSCREEN_LINE_LENGTH-1] = '\0';
for (line = 0; line < NETSCREEN_HEADER_LINES_TO_CHECK; line++) {
if (file_gets(buf, NETSCREEN_LINE_LENGTH, wth->fh) == NULL) {
/* EOF or error. */
*err = file_error(wth->fh, err_info);
return FALSE;
}
reclen = (guint) strlen(buf);
if (reclen < strlen(NETSCREEN_HDR_MAGIC_STR1) ||
reclen < strlen(NETSCREEN_HDR_MAGIC_STR2)) {
continue;
}
if (strstr(buf, NETSCREEN_HDR_MAGIC_STR1) ||
strstr(buf, NETSCREEN_HDR_MAGIC_STR2)) {
return TRUE;
}
}
*err = 0;
return FALSE;
}
wtap_open_return_val netscreen_open(wtap *wth, int *err, gchar **err_info)
{
/* Look for a NetScreen snoop header line */
if (!netscreen_check_file_type(wth, err, err_info)) {
if (*err != 0 && *err != WTAP_ERR_SHORT_READ)
return WTAP_OPEN_ERROR;
return WTAP_OPEN_NOT_MINE;
}
if (file_seek(wth->fh, 0L, SEEK_SET, err) == -1) /* rewind */
return WTAP_OPEN_ERROR;
wth->file_encap = WTAP_ENCAP_UNKNOWN;
wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_NETSCREEN;
wth->snapshot_length = 0; /* not known */
wth->subtype_read = netscreen_read;
wth->subtype_seek_read = netscreen_seek_read;
wth->file_tsprec = WTAP_TSPREC_DSEC;
return WTAP_OPEN_MINE;
}
/* Find the next packet and parse it; called from wtap_read(). */
static gboolean netscreen_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
int pkt_len;
char line[NETSCREEN_LINE_LENGTH];
char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH];
gboolean cap_dir;
char cap_dst[13];
/* Find the next packet */
offset = netscreen_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
/* Parse the header */
pkt_len = parse_netscreen_rec_hdr(&wth->phdr, line, cap_int, &cap_dir,
cap_dst, err, err_info);
if (pkt_len == -1)
return FALSE;
/* Convert the ASCII hex dump to binary data, and fill in some
struct wtap_pkthdr fields */
if (!parse_netscreen_hex_dump(wth->fh, pkt_len, cap_int,
cap_dst, &wth->phdr, wth->frame_buffer, err, err_info))
return FALSE;
/*
* If the per-file encapsulation isn't known, set it to this
* packet's encapsulation.
*
* If it *is* known, and it isn't this packet's encapsulation,
* set it to WTAP_ENCAP_PER_PACKET, as this file doesn't
* have a single encapsulation for all packets in the file.
*/
if (wth->file_encap == WTAP_ENCAP_UNKNOWN)
wth->file_encap = wth->phdr.pkt_encap;
else {
if (wth->file_encap != wth->phdr.pkt_encap)
wth->file_encap = WTAP_ENCAP_PER_PACKET;
}
*data_offset = offset;
return TRUE;
}
/* Used to read packets in random-access fashion */
static gboolean
netscreen_seek_read(wtap *wth, gint64 seek_off,
struct wtap_pkthdr *phdr, Buffer *buf,
int *err, gchar **err_info)
{
int pkt_len;
char line[NETSCREEN_LINE_LENGTH];
char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH];
gboolean cap_dir;
char cap_dst[13];
if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) {
return FALSE;
}
if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) {
*err = file_error(wth->random_fh, err_info);
if (*err == 0) {
*err = WTAP_ERR_SHORT_READ;
}
return FALSE;
}
pkt_len = parse_netscreen_rec_hdr(phdr, line, cap_int, &cap_dir,
cap_dst, err, err_info);
if (pkt_len == -1)
return FALSE;
if (!parse_netscreen_hex_dump(wth->random_fh, pkt_len, cap_int,
cap_dst, phdr, buf, err, err_info))
return FALSE;
return TRUE;
}
/* Parses a packet record header. There are a few possible formats:
*
* XXX list extra formats here!
6843828.0: trust(o) len=98:00121ebbd132->00600868d659/0800
192.168.1.1 -> 192.168.1.10/6
vhl=45, tos=00, id=37739, frag=0000, ttl=64 tlen=84
tcp:ports 2222->2333, seq=3452113890, ack=1540618280, flag=5018/ACK
00 60 08 68 d6 59 00 12 1e bb d1 32 08 00 45 00 .`.h.Y.....2..E.
00 54 93 6b 00 00 40 06 63 dd c0 a8 01 01 c0 a8 .T.k..@.c.......
01 0a 08 ae 09 1d cd c3 13 e2 5b d3 f8 28 50 18 ..........[..(P.
1f d4 79 21 00 00 e7 76 89 64 16 e2 19 0a 80 09 ..y!...v.d......
31 e7 04 28 04 58 f3 d9 b1 9f 3d 65 1a db d8 61 1..(.X....=e...a
2c 21 b6 d3 20 60 0c 8c 35 98 88 cf 20 91 0e a9 ,!...`..5.......
1d 0b ..
*/
static int
parse_netscreen_rec_hdr(struct wtap_pkthdr *phdr, const char *line, char *cap_int,
gboolean *cap_dir, char *cap_dst, int *err, gchar **err_info)
{
int sec;
int dsec, pkt_len;
char direction[2];
char cap_src[13];
phdr->rec_type = REC_TYPE_PACKET;
phdr->presence_flags = WTAP_HAS_TS|WTAP_HAS_CAP_LEN;
if (sscanf(line, "%9d.%9d: %15[a-z0-9/:.-](%1[io]) len=%9d:%12s->%12s/",
&sec, &dsec, cap_int, direction, &pkt_len, cap_src, cap_dst) < 5) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: Can't parse packet-header");
return -1;
}
*cap_dir = (direction[0] == 'o' ? NETSCREEN_EGRESS : NETSCREEN_INGRESS);
phdr->ts.secs = sec;
phdr->ts.nsecs = dsec * 100000000;
phdr->len = pkt_len;
return pkt_len;
}
/* Converts ASCII hex dump to binary data, and fills in some struct
wtap_pkthdr fields. Returns TRUE on success and FALSE on any error. */
static gboolean
parse_netscreen_hex_dump(FILE_T fh, int pkt_len, const char *cap_int,
const char *cap_dst, struct wtap_pkthdr *phdr, Buffer* buf,
int *err, gchar **err_info)
{
guint8 *pd;
gchar line[NETSCREEN_LINE_LENGTH];
gchar *p;
int n, i = 0, offset = 0;
gchar dststr[13];
/* Make sure we have enough room for the packet */
ws_buffer_assure_space(buf, NETSCREEN_MAX_PACKET_LEN);
pd = ws_buffer_start_ptr(buf);
while(1) {
/* The last packet is not delimited by an empty line, but by EOF
* So accept EOF as a valid delimiter too
*/
if (file_gets(line, NETSCREEN_LINE_LENGTH, fh) == NULL) {
break;
}
/*
* Skip blanks.
* The number of blanks is not fixed - for wireless
* interfaces, there may be 14 extra spaces before
* the hex data.
*/
for (p = &line[0]; g_ascii_isspace(*p); p++)
;
/* packets are delimited with empty lines */
if (*p == '\0') {
break;
}
n = parse_single_hex_dump_line(p, pd, offset);
/* the smallest packet has a length of 6 bytes, if
* the first hex-data is less then check whether
* it is a info-line and act accordingly
*/
if (offset == 0 && n < 6) {
if (info_line(line)) {
if (++i <= NETSCREEN_MAX_INFOLINES) {
continue;
}
} else {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
}
/* If there is no more data and the line was not empty,
* then there must be an error in the file
*/
if(n == -1) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: cannot parse hex-data");
return FALSE;
}
/* Adjust the offset to the data that was just added to the buffer */
offset += n;
/* If there was more hex-data than was announced in the len=x
* header, then then there must be an error in the file
*/
if(offset > pkt_len) {
*err = WTAP_ERR_BAD_FILE;
*err_info = g_strdup("netscreen: too much hex-data");
return FALSE;
}
}
/*
* Determine the encapsulation type, based on the
* first 4 characters of the interface name
*
* XXX convert this to a 'case' structure when adding more
* (non-ethernet) interfacetypes
*/
if (strncmp(cap_int, "adsl", 4) == 0) {
/* The ADSL interface can be bridged with or without
* PPP encapsulation. Check whether the first six bytes
* of the hex data are the same as the destination mac
* address in the header. If they are, assume ethernet
* LinkLayer or else PPP
*/
g_snprintf(dststr, 13, "%02x%02x%02x%02x%02x%02x",
pd[0], pd[1], pd[2], pd[3], pd[4], pd[5]);
if (strncmp(dststr, cap_dst, 12) == 0)
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
else
phdr->pkt_encap = WTAP_ENCAP_PPP;
}
else if (strncmp(cap_int, "seri", 4) == 0)
phdr->pkt_encap = WTAP_ENCAP_PPP;
else
phdr->pkt_encap = WTAP_ENCAP_ETHERNET;
phdr->caplen = offset;
return TRUE;
}
/* Take a string representing one line from a hex dump, with leading white
* space removed, and converts the text to binary data. We place the bytes
* in the buffer at the specified offset.
*
* Returns number of bytes successfully read, -1 if bad. */
static int
parse_single_hex_dump_line(char* rec, guint8 *buf, guint byte_offset)
{
int num_items_scanned;
guint8 character;
guint8 byte;
for (num_items_scanned = 0; num_items_scanned < 16; num_items_scanned++) {
character = *rec++;
if (character >= '0' && character <= '9')
byte = character - '0' + 0;
else if (character >= 'A' && character <= 'F')
byte = character - 'A' + 0xA;
else if (character >= 'a' && character <= 'f')
byte = character - 'a' + 0xa;
else if (character == ' ' || character == '\r' || character == '\n' || character == '\0') {
/* Nothing more to parse */
break;
} else
return -1; /* not a hex digit, space before ASCII dump, or EOL */
byte <<= 4;
character = *rec++ & 0xFF;
if (character >= '0' && character <= '9')
byte += character - '0' + 0;
else if (character >= 'A' && character <= 'F')
byte += character - 'A' + 0xA;
else if (character >= 'a' && character <= 'f')
byte += character - 'a' + 0xa;
else
return -1; /* not a hex digit */
buf[byte_offset + num_items_scanned] = byte;
character = *rec++ & 0xFF;
if (character == '\0' || character == '\r' || character == '\n') {
/* Nothing more to parse */
break;
} else if (character != ' ') {
/* not space before ASCII dump */
return -1;
}
}
if (num_items_scanned == 0)
return -1;
return num_items_scanned;
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 8
* tab-width: 8
* indent-tabs-mode: t
* End:
*
* vi: set shiftwidth=8 tabstop=8 noexpandtab:
* :indentSize=8:tabSize=8:noTabs=false:
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5114_0 |
crossvul-cpp_data_bad_1027_0 | /*
* Copyright (c) 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior
* written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* sf-pcapng.c - pcapng-file-format-specific code from savefile.c
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <pcap/pcap-inttypes.h>
#include <errno.h>
#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pcap-int.h"
#include "pcap-common.h"
#ifdef HAVE_OS_PROTO_H
#include "os-proto.h"
#endif
#include "sf-pcapng.h"
/*
* Block types.
*/
/*
* Common part at the beginning of all blocks.
*/
struct block_header {
bpf_u_int32 block_type;
bpf_u_int32 total_length;
};
/*
* Common trailer at the end of all blocks.
*/
struct block_trailer {
bpf_u_int32 total_length;
};
/*
* Common options.
*/
#define OPT_ENDOFOPT 0 /* end of options */
#define OPT_COMMENT 1 /* comment string */
/*
* Option header.
*/
struct option_header {
u_short option_code;
u_short option_length;
};
/*
* Structures for the part of each block type following the common
* part.
*/
/*
* Section Header Block.
*/
#define BT_SHB 0x0A0D0D0A
#define BT_SHB_INSANE_MAX 1024*1024*1 /* 1MB should be enough */
struct section_header_block {
bpf_u_int32 byte_order_magic;
u_short major_version;
u_short minor_version;
uint64_t section_length;
/* followed by options and trailer */
};
/*
* Byte-order magic value.
*/
#define BYTE_ORDER_MAGIC 0x1A2B3C4D
/*
* Current version number. If major_version isn't PCAP_NG_VERSION_MAJOR,
* that means that this code can't read the file.
*/
#define PCAP_NG_VERSION_MAJOR 1
#define PCAP_NG_VERSION_MINOR 0
/*
* Interface Description Block.
*/
#define BT_IDB 0x00000001
struct interface_description_block {
u_short linktype;
u_short reserved;
bpf_u_int32 snaplen;
/* followed by options and trailer */
};
/*
* Options in the IDB.
*/
#define IF_NAME 2 /* interface name string */
#define IF_DESCRIPTION 3 /* interface description string */
#define IF_IPV4ADDR 4 /* interface's IPv4 address and netmask */
#define IF_IPV6ADDR 5 /* interface's IPv6 address and prefix length */
#define IF_MACADDR 6 /* interface's MAC address */
#define IF_EUIADDR 7 /* interface's EUI address */
#define IF_SPEED 8 /* interface's speed, in bits/s */
#define IF_TSRESOL 9 /* interface's time stamp resolution */
#define IF_TZONE 10 /* interface's time zone */
#define IF_FILTER 11 /* filter used when capturing on interface */
#define IF_OS 12 /* string OS on which capture on this interface was done */
#define IF_FCSLEN 13 /* FCS length for this interface */
#define IF_TSOFFSET 14 /* time stamp offset for this interface */
/*
* Enhanced Packet Block.
*/
#define BT_EPB 0x00000006
struct enhanced_packet_block {
bpf_u_int32 interface_id;
bpf_u_int32 timestamp_high;
bpf_u_int32 timestamp_low;
bpf_u_int32 caplen;
bpf_u_int32 len;
/* followed by packet data, options, and trailer */
};
/*
* Simple Packet Block.
*/
#define BT_SPB 0x00000003
struct simple_packet_block {
bpf_u_int32 len;
/* followed by packet data and trailer */
};
/*
* Packet Block.
*/
#define BT_PB 0x00000002
struct packet_block {
u_short interface_id;
u_short drops_count;
bpf_u_int32 timestamp_high;
bpf_u_int32 timestamp_low;
bpf_u_int32 caplen;
bpf_u_int32 len;
/* followed by packet data, options, and trailer */
};
/*
* Block cursor - used when processing the contents of a block.
* Contains a pointer into the data being processed and a count
* of bytes remaining in the block.
*/
struct block_cursor {
u_char *data;
size_t data_remaining;
bpf_u_int32 block_type;
};
typedef enum {
PASS_THROUGH,
SCALE_UP_DEC,
SCALE_DOWN_DEC,
SCALE_UP_BIN,
SCALE_DOWN_BIN
} tstamp_scale_type_t;
/*
* Per-interface information.
*/
struct pcap_ng_if {
uint64_t tsresol; /* time stamp resolution */
tstamp_scale_type_t scale_type; /* how to scale */
uint64_t scale_factor; /* time stamp scale factor for power-of-10 tsresol */
uint64_t tsoffset; /* time stamp offset */
};
/*
* Per-pcap_t private data.
*
* max_blocksize is the maximum size of a block that we'll accept. We
* reject blocks bigger than this, so we don't consume too much memory
* with a truly huge block. It can change as we see IDBs with different
* link-layer header types. (Currently, we don't support IDBs with
* different link-layer header types, but we will support it in the
* future, when we offer file-reading APIs that support it.)
*
* XXX - that's an issue on ILP32 platforms, where the maximum block
* size of 2^31-1 would eat all but one byte of the entire address space.
* It's less of an issue on ILP64/LLP64 platforms, but the actual size
* of the address space may be limited by 1) the number of *significant*
* address bits (currently, x86-64 only supports 48 bits of address), 2)
* any limitations imposed by the operating system; 3) any limitations
* imposed by the amount of available backing store for anonymous pages,
* so we impose a limit regardless of the size of a pointer.
*/
struct pcap_ng_sf {
uint64_t user_tsresol; /* time stamp resolution requested by the user */
u_int max_blocksize; /* don't grow buffer size past this */
bpf_u_int32 ifcount; /* number of interfaces seen in this capture */
bpf_u_int32 ifaces_size; /* size of array below */
struct pcap_ng_if *ifaces; /* array of interface information */
};
/*
* The maximum block size we start with; we use an arbitrary value of
* 16 MiB.
*/
#define INITIAL_MAX_BLOCKSIZE (16*1024*1024)
/*
* Maximum block size for a given maximum snapshot length; we define it
* as the size of an EPB with a max_snaplen-sized packet and 128KB of
* options.
*/
#define MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen) \
(sizeof (struct block_header) + \
sizeof (struct enhanced_packet_block) + \
(max_snaplen) + 131072 + \
sizeof (struct block_trailer))
static void pcap_ng_cleanup(pcap_t *p);
static int pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr,
u_char **data);
static int
read_bytes(FILE *fp, void *buf, size_t bytes_to_read, int fail_on_eof,
char *errbuf)
{
size_t amt_read;
amt_read = fread(buf, 1, bytes_to_read, fp);
if (amt_read != bytes_to_read) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
} else {
if (amt_read == 0 && !fail_on_eof)
return (0); /* EOF */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"truncated pcapng dump file; tried to read %" PRIsize " bytes, only got %" PRIsize,
bytes_to_read, amt_read);
}
return (-1);
}
return (1);
}
static int
read_block(FILE *fp, pcap_t *p, struct block_cursor *cursor, char *errbuf)
{
struct pcap_ng_sf *ps;
int status;
struct block_header bhdr;
struct block_trailer *btrlr;
u_char *bdata;
size_t data_remaining;
ps = p->priv;
status = read_bytes(fp, &bhdr, sizeof(bhdr), 0, errbuf);
if (status <= 0)
return (status); /* error or EOF */
if (p->swapped) {
bhdr.block_type = SWAPLONG(bhdr.block_type);
bhdr.total_length = SWAPLONG(bhdr.total_length);
}
/*
* Is this block "too small" - i.e., is it shorter than a block
* header plus a block trailer?
*/
if (bhdr.total_length < sizeof(struct block_header) +
sizeof(struct block_trailer)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block in pcapng dump file has a length of %u < %" PRIsize,
bhdr.total_length,
sizeof(struct block_header) + sizeof(struct block_trailer));
return (-1);
}
/*
* Is the block total length a multiple of 4?
*/
if ((bhdr.total_length % 4) != 0) {
/*
* No. Report that as an error.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block in pcapng dump file has a length of %u that is not a multiple of 4" PRIsize,
bhdr.total_length);
return (-1);
}
/*
* Is the buffer big enough?
*/
if (p->bufsize < bhdr.total_length) {
/*
* No - make it big enough, unless it's too big, in
* which case we fail.
*/
void *bigger_buffer;
if (bhdr.total_length > ps->max_blocksize) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "pcapng block size %u > maximum %u", bhdr.total_length,
ps->max_blocksize);
return (-1);
}
bigger_buffer = realloc(p->buffer, bhdr.total_length);
if (bigger_buffer == NULL) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
return (-1);
}
p->buffer = bigger_buffer;
}
/*
* Copy the stuff we've read to the buffer, and read the rest
* of the block.
*/
memcpy(p->buffer, &bhdr, sizeof(bhdr));
bdata = (u_char *)p->buffer + sizeof(bhdr);
data_remaining = bhdr.total_length - sizeof(bhdr);
if (read_bytes(fp, bdata, data_remaining, 1, errbuf) == -1)
return (-1);
/*
* Get the block size from the trailer.
*/
btrlr = (struct block_trailer *)(bdata + data_remaining - sizeof (struct block_trailer));
if (p->swapped)
btrlr->total_length = SWAPLONG(btrlr->total_length);
/*
* Is the total length from the trailer the same as the total
* length from the header?
*/
if (bhdr.total_length != btrlr->total_length) {
/*
* No.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block total length in header and trailer don't match");
return (-1);
}
/*
* Initialize the cursor.
*/
cursor->data = bdata;
cursor->data_remaining = data_remaining - sizeof(struct block_trailer);
cursor->block_type = bhdr.block_type;
return (1);
}
static void *
get_from_block_data(struct block_cursor *cursor, size_t chunk_size,
char *errbuf)
{
void *data;
/*
* Make sure we have the specified amount of data remaining in
* the block data.
*/
if (cursor->data_remaining < chunk_size) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"block of type %u in pcapng dump file is too short",
cursor->block_type);
return (NULL);
}
/*
* Return the current pointer, and skip past the chunk.
*/
data = cursor->data;
cursor->data += chunk_size;
cursor->data_remaining -= chunk_size;
return (data);
}
static struct option_header *
get_opthdr_from_block_data(pcap_t *p, struct block_cursor *cursor, char *errbuf)
{
struct option_header *opthdr;
opthdr = get_from_block_data(cursor, sizeof(*opthdr), errbuf);
if (opthdr == NULL) {
/*
* Option header is cut short.
*/
return (NULL);
}
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
opthdr->option_code = SWAPSHORT(opthdr->option_code);
opthdr->option_length = SWAPSHORT(opthdr->option_length);
}
return (opthdr);
}
static void *
get_optvalue_from_block_data(struct block_cursor *cursor,
struct option_header *opthdr, char *errbuf)
{
size_t padded_option_len;
void *optvalue;
/* Pad option length to 4-byte boundary */
padded_option_len = opthdr->option_length;
padded_option_len = ((padded_option_len + 3)/4)*4;
optvalue = get_from_block_data(cursor, padded_option_len, errbuf);
if (optvalue == NULL) {
/*
* Option value is cut short.
*/
return (NULL);
}
return (optvalue);
}
static int
process_idb_options(pcap_t *p, struct block_cursor *cursor, uint64_t *tsresol,
uint64_t *tsoffset, int *is_binary, char *errbuf)
{
struct option_header *opthdr;
void *optvalue;
int saw_tsresol, saw_tsoffset;
uint8_t tsresol_opt;
u_int i;
saw_tsresol = 0;
saw_tsoffset = 0;
while (cursor->data_remaining != 0) {
/*
* Get the option header.
*/
opthdr = get_opthdr_from_block_data(p, cursor, errbuf);
if (opthdr == NULL) {
/*
* Option header is cut short.
*/
return (-1);
}
/*
* Get option value.
*/
optvalue = get_optvalue_from_block_data(cursor, opthdr,
errbuf);
if (optvalue == NULL) {
/*
* Option value is cut short.
*/
return (-1);
}
switch (opthdr->option_code) {
case OPT_ENDOFOPT:
if (opthdr->option_length != 0) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has opt_endofopt option with length %u != 0",
opthdr->option_length);
return (-1);
}
goto done;
case IF_TSRESOL:
if (opthdr->option_length != 1) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has if_tsresol option with length %u != 1",
opthdr->option_length);
return (-1);
}
if (saw_tsresol) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has more than one if_tsresol option");
return (-1);
}
saw_tsresol = 1;
memcpy(&tsresol_opt, optvalue, sizeof(tsresol_opt));
if (tsresol_opt & 0x80) {
/*
* Resolution is negative power of 2.
*/
uint8_t tsresol_shift = (tsresol_opt & 0x7F);
if (tsresol_shift > 63) {
/*
* Resolution is too high; 2^-{res}
* won't fit in a 64-bit value.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block if_tsresol option resolution 2^-%u is too high",
tsresol_shift);
return (-1);
}
*is_binary = 1;
*tsresol = ((uint64_t)1) << tsresol_shift;
} else {
/*
* Resolution is negative power of 10.
*/
if (tsresol_opt > 19) {
/*
* Resolution is too high; 2^-{res}
* won't fit in a 64-bit value (the
* largest power of 10 that fits
* in a 64-bit value is 10^19, as
* the largest 64-bit unsigned
* value is ~1.8*10^19).
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block if_tsresol option resolution 10^-%u is too high",
tsresol_opt);
return (-1);
}
*is_binary = 0;
*tsresol = 1;
for (i = 0; i < tsresol_opt; i++)
*tsresol *= 10;
}
break;
case IF_TSOFFSET:
if (opthdr->option_length != 8) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has if_tsoffset option with length %u != 8",
opthdr->option_length);
return (-1);
}
if (saw_tsoffset) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Interface Description Block has more than one if_tsoffset option");
return (-1);
}
saw_tsoffset = 1;
memcpy(tsoffset, optvalue, sizeof(*tsoffset));
if (p->swapped)
*tsoffset = SWAPLL(*tsoffset);
break;
default:
break;
}
}
done:
return (0);
}
static int
add_interface(pcap_t *p, struct block_cursor *cursor, char *errbuf)
{
struct pcap_ng_sf *ps;
uint64_t tsresol;
uint64_t tsoffset;
int is_binary;
ps = p->priv;
/*
* Count this interface.
*/
ps->ifcount++;
/*
* Grow the array of per-interface information as necessary.
*/
if (ps->ifcount > ps->ifaces_size) {
/*
* We need to grow the array.
*/
bpf_u_int32 new_ifaces_size;
struct pcap_ng_if *new_ifaces;
if (ps->ifaces_size == 0) {
/*
* It's currently empty.
*
* (The Clang static analyzer doesn't do enough,
* err, umm, dataflow *analysis* to realize that
* ps->ifaces_size == 0 if ps->ifaces == NULL,
* and so complains about a possible zero argument
* to realloc(), so we check for the former
* condition to shut it up.
*
* However, it doesn't complain that one of the
* multiplications below could overflow, which is
* a real, albeit extremely unlikely, problem (you'd
* need a pcapng file with tens of millions of
* interfaces).)
*/
new_ifaces_size = 1;
new_ifaces = malloc(sizeof (struct pcap_ng_if));
} else {
/*
* It's not currently empty; double its size.
* (Perhaps overkill once we have a lot of interfaces.)
*
* Check for overflow if we double it.
*/
if (ps->ifaces_size * 2 < ps->ifaces_size) {
/*
* The maximum number of interfaces before
* ps->ifaces_size overflows is the largest
* possible 32-bit power of 2, as we do
* size doubling.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"more than %u interfaces in the file",
0x80000000U);
return (0);
}
/*
* ps->ifaces_size * 2 doesn't overflow, so it's
* safe to multiply.
*/
new_ifaces_size = ps->ifaces_size * 2;
/*
* Now make sure that's not so big that it overflows
* if we multiply by sizeof (struct pcap_ng_if).
*
* That can happen on 32-bit platforms, with a 32-bit
* size_t; it shouldn't happen on 64-bit platforms,
* with a 64-bit size_t, as new_ifaces_size is
* 32 bits.
*/
if (new_ifaces_size * sizeof (struct pcap_ng_if) < new_ifaces_size) {
/*
* As this fails only with 32-bit size_t,
* the multiplication was 32x32->32, and
* the largest 32-bit value that can safely
* be multiplied by sizeof (struct pcap_ng_if)
* without overflow is the largest 32-bit
* (unsigned) value divided by
* sizeof (struct pcap_ng_if).
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"more than %u interfaces in the file",
0xFFFFFFFFU / ((u_int)sizeof (struct pcap_ng_if)));
return (0);
}
new_ifaces = realloc(ps->ifaces, new_ifaces_size * sizeof (struct pcap_ng_if));
}
if (new_ifaces == NULL) {
/*
* We ran out of memory.
* Give up.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"out of memory for per-interface information (%u interfaces)",
ps->ifcount);
return (0);
}
ps->ifaces_size = new_ifaces_size;
ps->ifaces = new_ifaces;
}
/*
* Set the default time stamp resolution and offset.
*/
tsresol = 1000000; /* microsecond resolution */
is_binary = 0; /* which is a power of 10 */
tsoffset = 0; /* absolute timestamps */
/*
* Now look for various time stamp options, so we know
* how to interpret the time stamps for this interface.
*/
if (process_idb_options(p, cursor, &tsresol, &tsoffset, &is_binary,
errbuf) == -1)
return (0);
ps->ifaces[ps->ifcount - 1].tsresol = tsresol;
ps->ifaces[ps->ifcount - 1].tsoffset = tsoffset;
/*
* Determine whether we're scaling up or down or not
* at all for this interface.
*/
if (tsresol == ps->user_tsresol) {
/*
* The resolution is the resolution the user wants,
* so we don't have to do scaling.
*/
ps->ifaces[ps->ifcount - 1].scale_type = PASS_THROUGH;
} else if (tsresol > ps->user_tsresol) {
/*
* The resolution is greater than what the user wants,
* so we have to scale the timestamps down.
*/
if (is_binary)
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_BIN;
else {
/*
* Calculate the scale factor.
*/
ps->ifaces[ps->ifcount - 1].scale_factor = tsresol/ps->user_tsresol;
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_DOWN_DEC;
}
} else {
/*
* The resolution is less than what the user wants,
* so we have to scale the timestamps up.
*/
if (is_binary)
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_BIN;
else {
/*
* Calculate the scale factor.
*/
ps->ifaces[ps->ifcount - 1].scale_factor = ps->user_tsresol/tsresol;
ps->ifaces[ps->ifcount - 1].scale_type = SCALE_UP_DEC;
}
}
return (1);
}
/*
* Check whether this is a pcapng savefile and, if it is, extract the
* relevant information from the header.
*/
pcap_t *
pcap_ng_check_header(const uint8_t *magic, FILE *fp, u_int precision,
char *errbuf, int *err)
{
bpf_u_int32 magic_int;
size_t amt_read;
bpf_u_int32 total_length;
bpf_u_int32 byte_order_magic;
struct block_header *bhdrp;
struct section_header_block *shbp;
pcap_t *p;
int swapped = 0;
struct pcap_ng_sf *ps;
int status;
struct block_cursor cursor;
struct interface_description_block *idbp;
/*
* Assume no read errors.
*/
*err = 0;
/*
* Check whether the first 4 bytes of the file are the block
* type for a pcapng savefile.
*/
memcpy(&magic_int, magic, sizeof(magic_int));
if (magic_int != BT_SHB) {
/*
* XXX - check whether this looks like what the block
* type would be after being munged by mapping between
* UN*X and DOS/Windows text file format and, if it
* does, look for the byte-order magic number in
* the appropriate place and, if we find it, report
* this as possibly being a pcapng file transferred
* between UN*X and Windows in text file format?
*/
return (NULL); /* nope */
}
/*
* OK, they are. However, that's just \n\r\r\n, so it could,
* conceivably, be an ordinary text file.
*
* It could not, however, conceivably be any other type of
* capture file, so we can read the rest of the putative
* Section Header Block; put the block type in the common
* header, read the rest of the common header and the
* fixed-length portion of the SHB, and look for the byte-order
* magic value.
*/
amt_read = fread(&total_length, 1, sizeof(total_length), fp);
if (amt_read < sizeof(total_length)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
amt_read = fread(&byte_order_magic, 1, sizeof(byte_order_magic), fp);
if (amt_read < sizeof(byte_order_magic)) {
if (ferror(fp)) {
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "error reading dump file");
*err = 1;
return (NULL); /* fail */
}
/*
* Possibly a weird short text file, so just say
* "not pcapng".
*/
return (NULL);
}
if (byte_order_magic != BYTE_ORDER_MAGIC) {
byte_order_magic = SWAPLONG(byte_order_magic);
if (byte_order_magic != BYTE_ORDER_MAGIC) {
/*
* Not a pcapng file.
*/
return (NULL);
}
swapped = 1;
total_length = SWAPLONG(total_length);
}
/*
* Check the sanity of the total length.
*/
if (total_length < sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer) ||
(total_length > BT_SHB_INSANE_MAX)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"Section Header Block in pcapng dump file has invalid length %" PRIsize " < _%lu_ < %lu (BT_SHB_INSANE_MAX)",
sizeof(*bhdrp) + sizeof(*shbp) + sizeof(struct block_trailer),
total_length,
BT_SHB_INSANE_MAX);
*err = 1;
return (NULL);
}
/*
* OK, this is a good pcapng file.
* Allocate a pcap_t for it.
*/
p = pcap_open_offline_common(errbuf, sizeof (struct pcap_ng_sf));
if (p == NULL) {
/* Allocation failed. */
*err = 1;
return (NULL);
}
p->swapped = swapped;
ps = p->priv;
/*
* What precision does the user want?
*/
switch (precision) {
case PCAP_TSTAMP_PRECISION_MICRO:
ps->user_tsresol = 1000000;
break;
case PCAP_TSTAMP_PRECISION_NANO:
ps->user_tsresol = 1000000000;
break;
default:
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unknown time stamp resolution %u", precision);
free(p);
*err = 1;
return (NULL);
}
p->opt.tstamp_precision = precision;
/*
* Allocate a buffer into which to read blocks. We default to
* the maximum of:
*
* the total length of the SHB for which we read the header;
*
* 2K, which should be more than large enough for an Enhanced
* Packet Block containing a full-size Ethernet frame, and
* leaving room for some options.
*
* If we find a bigger block, we reallocate the buffer, up to
* the maximum size. We start out with a maximum size of
* INITIAL_MAX_BLOCKSIZE; if we see any link-layer header types
* with a maximum snapshot that results in a larger maximum
* block length, we boost the maximum.
*/
p->bufsize = 2048;
if (p->bufsize < total_length)
p->bufsize = total_length;
p->buffer = malloc(p->bufsize);
if (p->buffer == NULL) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "out of memory");
free(p);
*err = 1;
return (NULL);
}
ps->max_blocksize = INITIAL_MAX_BLOCKSIZE;
/*
* Copy the stuff we've read to the buffer, and read the rest
* of the SHB.
*/
bhdrp = (struct block_header *)p->buffer;
shbp = (struct section_header_block *)((u_char *)p->buffer + sizeof(struct block_header));
bhdrp->block_type = magic_int;
bhdrp->total_length = total_length;
shbp->byte_order_magic = byte_order_magic;
if (read_bytes(fp,
(u_char *)p->buffer + (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
total_length - (sizeof(magic_int) + sizeof(total_length) + sizeof(byte_order_magic)),
1, errbuf) == -1)
goto fail;
if (p->swapped) {
/*
* Byte-swap the fields we've read.
*/
shbp->major_version = SWAPSHORT(shbp->major_version);
shbp->minor_version = SWAPSHORT(shbp->minor_version);
/*
* XXX - we don't care about the section length.
*/
}
/* currently only SHB version 1.0 is supported */
if (! (shbp->major_version == PCAP_NG_VERSION_MAJOR &&
shbp->minor_version == PCAP_NG_VERSION_MINOR)) {
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"unsupported pcapng savefile version %u.%u",
shbp->major_version, shbp->minor_version);
goto fail;
}
p->version_major = shbp->major_version;
p->version_minor = shbp->minor_version;
/*
* Save the time stamp resolution the user requested.
*/
p->opt.tstamp_precision = precision;
/*
* Now start looking for an Interface Description Block.
*/
for (;;) {
/*
* Read the next block.
*/
status = read_block(fp, p, &cursor, errbuf);
if (status == 0) {
/* EOF - no IDB in this file */
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has no Interface Description Blocks");
goto fail;
}
if (status == -1)
goto fail; /* error */
switch (cursor.block_type) {
case BT_IDB:
/*
* Get a pointer to the fixed-length portion of the
* IDB.
*/
idbp = get_from_block_data(&cursor, sizeof(*idbp),
errbuf);
if (idbp == NULL)
goto fail; /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
idbp->linktype = SWAPSHORT(idbp->linktype);
idbp->snaplen = SWAPLONG(idbp->snaplen);
}
/*
* Try to add this interface.
*/
if (!add_interface(p, &cursor, errbuf))
goto fail;
goto done;
case BT_EPB:
case BT_SPB:
case BT_PB:
/*
* Saw a packet before we saw any IDBs. That's
* not valid, as we don't know what link-layer
* encapsulation the packet has.
*/
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
"the capture file has a packet block before any Interface Description Blocks");
goto fail;
default:
/*
* Just ignore it.
*/
break;
}
}
done:
p->tzoff = 0; /* XXX - not used in pcap */
p->linktype = linktype_to_dlt(idbp->linktype);
p->snapshot = pcap_adjust_snapshot(p->linktype, idbp->snaplen);
p->linktype_ext = 0;
/*
* If the maximum block size for a packet with the maximum
* snapshot length for this DLT_ is bigger than the current
* maximum block size, increase the maximum.
*/
if (MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype)) > ps->max_blocksize)
ps->max_blocksize = MAX_BLOCKSIZE_FOR_SNAPLEN(max_snaplen_for_dlt(p->linktype));
p->next_packet_op = pcap_ng_next_packet;
p->cleanup_op = pcap_ng_cleanup;
return (p);
fail:
free(ps->ifaces);
free(p->buffer);
free(p);
*err = 1;
return (NULL);
}
static void
pcap_ng_cleanup(pcap_t *p)
{
struct pcap_ng_sf *ps = p->priv;
free(ps->ifaces);
sf_cleanup(p);
}
/*
* Read and return the next packet from the savefile. Return the header
* in hdr and a pointer to the contents in data. Return 0 on success, 1
* if there were no more packets, and -1 on an error.
*/
static int
pcap_ng_next_packet(pcap_t *p, struct pcap_pkthdr *hdr, u_char **data)
{
struct pcap_ng_sf *ps = p->priv;
struct block_cursor cursor;
int status;
struct enhanced_packet_block *epbp;
struct simple_packet_block *spbp;
struct packet_block *pbp;
bpf_u_int32 interface_id = 0xFFFFFFFF;
struct interface_description_block *idbp;
struct section_header_block *shbp;
FILE *fp = p->rfile;
uint64_t t, sec, frac;
/*
* Look for an Enhanced Packet Block, a Simple Packet Block,
* or a Packet Block.
*/
for (;;) {
/*
* Read the block type and length; those are common
* to all blocks.
*/
status = read_block(fp, p, &cursor, p->errbuf);
if (status == 0)
return (1); /* EOF */
if (status == -1)
return (-1); /* error */
switch (cursor.block_type) {
case BT_EPB:
/*
* Get a pointer to the fixed-length portion of the
* EPB.
*/
epbp = get_from_block_data(&cursor, sizeof(*epbp),
p->errbuf);
if (epbp == NULL)
return (-1); /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
/* these were written in opposite byte order */
interface_id = SWAPLONG(epbp->interface_id);
hdr->caplen = SWAPLONG(epbp->caplen);
hdr->len = SWAPLONG(epbp->len);
t = ((uint64_t)SWAPLONG(epbp->timestamp_high)) << 32 |
SWAPLONG(epbp->timestamp_low);
} else {
interface_id = epbp->interface_id;
hdr->caplen = epbp->caplen;
hdr->len = epbp->len;
t = ((uint64_t)epbp->timestamp_high) << 32 |
epbp->timestamp_low;
}
goto found;
case BT_SPB:
/*
* Get a pointer to the fixed-length portion of the
* SPB.
*/
spbp = get_from_block_data(&cursor, sizeof(*spbp),
p->errbuf);
if (spbp == NULL)
return (-1); /* error */
/*
* SPB packets are assumed to have arrived on
* the first interface.
*/
interface_id = 0;
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
/* these were written in opposite byte order */
hdr->len = SWAPLONG(spbp->len);
} else
hdr->len = spbp->len;
/*
* The SPB doesn't give the captured length;
* it's the minimum of the snapshot length
* and the packet length.
*/
hdr->caplen = hdr->len;
if (hdr->caplen > (bpf_u_int32)p->snapshot)
hdr->caplen = p->snapshot;
t = 0; /* no time stamps */
goto found;
case BT_PB:
/*
* Get a pointer to the fixed-length portion of the
* PB.
*/
pbp = get_from_block_data(&cursor, sizeof(*pbp),
p->errbuf);
if (pbp == NULL)
return (-1); /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
/* these were written in opposite byte order */
interface_id = SWAPSHORT(pbp->interface_id);
hdr->caplen = SWAPLONG(pbp->caplen);
hdr->len = SWAPLONG(pbp->len);
t = ((uint64_t)SWAPLONG(pbp->timestamp_high)) << 32 |
SWAPLONG(pbp->timestamp_low);
} else {
interface_id = pbp->interface_id;
hdr->caplen = pbp->caplen;
hdr->len = pbp->len;
t = ((uint64_t)pbp->timestamp_high) << 32 |
pbp->timestamp_low;
}
goto found;
case BT_IDB:
/*
* Interface Description Block. Get a pointer
* to its fixed-length portion.
*/
idbp = get_from_block_data(&cursor, sizeof(*idbp),
p->errbuf);
if (idbp == NULL)
return (-1); /* error */
/*
* Byte-swap it if necessary.
*/
if (p->swapped) {
idbp->linktype = SWAPSHORT(idbp->linktype);
idbp->snaplen = SWAPLONG(idbp->snaplen);
}
/*
* If the link-layer type or snapshot length
* differ from the ones for the first IDB we
* saw, quit.
*
* XXX - just discard packets from those
* interfaces?
*/
if (p->linktype != idbp->linktype) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"an interface has a type %u different from the type of the first interface",
idbp->linktype);
return (-1);
}
/*
* Check against the *adjusted* value of this IDB's
* snapshot length.
*/
if ((bpf_u_int32)p->snapshot !=
pcap_adjust_snapshot(p->linktype, idbp->snaplen)) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"an interface has a snapshot length %u different from the type of the first interface",
idbp->snaplen);
return (-1);
}
/*
* Try to add this interface.
*/
if (!add_interface(p, &cursor, p->errbuf))
return (-1);
break;
case BT_SHB:
/*
* Section Header Block. Get a pointer
* to its fixed-length portion.
*/
shbp = get_from_block_data(&cursor, sizeof(*shbp),
p->errbuf);
if (shbp == NULL)
return (-1); /* error */
/*
* Assume the byte order of this section is
* the same as that of the previous section.
* We'll check for that later.
*/
if (p->swapped) {
shbp->byte_order_magic =
SWAPLONG(shbp->byte_order_magic);
shbp->major_version =
SWAPSHORT(shbp->major_version);
}
/*
* Make sure the byte order doesn't change;
* pcap_is_swapped() shouldn't change its
* return value in the middle of reading a capture.
*/
switch (shbp->byte_order_magic) {
case BYTE_ORDER_MAGIC:
/*
* OK.
*/
break;
case SWAPLONG(BYTE_ORDER_MAGIC):
/*
* Byte order changes.
*/
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"the file has sections with different byte orders");
return (-1);
default:
/*
* Not a valid SHB.
*/
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"the file has a section with a bad byte order magic field");
return (-1);
}
/*
* Make sure the major version is the version
* we handle.
*/
if (shbp->major_version != PCAP_NG_VERSION_MAJOR) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"unknown pcapng savefile major version number %u",
shbp->major_version);
return (-1);
}
/*
* Reset the interface count; this section should
* have its own set of IDBs. If any of them
* don't have the same interface type, snapshot
* length, or resolution as the first interface
* we saw, we'll fail. (And if we don't see
* any IDBs, we'll fail when we see a packet
* block.)
*/
ps->ifcount = 0;
break;
default:
/*
* Not a packet block, IDB, or SHB; ignore it.
*/
break;
}
}
found:
/*
* Is the interface ID an interface we know?
*/
if (interface_id >= ps->ifcount) {
/*
* Yes. Fail.
*/
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"a packet arrived on interface %u, but there's no Interface Description Block for that interface",
interface_id);
return (-1);
}
if (hdr->caplen > (bpf_u_int32)p->snapshot) {
pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
"invalid packet capture length %u, bigger than "
"snaplen of %d", hdr->caplen, p->snapshot);
return (-1);
}
/*
* Convert the time stamp to seconds and fractions of a second,
* with the fractions being in units of the file-supplied resolution.
*/
sec = t / ps->ifaces[interface_id].tsresol + ps->ifaces[interface_id].tsoffset;
frac = t % ps->ifaces[interface_id].tsresol;
/*
* Convert the fractions from units of the file-supplied resolution
* to units of the user-requested resolution.
*/
switch (ps->ifaces[interface_id].scale_type) {
case PASS_THROUGH:
/*
* The interface resolution is what the user wants,
* so we're done.
*/
break;
case SCALE_UP_DEC:
/*
* The interface resolution is less than what the user
* wants; scale the fractional part up to the units of
* the resolution the user requested by multiplying by
* the quotient of the user-requested resolution and the
* file-supplied resolution.
*
* Those resolutions are both powers of 10, and the user-
* requested resolution is greater than the file-supplied
* resolution, so the quotient in question is an integer.
* We've calculated that quotient already, so we just
* multiply by it.
*/
frac *= ps->ifaces[interface_id].scale_factor;
break;
case SCALE_UP_BIN:
/*
* The interface resolution is less than what the user
* wants; scale the fractional part up to the units of
* the resolution the user requested by multiplying by
* the quotient of the user-requested resolution and the
* file-supplied resolution.
*
* The file-supplied resolution is a power of 2, so the
* quotient is not an integer, so, in order to do this
* entirely with integer arithmetic, we multiply by the
* user-requested resolution and divide by the file-
* supplied resolution.
*
* XXX - Is there something clever we could do here,
* given that we know that the file-supplied resolution
* is a power of 2? Doing a multiplication followed by
* a division runs the risk of overflowing, and involves
* two non-simple arithmetic operations.
*/
frac *= ps->user_tsresol;
frac /= ps->ifaces[interface_id].tsresol;
break;
case SCALE_DOWN_DEC:
/*
* The interface resolution is greater than what the user
* wants; scale the fractional part up to the units of
* the resolution the user requested by multiplying by
* the quotient of the user-requested resolution and the
* file-supplied resolution.
*
* Those resolutions are both powers of 10, and the user-
* requested resolution is less than the file-supplied
* resolution, so the quotient in question isn't an
* integer, but its reciprocal is, and we can just divide
* by the reciprocal of the quotient. We've calculated
* the reciprocal of that quotient already, so we must
* divide by it.
*/
frac /= ps->ifaces[interface_id].scale_factor;
break;
case SCALE_DOWN_BIN:
/*
* The interface resolution is greater than what the user
* wants; convert the fractional part to units of the
* resolution the user requested by multiplying by the
* quotient of the user-requested resolution and the
* file-supplied resolution. We do that by multiplying
* by the user-requested resolution and dividing by the
* file-supplied resolution, as the quotient might not
* fit in an integer.
*
* The file-supplied resolution is a power of 2, so the
* quotient is not an integer, and neither is its
* reciprocal, so, in order to do this entirely with
* integer arithmetic, we multiply by the user-requested
* resolution and divide by the file-supplied resolution.
*
* XXX - Is there something clever we could do here,
* given that we know that the file-supplied resolution
* is a power of 2? Doing a multiplication followed by
* a division runs the risk of overflowing, and involves
* two non-simple arithmetic operations.
*/
frac *= ps->user_tsresol;
frac /= ps->ifaces[interface_id].tsresol;
break;
}
#ifdef _WIN32
/*
* tv_sec and tv_used in the Windows struct timeval are both
* longs.
*/
hdr->ts.tv_sec = (long)sec;
hdr->ts.tv_usec = (long)frac;
#else
/*
* tv_sec in the UN*X struct timeval is a time_t; tv_usec is
* suseconds_t in UN*Xes that work the way the current Single
* UNIX Standard specify - but not all older UN*Xes necessarily
* support that type, so just cast to int.
*/
hdr->ts.tv_sec = (time_t)sec;
hdr->ts.tv_usec = (int)frac;
#endif
/*
* Get a pointer to the packet data.
*/
*data = get_from_block_data(&cursor, hdr->caplen, p->errbuf);
if (*data == NULL)
return (-1);
if (p->swapped)
swap_pseudo_headers(p->linktype, hdr, *data);
return (0);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_1027_0 |
crossvul-cpp_data_good_5845_6 | /* net/atm/common.c - ATM sockets (common part for PVC and SVC) */
/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */
#define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__
#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/net.h> /* struct socket, struct proto_ops */
#include <linux/atm.h> /* ATM stuff */
#include <linux/atmdev.h>
#include <linux/socket.h> /* SOL_SOCKET */
#include <linux/errno.h> /* error codes */
#include <linux/capability.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/time.h> /* struct timeval */
#include <linux/skbuff.h>
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <net/sock.h> /* struct sock */
#include <linux/uaccess.h>
#include <linux/poll.h>
#include <linux/atomic.h>
#include "resources.h" /* atm_find_dev */
#include "common.h" /* prototypes */
#include "protocols.h" /* atm_init_<transport> */
#include "addr.h" /* address registry */
#include "signaling.h" /* for WAITING and sigd_attach */
struct hlist_head vcc_hash[VCC_HTABLE_SIZE];
EXPORT_SYMBOL(vcc_hash);
DEFINE_RWLOCK(vcc_sklist_lock);
EXPORT_SYMBOL(vcc_sklist_lock);
static ATOMIC_NOTIFIER_HEAD(atm_dev_notify_chain);
static void __vcc_insert_socket(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
struct hlist_head *head = &vcc_hash[vcc->vci & (VCC_HTABLE_SIZE - 1)];
sk->sk_hash = vcc->vci & (VCC_HTABLE_SIZE - 1);
sk_add_node(sk, head);
}
void vcc_insert_socket(struct sock *sk)
{
write_lock_irq(&vcc_sklist_lock);
__vcc_insert_socket(sk);
write_unlock_irq(&vcc_sklist_lock);
}
EXPORT_SYMBOL(vcc_insert_socket);
static void vcc_remove_socket(struct sock *sk)
{
write_lock_irq(&vcc_sklist_lock);
sk_del_node_init(sk);
write_unlock_irq(&vcc_sklist_lock);
}
static struct sk_buff *alloc_tx(struct atm_vcc *vcc, unsigned int size)
{
struct sk_buff *skb;
struct sock *sk = sk_atm(vcc);
if (sk_wmem_alloc_get(sk) && !atm_may_send(vcc, size)) {
pr_debug("Sorry: wmem_alloc = %d, size = %d, sndbuf = %d\n",
sk_wmem_alloc_get(sk), size, sk->sk_sndbuf);
return NULL;
}
while (!(skb = alloc_skb(size, GFP_KERNEL)))
schedule();
pr_debug("%d += %d\n", sk_wmem_alloc_get(sk), skb->truesize);
atomic_add(skb->truesize, &sk->sk_wmem_alloc);
return skb;
}
static void vcc_sock_destruct(struct sock *sk)
{
if (atomic_read(&sk->sk_rmem_alloc))
printk(KERN_DEBUG "%s: rmem leakage (%d bytes) detected.\n",
__func__, atomic_read(&sk->sk_rmem_alloc));
if (atomic_read(&sk->sk_wmem_alloc))
printk(KERN_DEBUG "%s: wmem leakage (%d bytes) detected.\n",
__func__, atomic_read(&sk->sk_wmem_alloc));
}
static void vcc_def_wakeup(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up(&wq->wait);
rcu_read_unlock();
}
static inline int vcc_writable(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
return (vcc->qos.txtp.max_sdu +
atomic_read(&sk->sk_wmem_alloc)) <= sk->sk_sndbuf;
}
static void vcc_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
if (vcc_writable(sk)) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible(&wq->wait);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
static void vcc_release_cb(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
if (vcc->release_cb)
vcc->release_cb(vcc);
}
static struct proto vcc_proto = {
.name = "VCC",
.owner = THIS_MODULE,
.obj_size = sizeof(struct atm_vcc),
.release_cb = vcc_release_cb,
};
int vcc_create(struct net *net, struct socket *sock, int protocol, int family)
{
struct sock *sk;
struct atm_vcc *vcc;
sock->sk = NULL;
if (sock->type == SOCK_STREAM)
return -EINVAL;
sk = sk_alloc(net, family, GFP_KERNEL, &vcc_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sk->sk_state_change = vcc_def_wakeup;
sk->sk_write_space = vcc_write_space;
vcc = atm_sk(sk);
vcc->dev = NULL;
memset(&vcc->local, 0, sizeof(struct sockaddr_atmsvc));
memset(&vcc->remote, 0, sizeof(struct sockaddr_atmsvc));
vcc->qos.txtp.max_sdu = 1 << 16; /* for meta VCs */
atomic_set(&sk->sk_wmem_alloc, 1);
atomic_set(&sk->sk_rmem_alloc, 0);
vcc->push = NULL;
vcc->pop = NULL;
vcc->owner = NULL;
vcc->push_oam = NULL;
vcc->release_cb = NULL;
vcc->vpi = vcc->vci = 0; /* no VCI/VPI yet */
vcc->atm_options = vcc->aal_options = 0;
sk->sk_destruct = vcc_sock_destruct;
return 0;
}
static void vcc_destroy_socket(struct sock *sk)
{
struct atm_vcc *vcc = atm_sk(sk);
struct sk_buff *skb;
set_bit(ATM_VF_CLOSE, &vcc->flags);
clear_bit(ATM_VF_READY, &vcc->flags);
if (vcc->dev) {
if (vcc->dev->ops->close)
vcc->dev->ops->close(vcc);
if (vcc->push)
vcc->push(vcc, NULL); /* atmarpd has no push */
module_put(vcc->owner);
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
atm_return(vcc, skb->truesize);
kfree_skb(skb);
}
module_put(vcc->dev->ops->owner);
atm_dev_put(vcc->dev);
}
vcc_remove_socket(sk);
}
int vcc_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (sk) {
lock_sock(sk);
vcc_destroy_socket(sock->sk);
release_sock(sk);
sock_put(sk);
}
return 0;
}
void vcc_release_async(struct atm_vcc *vcc, int reply)
{
struct sock *sk = sk_atm(vcc);
set_bit(ATM_VF_CLOSE, &vcc->flags);
sk->sk_shutdown |= RCV_SHUTDOWN;
sk->sk_err = -reply;
clear_bit(ATM_VF_WAITING, &vcc->flags);
sk->sk_state_change(sk);
}
EXPORT_SYMBOL(vcc_release_async);
void vcc_process_recv_queue(struct atm_vcc *vcc)
{
struct sk_buff_head queue, *rq;
struct sk_buff *skb, *tmp;
unsigned long flags;
__skb_queue_head_init(&queue);
rq = &sk_atm(vcc)->sk_receive_queue;
spin_lock_irqsave(&rq->lock, flags);
skb_queue_splice_init(rq, &queue);
spin_unlock_irqrestore(&rq->lock, flags);
skb_queue_walk_safe(&queue, skb, tmp) {
__skb_unlink(skb, &queue);
vcc->push(vcc, skb);
}
}
EXPORT_SYMBOL(vcc_process_recv_queue);
void atm_dev_signal_change(struct atm_dev *dev, char signal)
{
pr_debug("%s signal=%d dev=%p number=%d dev->signal=%d\n",
__func__, signal, dev, dev->number, dev->signal);
/* atm driver sending invalid signal */
WARN_ON(signal < ATM_PHY_SIG_LOST || signal > ATM_PHY_SIG_FOUND);
if (dev->signal == signal)
return; /* no change */
dev->signal = signal;
atomic_notifier_call_chain(&atm_dev_notify_chain, signal, dev);
}
EXPORT_SYMBOL(atm_dev_signal_change);
void atm_dev_release_vccs(struct atm_dev *dev)
{
int i;
write_lock_irq(&vcc_sklist_lock);
for (i = 0; i < VCC_HTABLE_SIZE; i++) {
struct hlist_head *head = &vcc_hash[i];
struct hlist_node *tmp;
struct sock *s;
struct atm_vcc *vcc;
sk_for_each_safe(s, tmp, head) {
vcc = atm_sk(s);
if (vcc->dev == dev) {
vcc_release_async(vcc, -EPIPE);
sk_del_node_init(s);
}
}
}
write_unlock_irq(&vcc_sklist_lock);
}
EXPORT_SYMBOL(atm_dev_release_vccs);
static int adjust_tp(struct atm_trafprm *tp, unsigned char aal)
{
int max_sdu;
if (!tp->traffic_class)
return 0;
switch (aal) {
case ATM_AAL0:
max_sdu = ATM_CELL_SIZE-1;
break;
case ATM_AAL34:
max_sdu = ATM_MAX_AAL34_PDU;
break;
default:
pr_warning("AAL problems ... (%d)\n", aal);
/* fall through */
case ATM_AAL5:
max_sdu = ATM_MAX_AAL5_PDU;
}
if (!tp->max_sdu)
tp->max_sdu = max_sdu;
else if (tp->max_sdu > max_sdu)
return -EINVAL;
if (!tp->max_cdv)
tp->max_cdv = ATM_MAX_CDV;
return 0;
}
static int check_ci(const struct atm_vcc *vcc, short vpi, int vci)
{
struct hlist_head *head = &vcc_hash[vci & (VCC_HTABLE_SIZE - 1)];
struct sock *s;
struct atm_vcc *walk;
sk_for_each(s, head) {
walk = atm_sk(s);
if (walk->dev != vcc->dev)
continue;
if (test_bit(ATM_VF_ADDR, &walk->flags) && walk->vpi == vpi &&
walk->vci == vci && ((walk->qos.txtp.traffic_class !=
ATM_NONE && vcc->qos.txtp.traffic_class != ATM_NONE) ||
(walk->qos.rxtp.traffic_class != ATM_NONE &&
vcc->qos.rxtp.traffic_class != ATM_NONE)))
return -EADDRINUSE;
}
/* allow VCCs with same VPI/VCI iff they don't collide on
TX/RX (but we may refuse such sharing for other reasons,
e.g. if protocol requires to have both channels) */
return 0;
}
static int find_ci(const struct atm_vcc *vcc, short *vpi, int *vci)
{
static short p; /* poor man's per-device cache */
static int c;
short old_p;
int old_c;
int err;
if (*vpi != ATM_VPI_ANY && *vci != ATM_VCI_ANY) {
err = check_ci(vcc, *vpi, *vci);
return err;
}
/* last scan may have left values out of bounds for current device */
if (*vpi != ATM_VPI_ANY)
p = *vpi;
else if (p >= 1 << vcc->dev->ci_range.vpi_bits)
p = 0;
if (*vci != ATM_VCI_ANY)
c = *vci;
else if (c < ATM_NOT_RSV_VCI || c >= 1 << vcc->dev->ci_range.vci_bits)
c = ATM_NOT_RSV_VCI;
old_p = p;
old_c = c;
do {
if (!check_ci(vcc, p, c)) {
*vpi = p;
*vci = c;
return 0;
}
if (*vci == ATM_VCI_ANY) {
c++;
if (c >= 1 << vcc->dev->ci_range.vci_bits)
c = ATM_NOT_RSV_VCI;
}
if ((c == ATM_NOT_RSV_VCI || *vci != ATM_VCI_ANY) &&
*vpi == ATM_VPI_ANY) {
p++;
if (p >= 1 << vcc->dev->ci_range.vpi_bits)
p = 0;
}
} while (old_p != p || old_c != c);
return -EADDRINUSE;
}
static int __vcc_connect(struct atm_vcc *vcc, struct atm_dev *dev, short vpi,
int vci)
{
struct sock *sk = sk_atm(vcc);
int error;
if ((vpi != ATM_VPI_UNSPEC && vpi != ATM_VPI_ANY &&
vpi >> dev->ci_range.vpi_bits) || (vci != ATM_VCI_UNSPEC &&
vci != ATM_VCI_ANY && vci >> dev->ci_range.vci_bits))
return -EINVAL;
if (vci > 0 && vci < ATM_NOT_RSV_VCI && !capable(CAP_NET_BIND_SERVICE))
return -EPERM;
error = -ENODEV;
if (!try_module_get(dev->ops->owner))
return error;
vcc->dev = dev;
write_lock_irq(&vcc_sklist_lock);
if (test_bit(ATM_DF_REMOVED, &dev->flags) ||
(error = find_ci(vcc, &vpi, &vci))) {
write_unlock_irq(&vcc_sklist_lock);
goto fail_module_put;
}
vcc->vpi = vpi;
vcc->vci = vci;
__vcc_insert_socket(sk);
write_unlock_irq(&vcc_sklist_lock);
switch (vcc->qos.aal) {
case ATM_AAL0:
error = atm_init_aal0(vcc);
vcc->stats = &dev->stats.aal0;
break;
case ATM_AAL34:
error = atm_init_aal34(vcc);
vcc->stats = &dev->stats.aal34;
break;
case ATM_NO_AAL:
/* ATM_AAL5 is also used in the "0 for default" case */
vcc->qos.aal = ATM_AAL5;
/* fall through */
case ATM_AAL5:
error = atm_init_aal5(vcc);
vcc->stats = &dev->stats.aal5;
break;
default:
error = -EPROTOTYPE;
}
if (!error)
error = adjust_tp(&vcc->qos.txtp, vcc->qos.aal);
if (!error)
error = adjust_tp(&vcc->qos.rxtp, vcc->qos.aal);
if (error)
goto fail;
pr_debug("VCC %d.%d, AAL %d\n", vpi, vci, vcc->qos.aal);
pr_debug(" TX: %d, PCR %d..%d, SDU %d\n",
vcc->qos.txtp.traffic_class,
vcc->qos.txtp.min_pcr,
vcc->qos.txtp.max_pcr,
vcc->qos.txtp.max_sdu);
pr_debug(" RX: %d, PCR %d..%d, SDU %d\n",
vcc->qos.rxtp.traffic_class,
vcc->qos.rxtp.min_pcr,
vcc->qos.rxtp.max_pcr,
vcc->qos.rxtp.max_sdu);
if (dev->ops->open) {
error = dev->ops->open(vcc);
if (error)
goto fail;
}
return 0;
fail:
vcc_remove_socket(sk);
fail_module_put:
module_put(dev->ops->owner);
/* ensure we get dev module ref count correct */
vcc->dev = NULL;
return error;
}
int vcc_connect(struct socket *sock, int itf, short vpi, int vci)
{
struct atm_dev *dev;
struct atm_vcc *vcc = ATM_SD(sock);
int error;
pr_debug("(vpi %d, vci %d)\n", vpi, vci);
if (sock->state == SS_CONNECTED)
return -EISCONN;
if (sock->state != SS_UNCONNECTED)
return -EINVAL;
if (!(vpi || vci))
return -EINVAL;
if (vpi != ATM_VPI_UNSPEC && vci != ATM_VCI_UNSPEC)
clear_bit(ATM_VF_PARTIAL, &vcc->flags);
else
if (test_bit(ATM_VF_PARTIAL, &vcc->flags))
return -EINVAL;
pr_debug("(TX: cl %d,bw %d-%d,sdu %d; "
"RX: cl %d,bw %d-%d,sdu %d,AAL %s%d)\n",
vcc->qos.txtp.traffic_class, vcc->qos.txtp.min_pcr,
vcc->qos.txtp.max_pcr, vcc->qos.txtp.max_sdu,
vcc->qos.rxtp.traffic_class, vcc->qos.rxtp.min_pcr,
vcc->qos.rxtp.max_pcr, vcc->qos.rxtp.max_sdu,
vcc->qos.aal == ATM_AAL5 ? "" :
vcc->qos.aal == ATM_AAL0 ? "" : " ??? code ",
vcc->qos.aal == ATM_AAL0 ? 0 : vcc->qos.aal);
if (!test_bit(ATM_VF_HASQOS, &vcc->flags))
return -EBADFD;
if (vcc->qos.txtp.traffic_class == ATM_ANYCLASS ||
vcc->qos.rxtp.traffic_class == ATM_ANYCLASS)
return -EINVAL;
if (likely(itf != ATM_ITF_ANY)) {
dev = try_then_request_module(atm_dev_lookup(itf),
"atm-device-%d", itf);
} else {
dev = NULL;
mutex_lock(&atm_dev_mutex);
if (!list_empty(&atm_devs)) {
dev = list_entry(atm_devs.next,
struct atm_dev, dev_list);
atm_dev_hold(dev);
}
mutex_unlock(&atm_dev_mutex);
}
if (!dev)
return -ENODEV;
error = __vcc_connect(vcc, dev, vpi, vci);
if (error) {
atm_dev_put(dev);
return error;
}
if (vpi == ATM_VPI_UNSPEC || vci == ATM_VCI_UNSPEC)
set_bit(ATM_VF_PARTIAL, &vcc->flags);
if (test_bit(ATM_VF_READY, &ATM_SD(sock)->flags))
sock->state = SS_CONNECTED;
return 0;
}
int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
size_t size, int flags)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
struct sk_buff *skb;
int copied, error = -EINVAL;
if (sock->state != SS_CONNECTED)
return -ENOTCONN;
/* only handle MSG_DONTWAIT and MSG_PEEK */
if (flags & ~(MSG_DONTWAIT | MSG_PEEK))
return -EOPNOTSUPP;
vcc = ATM_SD(sock);
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags))
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error);
if (!skb)
return error;
copied = skb->len;
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (error)
return error;
sock_recv_ts_and_drops(msg, sk, skb);
if (!(flags & MSG_PEEK)) {
pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc),
skb->truesize);
atm_return(vcc, skb->truesize);
}
skb_free_datagram(sk, skb);
return copied;
}
int vcc_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m,
size_t total_len)
{
struct sock *sk = sock->sk;
DEFINE_WAIT(wait);
struct atm_vcc *vcc;
struct sk_buff *skb;
int eff, error;
const void __user *buff;
int size;
lock_sock(sk);
if (sock->state != SS_CONNECTED) {
error = -ENOTCONN;
goto out;
}
if (m->msg_name) {
error = -EISCONN;
goto out;
}
if (m->msg_iovlen != 1) {
error = -ENOSYS; /* fix this later @@@ */
goto out;
}
buff = m->msg_iov->iov_base;
size = m->msg_iov->iov_len;
vcc = ATM_SD(sock);
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags)) {
error = -EPIPE;
send_sig(SIGPIPE, current, 0);
goto out;
}
if (!size) {
error = 0;
goto out;
}
if (size < 0 || size > vcc->qos.txtp.max_sdu) {
error = -EMSGSIZE;
goto out;
}
eff = (size+3) & ~3; /* align to word boundary */
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
error = 0;
while (!(skb = alloc_tx(vcc, eff))) {
if (m->msg_flags & MSG_DONTWAIT) {
error = -EAGAIN;
break;
}
schedule();
if (signal_pending(current)) {
error = -ERESTARTSYS;
break;
}
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags) ||
!test_bit(ATM_VF_READY, &vcc->flags)) {
error = -EPIPE;
send_sig(SIGPIPE, current, 0);
break;
}
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
}
finish_wait(sk_sleep(sk), &wait);
if (error)
goto out;
skb->dev = NULL; /* for paths shared with net_device interfaces */
ATM_SKB(skb)->atm_options = vcc->atm_options;
if (copy_from_user(skb_put(skb, size), buff, size)) {
kfree_skb(skb);
error = -EFAULT;
goto out;
}
if (eff != size)
memset(skb->data + size, 0, eff-size);
error = vcc->dev->ops->send(vcc, skb);
error = error ? error : size;
out:
release_sock(sk);
return error;
}
unsigned int vcc_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
struct atm_vcc *vcc;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
vcc = ATM_SD(sock);
/* exceptional events */
if (sk->sk_err)
mask = POLLERR;
if (test_bit(ATM_VF_RELEASED, &vcc->flags) ||
test_bit(ATM_VF_CLOSE, &vcc->flags))
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* writable? */
if (sock->state == SS_CONNECTING &&
test_bit(ATM_VF_WAITING, &vcc->flags))
return mask;
if (vcc->qos.txtp.traffic_class != ATM_NONE &&
vcc_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static int atm_change_qos(struct atm_vcc *vcc, struct atm_qos *qos)
{
int error;
/*
* Don't let the QoS change the already connected AAL type nor the
* traffic class.
*/
if (qos->aal != vcc->qos.aal ||
qos->rxtp.traffic_class != vcc->qos.rxtp.traffic_class ||
qos->txtp.traffic_class != vcc->qos.txtp.traffic_class)
return -EINVAL;
error = adjust_tp(&qos->txtp, qos->aal);
if (!error)
error = adjust_tp(&qos->rxtp, qos->aal);
if (error)
return error;
if (!vcc->dev->ops->change_qos)
return -EOPNOTSUPP;
if (sk_atm(vcc)->sk_family == AF_ATMPVC)
return vcc->dev->ops->change_qos(vcc, qos, ATM_MF_SET);
return svc_change_qos(vcc, qos);
}
static int check_tp(const struct atm_trafprm *tp)
{
/* @@@ Should be merged with adjust_tp */
if (!tp->traffic_class || tp->traffic_class == ATM_ANYCLASS)
return 0;
if (tp->traffic_class != ATM_UBR && !tp->min_pcr && !tp->pcr &&
!tp->max_pcr)
return -EINVAL;
if (tp->min_pcr == ATM_MAX_PCR)
return -EINVAL;
if (tp->min_pcr && tp->max_pcr && tp->max_pcr != ATM_MAX_PCR &&
tp->min_pcr > tp->max_pcr)
return -EINVAL;
/*
* We allow pcr to be outside [min_pcr,max_pcr], because later
* adjustment may still push it in the valid range.
*/
return 0;
}
static int check_qos(const struct atm_qos *qos)
{
int error;
if (!qos->txtp.traffic_class && !qos->rxtp.traffic_class)
return -EINVAL;
if (qos->txtp.traffic_class != qos->rxtp.traffic_class &&
qos->txtp.traffic_class && qos->rxtp.traffic_class &&
qos->txtp.traffic_class != ATM_ANYCLASS &&
qos->rxtp.traffic_class != ATM_ANYCLASS)
return -EINVAL;
error = check_tp(&qos->txtp);
if (error)
return error;
return check_tp(&qos->rxtp);
}
int vcc_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct atm_vcc *vcc;
unsigned long value;
int error;
if (__SO_LEVEL_MATCH(optname, level) && optlen != __SO_SIZE(optname))
return -EINVAL;
vcc = ATM_SD(sock);
switch (optname) {
case SO_ATMQOS:
{
struct atm_qos qos;
if (copy_from_user(&qos, optval, sizeof(qos)))
return -EFAULT;
error = check_qos(&qos);
if (error)
return error;
if (sock->state == SS_CONNECTED)
return atm_change_qos(vcc, &qos);
if (sock->state != SS_UNCONNECTED)
return -EBADFD;
vcc->qos = qos;
set_bit(ATM_VF_HASQOS, &vcc->flags);
return 0;
}
case SO_SETCLP:
if (get_user(value, (unsigned long __user *)optval))
return -EFAULT;
if (value)
vcc->atm_options |= ATM_ATMOPT_CLP;
else
vcc->atm_options &= ~ATM_ATMOPT_CLP;
return 0;
default:
if (level == SOL_SOCKET)
return -EINVAL;
break;
}
if (!vcc->dev || !vcc->dev->ops->setsockopt)
return -EINVAL;
return vcc->dev->ops->setsockopt(vcc, level, optname, optval, optlen);
}
int vcc_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct atm_vcc *vcc;
int len;
if (get_user(len, optlen))
return -EFAULT;
if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname))
return -EINVAL;
vcc = ATM_SD(sock);
switch (optname) {
case SO_ATMQOS:
if (!test_bit(ATM_VF_HASQOS, &vcc->flags))
return -EINVAL;
return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos))
? -EFAULT : 0;
case SO_SETCLP:
return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0,
(unsigned long __user *)optval) ? -EFAULT : 0;
case SO_ATMPVC:
{
struct sockaddr_atmpvc pvc;
if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags))
return -ENOTCONN;
memset(&pvc, 0, sizeof(pvc));
pvc.sap_family = AF_ATMPVC;
pvc.sap_addr.itf = vcc->dev->number;
pvc.sap_addr.vpi = vcc->vpi;
pvc.sap_addr.vci = vcc->vci;
return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0;
}
default:
if (level == SOL_SOCKET)
return -EINVAL;
break;
}
if (!vcc->dev || !vcc->dev->ops->getsockopt)
return -EINVAL;
return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len);
}
int register_atmdevice_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&atm_dev_notify_chain, nb);
}
EXPORT_SYMBOL_GPL(register_atmdevice_notifier);
void unregister_atmdevice_notifier(struct notifier_block *nb)
{
atomic_notifier_chain_unregister(&atm_dev_notify_chain, nb);
}
EXPORT_SYMBOL_GPL(unregister_atmdevice_notifier);
static int __init atm_init(void)
{
int error;
error = proto_register(&vcc_proto, 0);
if (error < 0)
goto out;
error = atmpvc_init();
if (error < 0) {
pr_err("atmpvc_init() failed with %d\n", error);
goto out_unregister_vcc_proto;
}
error = atmsvc_init();
if (error < 0) {
pr_err("atmsvc_init() failed with %d\n", error);
goto out_atmpvc_exit;
}
error = atm_proc_init();
if (error < 0) {
pr_err("atm_proc_init() failed with %d\n", error);
goto out_atmsvc_exit;
}
error = atm_sysfs_init();
if (error < 0) {
pr_err("atm_sysfs_init() failed with %d\n", error);
goto out_atmproc_exit;
}
out:
return error;
out_atmproc_exit:
atm_proc_exit();
out_atmsvc_exit:
atmsvc_exit();
out_atmpvc_exit:
atmsvc_exit();
out_unregister_vcc_proto:
proto_unregister(&vcc_proto);
goto out;
}
static void __exit atm_exit(void)
{
atm_proc_exit();
atm_sysfs_exit();
atmsvc_exit();
atmpvc_exit();
proto_unregister(&vcc_proto);
}
subsys_initcall(atm_init);
module_exit(atm_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_ATMPVC);
MODULE_ALIAS_NETPROTO(PF_ATMSVC);
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5845_6 |
crossvul-cpp_data_good_4789_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M M SSSSS L %
% MM MM SS L %
% M M M SSS L %
% M M SS L %
% M M SSSSS LLLLL %
% %
% %
% Execute Magick Scripting Language Scripts. %
% %
% Software Design %
% Cristy %
% Leonard Rosenthol %
% William Radcliffe %
% December 2001 %
% %
% %
% Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/annotate.h"
#include "magick/artifact.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-view.h"
#include "magick/channel.h"
#include "magick/color.h"
#include "magick/colormap.h"
#include "magick/color-private.h"
#include "magick/composite.h"
#include "magick/constitute.h"
#include "magick/decorate.h"
#include "magick/display.h"
#include "magick/distort.h"
#include "magick/draw.h"
#include "magick/effect.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/fx.h"
#include "magick/geometry.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/quantum-private.h"
#include "magick/registry.h"
#include "magick/resize.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/shear.h"
#include "magick/signature.h"
#include "magick/statistic.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/transform.h"
#include "magick/threshold.h"
#include "magick/utility.h"
#if defined(MAGICKCORE_XML_DELEGATE)
# if defined(MAGICKCORE_WINDOWS_SUPPORT)
# if !defined(__MINGW32__) && !defined(__MINGW64__)
# include <win32config.h>
# endif
# endif
# include <libxml/parser.h>
# include <libxml/xmlmemory.h>
# include <libxml/parserInternals.h>
# include <libxml/xmlerror.h>
#endif
/*
Define Declatations.
*/
#define ThrowMSLException(severity,tag,reason) \
(void) ThrowMagickException(msl_info->exception,GetMagickModule(),severity, \
tag,"`%s'",reason);
/*
Typedef declaractions.
*/
typedef struct _MSLGroupInfo
{
size_t
numImages; /* how many images are in this group */
} MSLGroupInfo;
typedef struct _MSLInfo
{
ExceptionInfo
*exception;
ssize_t
n,
number_groups;
ImageInfo
**image_info;
DrawInfo
**draw_info;
Image
**attributes,
**image;
char
*content;
MSLGroupInfo
*group_info;
#if defined(MAGICKCORE_XML_DELEGATE)
xmlParserCtxtPtr
parser;
xmlDocPtr
document;
#endif
} MSLInfo;
/*
Forward declarations.
*/
#if defined(MAGICKCORE_XML_DELEGATE)
static MagickBooleanType
WriteMSLImage(const ImageInfo *,Image *);
static MagickBooleanType
SetMSLAttributes(MSLInfo *,const char *,const char *);
#endif
#if defined(MAGICKCORE_XML_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMSLImage() reads a Magick Scripting Language file and returns it.
% It allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadMSLImage method is:
%
% Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static inline Image *GetImageCache(const ImageInfo *image_info,const char *path,
ExceptionInfo *exception)
{
char
key[MaxTextExtent];
ExceptionInfo
*sans_exception;
Image
*image;
ImageInfo
*read_info;
(void) FormatLocaleString(key,MaxTextExtent,"cache:%s",path);
sans_exception=AcquireExceptionInfo();
image=(Image *) GetImageRegistry(ImageRegistryType,key,sans_exception);
sans_exception=DestroyExceptionInfo(sans_exception);
if (image != (Image *) NULL)
return(image);
read_info=CloneImageInfo(image_info);
(void) CopyMagickString(read_info->filename,path,MaxTextExtent);
image=ReadImage(read_info,exception);
read_info=DestroyImageInfo(read_info);
if (image != (Image *) NULL)
(void) SetImageRegistry(ImageRegistryType,key,image,exception);
return(image);
}
static int IsPathDirectory(const char *path)
{
MagickBooleanType
status;
struct stat
attributes;
if ((path == (const char *) NULL) || (*path == '\0'))
return(MagickFalse);
status=GetPathAttributes(path,&attributes);
if (status == MagickFalse)
return(-1);
if (S_ISDIR(attributes.st_mode) == 0)
return(0);
return(1);
}
static int MSLIsStandalone(void *context)
{
MSLInfo
*msl_info;
/*
Is this document tagged standalone?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.MSLIsStandalone()");
msl_info=(MSLInfo *) context;
return(msl_info->document->standalone == 1);
}
static int MSLHasInternalSubset(void *context)
{
MSLInfo
*msl_info;
/*
Does this document has an internal subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.MSLHasInternalSubset()");
msl_info=(MSLInfo *) context;
return(msl_info->document->intSubset != NULL);
}
static int MSLHasExternalSubset(void *context)
{
MSLInfo
*msl_info;
/*
Does this document has an external subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.MSLHasExternalSubset()");
msl_info=(MSLInfo *) context;
return(msl_info->document->extSubset != NULL);
}
static void MSLInternalSubset(void *context,const xmlChar *name,
const xmlChar *external_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
/*
Does this document has an internal subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.internalSubset(%s %s %s)",name,
(external_id != (const xmlChar *) NULL ? (const char *) external_id : " "),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : " "));
msl_info=(MSLInfo *) context;
(void) xmlCreateIntSubset(msl_info->document,name,external_id,system_id);
}
static xmlParserInputPtr MSLResolveEntity(void *context,
const xmlChar *public_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
xmlParserInputPtr
stream;
/*
Special entity resolver, better left to the parser, it has more
context than the application layer. The default behaviour is to
not resolve the entities, in that case the ENTITY_REF nodes are
built in the structure (and the parameter values).
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.resolveEntity(%s, %s)",
(public_id != (const xmlChar *) NULL ? (const char *) public_id : "none"),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : "none"));
msl_info=(MSLInfo *) context;
stream=xmlLoadExternalEntity((const char *) system_id,(const char *)
public_id,msl_info->parser);
return(stream);
}
static xmlEntityPtr MSLGetEntity(void *context,const xmlChar *name)
{
MSLInfo
*msl_info;
/*
Get an entity by name.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.MSLGetEntity(%s)",(const char *) name);
msl_info=(MSLInfo *) context;
return(xmlGetDocEntity(msl_info->document,name));
}
static xmlEntityPtr MSLGetParameterEntity(void *context,const xmlChar *name)
{
MSLInfo
*msl_info;
/*
Get a parameter entity by name.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.getParameterEntity(%s)",(const char *) name);
msl_info=(MSLInfo *) context;
return(xmlGetParameterEntity(msl_info->document,name));
}
static void MSLEntityDeclaration(void *context,const xmlChar *name,int type,
const xmlChar *public_id,const xmlChar *system_id,xmlChar *content)
{
MSLInfo
*msl_info;
/*
An entity definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.entityDecl(%s, %d, %s, %s, %s)",name,type,
public_id != (const xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (const xmlChar *) NULL ? (const char *) system_id : "none",
content);
msl_info=(MSLInfo *) context;
if (msl_info->parser->inSubset == 1)
(void) xmlAddDocEntity(msl_info->document,name,type,public_id,system_id,
content);
else
if (msl_info->parser->inSubset == 2)
(void) xmlAddDtdEntity(msl_info->document,name,type,public_id,system_id,
content);
}
static void MSLAttributeDeclaration(void *context,const xmlChar *element,
const xmlChar *name,int type,int value,const xmlChar *default_value,
xmlEnumerationPtr tree)
{
MSLInfo
*msl_info;
xmlChar
*fullname,
*prefix;
xmlParserCtxtPtr
parser;
/*
An attribute definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.attributeDecl(%s, %s, %d, %d, %s, ...)\n",element,name,type,value,
default_value);
msl_info=(MSLInfo *) context;
fullname=(xmlChar *) NULL;
prefix=(xmlChar *) NULL;
parser=msl_info->parser;
fullname=(xmlChar *) xmlSplitQName(parser,name,&prefix);
if (parser->inSubset == 1)
(void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->intSubset,
element,fullname,prefix,(xmlAttributeType) type,
(xmlAttributeDefault) value,default_value,tree);
else
if (parser->inSubset == 2)
(void) xmlAddAttributeDecl(&parser->vctxt,msl_info->document->extSubset,
element,fullname,prefix,(xmlAttributeType) type,
(xmlAttributeDefault) value,default_value,tree);
if (prefix != (xmlChar *) NULL)
xmlFree(prefix);
if (fullname != (xmlChar *) NULL)
xmlFree(fullname);
}
static void MSLElementDeclaration(void *context,const xmlChar *name,int type,
xmlElementContentPtr content)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
An element definition has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.elementDecl(%s, %d, ...)",name,type);
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
if (parser->inSubset == 1)
(void) xmlAddElementDecl(&parser->vctxt,msl_info->document->intSubset,
name,(xmlElementTypeVal) type,content);
else
if (parser->inSubset == 2)
(void) xmlAddElementDecl(&parser->vctxt,msl_info->document->extSubset,
name,(xmlElementTypeVal) type,content);
}
static void MSLNotationDeclaration(void *context,const xmlChar *name,
const xmlChar *public_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
What to do when a notation declaration has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.notationDecl(%s, %s, %s)",name,
public_id != (const xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (const xmlChar *) NULL ? (const char *) system_id : "none");
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
if (parser->inSubset == 1)
(void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset,
name,public_id,system_id);
else
if (parser->inSubset == 2)
(void) xmlAddNotationDecl(&parser->vctxt,msl_info->document->intSubset,
name,public_id,system_id);
}
static void MSLUnparsedEntityDeclaration(void *context,const xmlChar *name,
const xmlChar *public_id,const xmlChar *system_id,const xmlChar *notation)
{
MSLInfo
*msl_info;
/*
What to do when an unparsed entity declaration is parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.unparsedEntityDecl(%s, %s, %s, %s)",name,
public_id != (const xmlChar *) NULL ? (const char *) public_id : "none",
system_id != (const xmlChar *) NULL ? (const char *) system_id : "none",
notation);
msl_info=(MSLInfo *) context;
(void) xmlAddDocEntity(msl_info->document,name,
XML_EXTERNAL_GENERAL_UNPARSED_ENTITY,public_id,system_id,notation);
}
static void MSLSetDocumentLocator(void *context,xmlSAXLocatorPtr location)
{
MSLInfo
*msl_info;
/*
Receive the document locator at startup, actually xmlDefaultSAXLocator.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.setDocumentLocator()\n");
(void) location;
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLStartDocument(void *context)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
Called when the document start being processed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.startDocument()");
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
msl_info->document=xmlNewDoc(parser->version);
if (msl_info->document == (xmlDocPtr) NULL)
return;
if (parser->encoding == NULL)
msl_info->document->encoding=NULL;
else
msl_info->document->encoding=xmlStrdup(parser->encoding);
msl_info->document->standalone=parser->standalone;
}
static void MSLEndDocument(void *context)
{
MSLInfo
*msl_info;
/*
Called when the document end has been detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endDocument()");
msl_info=(MSLInfo *) context;
if (msl_info->content != (char *) NULL)
msl_info->content=DestroyString(msl_info->content);
}
static void MSLPushImage(MSLInfo *msl_info,Image *image)
{
ssize_t
n;
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(msl_info != (MSLInfo *) NULL);
msl_info->n++;
n=msl_info->n;
msl_info->image_info=(ImageInfo **) ResizeQuantumMemory(msl_info->image_info,
(n+1),sizeof(*msl_info->image_info));
msl_info->draw_info=(DrawInfo **) ResizeQuantumMemory(msl_info->draw_info,
(n+1),sizeof(*msl_info->draw_info));
msl_info->attributes=(Image **) ResizeQuantumMemory(msl_info->attributes,
(n+1),sizeof(*msl_info->attributes));
msl_info->image=(Image **) ResizeQuantumMemory(msl_info->image,(n+1),
sizeof(*msl_info->image));
if ((msl_info->image_info == (ImageInfo **) NULL) ||
(msl_info->draw_info == (DrawInfo **) NULL) ||
(msl_info->attributes == (Image **) NULL) ||
(msl_info->image == (Image **) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
msl_info->image_info[n]=CloneImageInfo(msl_info->image_info[n-1]);
msl_info->draw_info[n]=CloneDrawInfo(msl_info->image_info[n-1],
msl_info->draw_info[n-1]);
if (image == (Image *) NULL)
msl_info->attributes[n]=AcquireImage(msl_info->image_info[n]);
else
msl_info->attributes[n]=CloneImage(image,0,0,MagickTrue,&image->exception);
msl_info->image[n]=(Image *) image;
if ((msl_info->image_info[n] == (ImageInfo *) NULL) ||
(msl_info->attributes[n] == (Image *) NULL))
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
if (msl_info->number_groups != 0)
msl_info->group_info[msl_info->number_groups-1].numImages++;
}
static void MSLPopImage(MSLInfo *msl_info)
{
if (msl_info->number_groups != 0)
return;
if (msl_info->image[msl_info->n] != (Image *) NULL)
msl_info->image[msl_info->n]=DestroyImage(msl_info->image[msl_info->n]);
msl_info->attributes[msl_info->n]=DestroyImage(
msl_info->attributes[msl_info->n]);
msl_info->image_info[msl_info->n]=DestroyImageInfo(
msl_info->image_info[msl_info->n]);
msl_info->n--;
}
static void MSLStartElement(void *context,const xmlChar *tag,
const xmlChar **attributes)
{
AffineMatrix
affine,
current;
ChannelType
channel;
char
key[MaxTextExtent],
*value;
const char
*attribute,
*keyword;
double
angle;
DrawInfo
*draw_info;
ExceptionInfo
*exception;
GeometryInfo
geometry_info;
Image
*image;
int
flags;
ssize_t
option,
j,
n,
x,
y;
MSLInfo
*msl_info;
RectangleInfo
geometry;
register ssize_t
i;
size_t
height,
width;
/*
Called when an opening tag has been processed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.startElement(%s",tag);
exception=AcquireExceptionInfo();
msl_info=(MSLInfo *) context;
n=msl_info->n;
keyword=(const char *) NULL;
value=(char *) NULL;
SetGeometryInfo(&geometry_info);
(void) ResetMagickMemory(&geometry,0,sizeof(geometry));
channel=DefaultChannels;
switch (*tag)
{
case 'A':
case 'a':
{
if (LocaleCompare((const char *) tag,"add-noise") == 0)
{
Image
*noise_image;
NoiseType
noise;
/*
Add noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
noise=UniformNoise;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'N':
case 'n':
{
if (LocaleCompare(keyword,"noise") == 0)
{
option=ParseCommandOption(MagickNoiseOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
noise=(NoiseType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
noise_image=AddNoiseImageChannel(msl_info->image[n],channel,noise,
&msl_info->image[n]->exception);
if (noise_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=noise_image;
break;
}
if (LocaleCompare((const char *) tag,"annotate") == 0)
{
char
text[MaxTextExtent];
/*
Annotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=tan(DegreesToRadians(fmod((double) angle,
360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=tan(DegreesToRadians(fmod((double) angle,
360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
CloneString(&draw_info->text,value);
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
(void) AnnotateImage(msl_info->image[n],draw_info);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"append") == 0)
{
Image
*append_image;
MagickBooleanType
stack;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
stack=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'S':
case 's':
{
if (LocaleCompare(keyword,"stack") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
stack=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
append_image=AppendImages(msl_info->image[n],stack,
&msl_info->image[n]->exception);
if (append_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=append_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
break;
}
case 'B':
case 'b':
{
if (LocaleCompare((const char *) tag,"blur") == 0)
{
Image
*blur_image;
/*
Blur image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
blur_image=BlurImageChannel(msl_info->image[n],channel,
geometry_info.rho,geometry_info.sigma,
&msl_info->image[n]->exception);
if (blur_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=blur_image;
break;
}
if (LocaleCompare((const char *) tag,"border") == 0)
{
Image
*border_image;
/*
Border image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
msl_info->image[n]->compose=(CompositeOperator) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->border_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
border_image=BorderImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (border_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=border_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'C':
case 'c':
{
if (LocaleCompare((const char *) tag,"colorize") == 0)
{
char
opacity[MaxTextExtent];
Image
*colorize_image;
PixelPacket
target;
/*
Add noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
target=msl_info->image[n]->background_color;
(void) CopyMagickString(opacity,"100",MaxTextExtent);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&target,
&msl_info->image[n]->exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
(void) CopyMagickString(opacity,value,MaxTextExtent);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
colorize_image=ColorizeImage(msl_info->image[n],opacity,target,
&msl_info->image[n]->exception);
if (colorize_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=colorize_image;
break;
}
if (LocaleCompare((const char *) tag, "charcoal") == 0)
{
double radius = 0.0,
sigma = 1.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/*
NOTE: charcoal can have no attributes, since we use all the defaults!
*/
if (attributes != (const xmlChar **) NULL)
{
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
radius=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
sigma = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
}
/*
charcoal image.
*/
{
Image
*newImage;
newImage=CharcoalImage(msl_info->image[n],radius,sigma,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
if (LocaleCompare((const char *) tag,"chop") == 0)
{
Image
*chop_image;
/*
Chop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
chop_image=ChopImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (chop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=chop_image;
break;
}
if (LocaleCompare((const char *) tag,"color-floodfill") == 0)
{
PaintMethod
paint_method;
MagickPixelPacket
target;
/*
Color floodfill image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
SetGeometry(msl_info->image[n],&geometry);
paint_method=FloodfillMethod;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryMagickColor(value,&target,exception);
paint_method=FillToBorderMethod;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FloodfillPaintImage(msl_info->image[n],DefaultChannels,
draw_info,&target,geometry.x,geometry.y,
paint_method == FloodfillMethod ? MagickFalse : MagickTrue);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"comment") == 0)
break;
if (LocaleCompare((const char *) tag,"composite") == 0)
{
char
composite_geometry[MaxTextExtent];
CompositeOperator
compose;
Image
*composite_image,
*rotate_image;
PixelPacket
target;
/*
Composite image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
composite_image=NewImageList();
compose=OverCompositeOp;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
compose=(CompositeOperator) option;
break;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
composite_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
break;
}
}
if (composite_image == (Image *) NULL)
break;
rotate_image=NewImageList();
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blend") == 0)
{
(void) SetImageArtifact(composite_image,
"compose:args",value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
if (LocaleCompare(keyword, "color") == 0)
{
(void) QueryColorDatabase(value,
&composite_image->background_color,exception);
break;
}
if (LocaleCompare(keyword,"compose") == 0)
break;
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
msl_info->image[n]->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
break;
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"mask") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(value,value) == 0))
{
SetImageType(composite_image,TrueColorMatteType);
(void) CompositeImage(composite_image,
CopyOpacityCompositeOp,msl_info->image[j],0,0);
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
ssize_t
opacity,
y;
register ssize_t
x;
register PixelPacket
*q;
CacheView
*composite_view;
opacity=QuantumRange-StringToLong(value);
if (compose != DissolveCompositeOp)
{
(void) SetImageOpacity(composite_image,(Quantum)
opacity);
break;
}
(void) SetImageArtifact(msl_info->image[n],
"compose:args",value);
if (composite_image->matte != MagickTrue)
(void) SetImageOpacity(composite_image,OpaqueOpacity);
composite_view=AcquireAuthenticCacheView(composite_image,
exception);
for (y=0; y < (ssize_t) composite_image->rows ; y++)
{
q=GetCacheViewAuthenticPixels(composite_view,0,y,
(ssize_t) composite_image->columns,1,exception);
for (x=0; x < (ssize_t) composite_image->columns; x++)
{
if (q->opacity == OpaqueOpacity)
q->opacity=ClampToQuantum(opacity);
q++;
}
if (SyncCacheViewAuthenticPixels(composite_view,exception) == MagickFalse)
break;
}
composite_view=DestroyCacheView(composite_view);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
rotate_image=RotateImage(composite_image,
StringToDouble(value,(char **) NULL),exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"tile") == 0)
{
MagickBooleanType
tile;
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
tile=(MagickBooleanType) option;
(void) tile;
if (rotate_image != (Image *) NULL)
(void) SetImageArtifact(rotate_image,
"compose:outside-overlay","false");
else
(void) SetImageArtifact(composite_image,
"compose:outside-overlay","false");
image=msl_info->image[n];
height=composite_image->rows;
width=composite_image->columns;
for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) height)
for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) width)
{
if (rotate_image != (Image *) NULL)
(void) CompositeImage(image,compose,rotate_image,
x,y);
else
(void) CompositeImage(image,compose,
composite_image,x,y);
}
if (rotate_image != (Image *) NULL)
rotate_image=DestroyImage(rotate_image);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualPixel(msl_info->image[n],geometry.x,
geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
image=msl_info->image[n];
(void) FormatLocaleString(composite_geometry,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,
(double) composite_image->rows,(double) geometry.x,(double)
geometry.y);
flags=ParseGravityGeometry(image,composite_geometry,&geometry,
exception);
if (rotate_image == (Image *) NULL)
CompositeImageChannel(image,channel,compose,composite_image,
geometry.x,geometry.y);
else
{
/*
Rotate image.
*/
geometry.x-=(ssize_t) (rotate_image->columns-
composite_image->columns)/2;
geometry.y-=(ssize_t) (rotate_image->rows-composite_image->rows)/2;
CompositeImageChannel(image,channel,compose,rotate_image,
geometry.x,geometry.y);
rotate_image=DestroyImage(rotate_image);
}
composite_image=DestroyImage(composite_image);
break;
}
if (LocaleCompare((const char *) tag,"contrast") == 0)
{
MagickBooleanType
sharpen;
/*
Contrast image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
sharpen=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sharpen") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
sharpen=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) ContrastImage(msl_info->image[n],sharpen);
break;
}
if (LocaleCompare((const char *) tag,"crop") == 0)
{
Image
*crop_image;
/*
Crop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGravityGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
crop_image=CropImage(msl_info->image[n],&geometry,
&msl_info->image[n]->exception);
if (crop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=crop_image;
break;
}
if (LocaleCompare((const char *) tag,"cycle-colormap") == 0)
{
ssize_t
display;
/*
Cycle-colormap image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
display=0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"display") == 0)
{
display=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) CycleColormapImage(msl_info->image[n],display);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'D':
case 'd':
{
if (LocaleCompare((const char *) tag,"despeckle") == 0)
{
Image
*despeckle_image;
/*
Despeckle image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
despeckle_image=DespeckleImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (despeckle_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=despeckle_image;
break;
}
if (LocaleCompare((const char *) tag,"display") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) DisplayImages(msl_info->image_info[n],msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"draw") == 0)
{
char
text[MaxTextExtent];
/*
Annotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"points") == 0)
{
if (LocaleCompare(draw_info->primitive,"path") == 0)
{
(void) ConcatenateString(&draw_info->primitive," '");
ConcatenateString(&draw_info->primitive,value);
(void) ConcatenateString(&draw_info->primitive,"'");
}
else
{
(void) ConcatenateString(&draw_info->primitive," ");
ConcatenateString(&draw_info->primitive,value);
}
break;
}
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"primitive") == 0)
{
CloneString(&draw_info->primitive,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
(void) ConcatenateString(&draw_info->primitive," '");
(void) ConcatenateString(&draw_info->primitive,value);
(void) ConcatenateString(&draw_info->primitive,"'");
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
(void) DrawImage(msl_info->image[n],draw_info);
draw_info=DestroyDrawInfo(draw_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'E':
case 'e':
{
if (LocaleCompare((const char *) tag,"edge") == 0)
{
Image
*edge_image;
/*
Edge image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
edge_image=EdgeImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (edge_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=edge_image;
break;
}
if (LocaleCompare((const char *) tag,"emboss") == 0)
{
Image
*emboss_image;
/*
Emboss image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
emboss_image=EmbossImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (emboss_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=emboss_image;
break;
}
if (LocaleCompare((const char *) tag,"enhance") == 0)
{
Image
*enhance_image;
/*
Enhance image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
enhance_image=EnhanceImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (enhance_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=enhance_image;
break;
}
if (LocaleCompare((const char *) tag,"equalize") == 0)
{
/*
Equalize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) EqualizeImage(msl_info->image[n]);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'F':
case 'f':
{
if (LocaleCompare((const char *) tag, "flatten") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/* no attributes here */
/* process the image */
{
Image
*newImage;
newImage=MergeImageLayers(msl_info->image[n],FlattenLayer,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
if (LocaleCompare((const char *) tag,"flip") == 0)
{
Image
*flip_image;
/*
Flip image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
flip_image=FlipImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (flip_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=flip_image;
break;
}
if (LocaleCompare((const char *) tag,"flop") == 0)
{
Image
*flop_image;
/*
Flop image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
flop_image=FlopImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (flop_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=flop_image;
break;
}
if (LocaleCompare((const char *) tag,"frame") == 0)
{
FrameInfo
frame_info;
Image
*frame_image;
/*
Frame image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
(void) ResetMagickMemory(&frame_info,0,sizeof(frame_info));
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"compose") == 0)
{
option=ParseCommandOption(MagickComposeOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedComposeType",
value);
msl_info->image[n]->compose=(CompositeOperator) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->matte_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
frame_info.width=geometry.width;
frame_info.height=geometry.height;
frame_info.outer_bevel=geometry.x;
frame_info.inner_bevel=geometry.y;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
frame_info.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"inner") == 0)
{
frame_info.inner_bevel=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"outer") == 0)
{
frame_info.outer_bevel=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
frame_info.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
frame_info.x=(ssize_t) frame_info.width;
frame_info.y=(ssize_t) frame_info.height;
frame_info.width=msl_info->image[n]->columns+2*frame_info.x;
frame_info.height=msl_info->image[n]->rows+2*frame_info.y;
frame_image=FrameImage(msl_info->image[n],&frame_info,
&msl_info->image[n]->exception);
if (frame_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=frame_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'G':
case 'g':
{
if (LocaleCompare((const char *) tag,"gamma") == 0)
{
char
gamma[MaxTextExtent];
MagickPixelPacket
pixel;
/*
Gamma image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
channel=UndefinedChannel;
pixel.red=0.0;
pixel.green=0.0;
pixel.blue=0.0;
*gamma='\0';
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blue") == 0)
{
pixel.blue=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
(void) CopyMagickString(gamma,value,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"green") == 0)
{
pixel.green=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"red") == 0)
{
pixel.red=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
if (*gamma == '\0')
(void) FormatLocaleString(gamma,MaxTextExtent,"%g,%g,%g",
(double) pixel.red,(double) pixel.green,(double) pixel.blue);
switch (channel)
{
default:
{
(void) GammaImage(msl_info->image[n],gamma);
break;
}
case RedChannel:
{
(void) GammaImageChannel(msl_info->image[n],RedChannel,pixel.red);
break;
}
case GreenChannel:
{
(void) GammaImageChannel(msl_info->image[n],GreenChannel,
pixel.green);
break;
}
case BlueChannel:
{
(void) GammaImageChannel(msl_info->image[n],BlueChannel,
pixel.blue);
break;
}
}
break;
}
else if (LocaleCompare((const char *) tag,"get") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,(const char *) attributes[i]);
(void) CopyMagickString(key,value,MaxTextExtent);
switch (*keyword)
{
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
(double) msl_info->image[n]->rows);
(void) SetImageProperty(msl_info->attributes[n],key,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
(void) FormatLocaleString(value,MaxTextExtent,"%.20g",
(double) msl_info->image[n]->columns);
(void) SetImageProperty(msl_info->attributes[n],key,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
else if (LocaleCompare((const char *) tag, "group") == 0)
{
msl_info->number_groups++;
msl_info->group_info=(MSLGroupInfo *) ResizeQuantumMemory(
msl_info->group_info,msl_info->number_groups+1UL,
sizeof(*msl_info->group_info));
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'I':
case 'i':
{
if (LocaleCompare((const char *) tag,"image") == 0)
{
MSLPushImage(msl_info,(Image *) NULL);
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"color") == 0)
{
Image
*next_image;
(void) CopyMagickString(msl_info->image_info[n]->filename,
"xc:",MaxTextExtent);
(void) ConcatenateMagickString(msl_info->image_info[n]->
filename,value,MaxTextExtent);
next_image=ReadImage(msl_info->image_info[n],exception);
CatchException(exception);
if (next_image == (Image *) NULL)
continue;
if (msl_info->image[n] == (Image *) NULL)
msl_info->image[n]=next_image;
else
{
register Image
*p;
/*
Link image into image list.
*/
p=msl_info->image[n];
while (p->next != (Image *) NULL)
p=GetNextImageInList(p);
next_image->previous=p;
p->next=next_image;
}
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"implode") == 0)
{
Image
*implode_image;
/*
Implode image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"amount") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
implode_image=ImplodeImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (implode_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=implode_image;
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'L':
case 'l':
{
if (LocaleCompare((const char *) tag,"label") == 0)
break;
if (LocaleCompare((const char *) tag, "level") == 0)
{
double
levelBlack = 0, levelGamma = 1, levelWhite = QuantumRange;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,(const char *) attributes[i]);
(void) CopyMagickString(key,value,MaxTextExtent);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"black") == 0)
{
levelBlack = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
levelGamma = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"white") == 0)
{
levelWhite = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/* process image */
{
char level[MaxTextExtent + 1];
(void) FormatLocaleString(level,MaxTextExtent,"%3.6f/%3.6f/%3.6f/",
levelBlack,levelGamma,levelWhite);
LevelImage ( msl_info->image[n], level );
break;
}
}
}
case 'M':
case 'm':
{
if (LocaleCompare((const char *) tag,"magnify") == 0)
{
Image
*magnify_image;
/*
Magnify image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
magnify_image=MagnifyImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (magnify_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=magnify_image;
break;
}
if (LocaleCompare((const char *) tag,"map") == 0)
{
Image
*affinity_image;
MagickBooleanType
dither;
QuantizeInfo
*quantize_info;
/*
Map image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
affinity_image=NewImageList();
dither=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"dither") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
dither=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
affinity_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
quantize_info=AcquireQuantizeInfo(msl_info->image_info[n]);
quantize_info->dither=dither;
(void) RemapImages(quantize_info,msl_info->image[n],
affinity_image);
quantize_info=DestroyQuantizeInfo(quantize_info);
affinity_image=DestroyImage(affinity_image);
break;
}
if (LocaleCompare((const char *) tag,"matte-floodfill") == 0)
{
double
opacity;
MagickPixelPacket
target;
PaintMethod
paint_method;
/*
Matte floodfill image.
*/
opacity=0.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
paint_method=FloodfillMethod;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryMagickColor(value,&target,exception);
paint_method=FillToBorderMethod;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
opacity=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
(void) GetOneVirtualMagickPixel(msl_info->image[n],
geometry.x,geometry.y,&target,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
draw_info->fill.opacity=ClampToQuantum(opacity);
(void) FloodfillPaintImage(msl_info->image[n],OpacityChannel,
draw_info,&target,geometry.x,geometry.y,
paint_method == FloodfillMethod ? MagickFalse : MagickTrue);
draw_info=DestroyDrawInfo(draw_info);
break;
}
if (LocaleCompare((const char *) tag,"median-filter") == 0)
{
Image
*median_image;
/*
Median-filter image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
median_image=StatisticImage(msl_info->image[n],MedianStatistic,
(size_t) geometry_info.rho,(size_t) geometry_info.sigma,
&msl_info->image[n]->exception);
if (median_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=median_image;
break;
}
if (LocaleCompare((const char *) tag,"minify") == 0)
{
Image
*minify_image;
/*
Minify image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
minify_image=MinifyImage(msl_info->image[n],
&msl_info->image[n]->exception);
if (minify_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=minify_image;
break;
}
if (LocaleCompare((const char *) tag,"msl") == 0 )
break;
if (LocaleCompare((const char *) tag,"modulate") == 0)
{
char
modulate[MaxTextExtent];
/*
Modulate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=100.0;
geometry_info.sigma=100.0;
geometry_info.xi=100.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"blackness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"brightness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"factor") == 0)
{
flags=ParseGeometry(value,&geometry_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"hue") == 0)
{
geometry_info.xi=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare(keyword,"lightness") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"saturation") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"whiteness") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(modulate,MaxTextExtent,"%g,%g,%g",
geometry_info.rho,geometry_info.sigma,geometry_info.xi);
(void) ModulateImage(msl_info->image[n],modulate);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'N':
case 'n':
{
if (LocaleCompare((const char *) tag,"negate") == 0)
{
MagickBooleanType
gray;
/*
Negate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
gray=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gray") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
gray=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) NegateImageChannel(msl_info->image[n],channel,gray);
break;
}
if (LocaleCompare((const char *) tag,"normalize") == 0)
{
/*
Normalize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) NormalizeImageChannel(msl_info->image[n],channel);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'O':
case 'o':
{
if (LocaleCompare((const char *) tag,"oil-paint") == 0)
{
Image
*paint_image;
/*
Oil-paint image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
paint_image=OilPaintImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (paint_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=paint_image;
break;
}
if (LocaleCompare((const char *) tag,"opaque") == 0)
{
MagickPixelPacket
fill_color,
target;
/*
Opaque image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
(void) QueryMagickColor("none",&target,exception);
(void) QueryMagickColor("none",&fill_color,exception);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"channel") == 0)
{
option=ParseChannelOption(value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedChannelType",
value);
channel=(ChannelType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryMagickColor(value,&fill_color,exception);
break;
}
if (LocaleCompare(keyword,"fuzz") == 0)
{
msl_info->image[n]->fuzz=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) OpaquePaintImageChannel(msl_info->image[n],channel,
&target,&fill_color,MagickFalse);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'P':
case 'p':
{
if (LocaleCompare((const char *) tag,"print") == 0)
{
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"output") == 0)
{
(void) FormatLocaleFile(stdout,"%s",value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag, "profile") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
const char
*name;
const StringInfo
*profile;
Image
*profile_image;
ImageInfo
*profile_info;
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
if (*keyword == '!')
{
/*
Remove a profile from the image.
*/
(void) ProfileImage(msl_info->image[n],keyword,
(const unsigned char *) NULL,0,MagickTrue);
continue;
}
/*
Associate a profile with the image.
*/
profile_info=CloneImageInfo(msl_info->image_info[n]);
profile=GetImageProfile(msl_info->image[n],"iptc");
if (profile != (StringInfo *) NULL)
profile_info->profile=(void *) CloneStringInfo(profile);
profile_image=GetImageCache(profile_info,keyword,exception);
profile_info=DestroyImageInfo(profile_info);
if (profile_image == (Image *) NULL)
{
char
name[MaxTextExtent],
filename[MaxTextExtent];
register char
*p;
StringInfo
*profile;
(void) CopyMagickString(filename,keyword,MaxTextExtent);
(void) CopyMagickString(name,keyword,MaxTextExtent);
for (p=filename; *p != '\0'; p++)
if ((*p == ':') && (IsPathDirectory(keyword) < 0) &&
(IsPathAccessible(keyword) == MagickFalse))
{
register char
*q;
/*
Look for profile name (e.g. name:profile).
*/
(void) CopyMagickString(name,filename,(size_t)
(p-filename+1));
for (q=filename; *q != '\0'; q++)
*q=(*++p);
break;
}
profile=FileToStringInfo(filename,~0UL,exception);
if (profile != (StringInfo *) NULL)
{
(void) ProfileImage(msl_info->image[n],name,
GetStringInfoDatum(profile),(size_t)
GetStringInfoLength(profile),MagickFalse);
profile=DestroyStringInfo(profile);
}
continue;
}
ResetImageProfileIterator(profile_image);
name=GetNextImageProfile(profile_image);
while (name != (const char *) NULL)
{
profile=GetImageProfile(profile_image,name);
if (profile != (StringInfo *) NULL)
(void) ProfileImage(msl_info->image[n],name,
GetStringInfoDatum(profile),(size_t)
GetStringInfoLength(profile),MagickFalse);
name=GetNextImageProfile(profile_image);
}
profile_image=DestroyImage(profile_image);
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'Q':
case 'q':
{
if (LocaleCompare((const char *) tag,"quantize") == 0)
{
QuantizeInfo
quantize_info;
/*
Quantize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
GetQuantizeInfo(&quantize_info);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"colors") == 0)
{
quantize_info.number_colors=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
option=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,
"UnrecognizedColorspaceType",value);
quantize_info.colorspace=(ColorspaceType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"dither") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
quantize_info.dither=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"measure") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
quantize_info.measure_error=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"treedepth") == 0)
{
quantize_info.tree_depth=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) QuantizeImage(&quantize_info,msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"query-font-metrics") == 0)
{
char
text[MaxTextExtent];
MagickBooleanType
status;
TypeMetric
metrics;
/*
Query font metrics.
*/
draw_info=CloneDrawInfo(msl_info->image_info[n],
msl_info->draw_info[n]);
angle=0.0;
current=draw_info->affine;
GetAffineMatrix(&affine);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"affine") == 0)
{
char
*p;
p=value;
draw_info->affine.sx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.rx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ry=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.sy=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.tx=StringToDouble(p,&p);
if (*p ==',')
p++;
draw_info->affine.ty=StringToDouble(p,&p);
break;
}
if (LocaleCompare(keyword,"align") == 0)
{
option=ParseCommandOption(MagickAlignOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedAlignType",
value);
draw_info->align=(AlignType) option;
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedBooleanType",
value);
draw_info->stroke_antialias=(MagickBooleanType) option;
draw_info->text_antialias=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"encoding") == 0)
{
CloneString(&draw_info->encoding,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,
exception);
break;
}
if (LocaleCompare(keyword,"family") == 0)
{
CloneString(&draw_info->family,value);
break;
}
if (LocaleCompare(keyword,"font") == 0)
{
CloneString(&draw_info->font,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
if (LocaleCompare(keyword,"gravity") == 0)
{
option=ParseCommandOption(MagickGravityOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",
value);
draw_info->gravity=(GravityType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
draw_info->pointsize=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"rotate") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.sx=cos(DegreesToRadians(fmod(angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod(angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"scale") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.sx=geometry_info.rho;
affine.sy=geometry_info.sigma;
break;
}
if (LocaleCompare(keyword,"skewX") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.ry=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"skewY") == 0)
{
angle=StringToDouble(value,(char **) NULL);
affine.rx=cos(DegreesToRadians(fmod(angle,360.0)));
break;
}
if (LocaleCompare(keyword,"stretch") == 0)
{
option=ParseCommandOption(MagickStretchOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStretchType",
value);
draw_info->stretch=(StretchType) option;
break;
}
if (LocaleCompare(keyword, "stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,
exception);
break;
}
if (LocaleCompare(keyword,"strokewidth") == 0)
{
draw_info->stroke_width=StringToLong(value);
break;
}
if (LocaleCompare(keyword,"style") == 0)
{
option=ParseCommandOption(MagickStyleOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedStyleType",
value);
draw_info->style=(StyleType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"text") == 0)
{
CloneString(&draw_info->text,value);
break;
}
if (LocaleCompare(keyword,"translate") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
affine.tx=geometry_info.rho;
affine.ty=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'U':
case 'u':
{
if (LocaleCompare(keyword, "undercolor") == 0)
{
(void) QueryColorDatabase(value,&draw_info->undercolor,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"weight") == 0)
{
draw_info->weight=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) FormatLocaleString(text,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double)
geometry.height,(double) geometry.x,(double) geometry.y);
CloneString(&draw_info->geometry,text);
draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx;
draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx;
draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy;
draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy;
draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+
affine.tx;
draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+
affine.ty;
status=GetTypeMetrics(msl_info->attributes[n],draw_info,&metrics);
if (status != MagickFalse)
{
Image
*image;
image=msl_info->attributes[n];
FormatImageProperty(image,"msl:font-metrics.pixels_per_em.x",
"%g",metrics.pixels_per_em.x);
FormatImageProperty(image,"msl:font-metrics.pixels_per_em.y",
"%g",metrics.pixels_per_em.y);
FormatImageProperty(image,"msl:font-metrics.ascent","%g",
metrics.ascent);
FormatImageProperty(image,"msl:font-metrics.descent","%g",
metrics.descent);
FormatImageProperty(image,"msl:font-metrics.width","%g",
metrics.width);
FormatImageProperty(image,"msl:font-metrics.height","%g",
metrics.height);
FormatImageProperty(image,"msl:font-metrics.max_advance","%g",
metrics.max_advance);
FormatImageProperty(image,"msl:font-metrics.bounds.x1","%g",
metrics.bounds.x1);
FormatImageProperty(image,"msl:font-metrics.bounds.y1","%g",
metrics.bounds.y1);
FormatImageProperty(image,"msl:font-metrics.bounds.x2","%g",
metrics.bounds.x2);
FormatImageProperty(image,"msl:font-metrics.bounds.y2","%g",
metrics.bounds.y2);
FormatImageProperty(image,"msl:font-metrics.origin.x","%g",
metrics.origin.x);
FormatImageProperty(image,"msl:font-metrics.origin.y","%g",
metrics.origin.y);
}
draw_info=DestroyDrawInfo(draw_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'R':
case 'r':
{
if (LocaleCompare((const char *) tag,"raise") == 0)
{
MagickBooleanType
raise;
/*
Raise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
raise=MagickFalse;
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"raise") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
raise=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) RaiseImage(msl_info->image[n],&geometry,raise);
break;
}
if (LocaleCompare((const char *) tag,"read") == 0)
{
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filename") == 0)
{
Image
*image;
if (value == (char *) NULL)
break;
(void) CopyMagickString(msl_info->image_info[n]->filename,
value,MaxTextExtent);
image=ReadImage(msl_info->image_info[n],exception);
CatchException(exception);
if (image == (Image *) NULL)
continue;
AppendImageToList(&msl_info->image[n],image);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"reduce-noise") == 0)
{
Image
*paint_image;
/*
Reduce-noise image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
paint_image=StatisticImage(msl_info->image[n],NonpeakStatistic,
(size_t) geometry_info.rho,(size_t) geometry_info.sigma,
&msl_info->image[n]->exception);
if (paint_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=paint_image;
break;
}
else if (LocaleCompare((const char *) tag,"repage") == 0)
{
/* init the values */
width=msl_info->image[n]->page.width;
height=msl_info->image[n]->page.height;
x=msl_info->image[n]->page.x;
y=msl_info->image[n]->page.y;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
int
flags;
RectangleInfo
geometry;
flags=ParseAbsoluteGeometry(value,&geometry);
if ((flags & WidthValue) != 0)
{
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
width=geometry.width;
height=geometry.height;
}
if ((flags & AspectValue) != 0)
{
if ((flags & XValue) != 0)
x+=geometry.x;
if ((flags & YValue) != 0)
y+=geometry.y;
}
else
{
if ((flags & XValue) != 0)
{
x=geometry.x;
if ((width == 0) && (geometry.x > 0))
width=msl_info->image[n]->columns+geometry.x;
}
if ((flags & YValue) != 0)
{
y=geometry.y;
if ((height == 0) && (geometry.y > 0))
height=msl_info->image[n]->rows+geometry.y;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
height = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
width = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
x = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
y = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
msl_info->image[n]->page.width=width;
msl_info->image[n]->page.height=height;
msl_info->image[n]->page.x=x;
msl_info->image[n]->page.y=y;
break;
}
else if (LocaleCompare((const char *) tag,"resample") == 0)
{
double
x_resolution,
y_resolution;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
x_resolution=DefaultResolution;
y_resolution=DefaultResolution;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'b':
{
if (LocaleCompare(keyword,"blur") == 0)
{
msl_info->image[n]->blur=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
ssize_t
flags;
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma*=geometry_info.rho;
x_resolution=geometry_info.rho;
y_resolution=geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x-resolution") == 0)
{
x_resolution=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y-resolution") == 0)
{
y_resolution=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
Resample image.
*/
{
double
factor;
Image
*resample_image;
factor=1.0;
if (msl_info->image[n]->units == PixelsPerCentimeterResolution)
factor=2.54;
width=(size_t) (x_resolution*msl_info->image[n]->columns/
(factor*(msl_info->image[n]->x_resolution == 0.0 ? DefaultResolution :
msl_info->image[n]->x_resolution))+0.5);
height=(size_t) (y_resolution*msl_info->image[n]->rows/
(factor*(msl_info->image[n]->y_resolution == 0.0 ? DefaultResolution :
msl_info->image[n]->y_resolution))+0.5);
resample_image=ResizeImage(msl_info->image[n],width,height,
msl_info->image[n]->filter,msl_info->image[n]->blur,
&msl_info->image[n]->exception);
if (resample_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=resample_image;
}
break;
}
if (LocaleCompare((const char *) tag,"resize") == 0)
{
double
blur;
FilterTypes
filter;
Image
*resize_image;
/*
Resize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
filter=UndefinedFilter;
blur=1.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filter") == 0)
{
option=ParseCommandOption(MagickFilterOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
filter=(FilterTypes) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"support") == 0)
{
blur=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
resize_image=ResizeImage(msl_info->image[n],geometry.width,
geometry.height,filter,blur,&msl_info->image[n]->exception);
if (resize_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=resize_image;
break;
}
if (LocaleCompare((const char *) tag,"roll") == 0)
{
Image
*roll_image;
/*
Roll image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
SetGeometry(msl_info->image[n],&geometry);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParsePageGeometry(msl_info->image[n],value,
&geometry,exception);
if ((flags & HeightValue) == 0)
geometry.height=geometry.width;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry.x=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry.y=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
roll_image=RollImage(msl_info->image[n],geometry.x,geometry.y,
&msl_info->image[n]->exception);
if (roll_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=roll_image;
break;
}
else if (LocaleCompare((const char *) tag,"roll") == 0)
{
/* init the values */
width=msl_info->image[n]->columns;
height=msl_info->image[n]->rows;
x = y = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
(void) ParseMetaGeometry(value,&x,&y,&width,&height);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
x = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
y = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
newImage=RollImage(msl_info->image[n], x, y, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
if (LocaleCompare((const char *) tag,"rotate") == 0)
{
Image
*rotate_image;
/*
Rotate image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
rotate_image=RotateImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (rotate_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=rotate_image;
break;
}
else if (LocaleCompare((const char *) tag,"rotate") == 0)
{
/* init the values */
double degrees = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
degrees = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
newImage=RotateImage(msl_info->image[n], degrees, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'S':
case 's':
{
if (LocaleCompare((const char *) tag,"sample") == 0)
{
Image
*sample_image;
/*
Sample image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
sample_image=SampleImage(msl_info->image[n],geometry.width,
geometry.height,&msl_info->image[n]->exception);
if (sample_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=sample_image;
break;
}
if (LocaleCompare((const char *) tag,"scale") == 0)
{
Image
*scale_image;
/*
Scale image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseRegionGeometry(msl_info->image[n],value,
&geometry,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
geometry.height=StringToUnsignedLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
geometry.width=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
scale_image=ScaleImage(msl_info->image[n],geometry.width,
geometry.height,&msl_info->image[n]->exception);
if (scale_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=scale_image;
break;
}
if (LocaleCompare((const char *) tag,"segment") == 0)
{
ColorspaceType
colorspace;
MagickBooleanType
verbose;
/*
Segment image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=1.0;
geometry_info.sigma=1.5;
colorspace=sRGBColorspace;
verbose=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"cluster-threshold") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
option=ParseCommandOption(MagickColorspaceOptions,
MagickFalse,value);
if (option < 0)
ThrowMSLException(OptionError,
"UnrecognizedColorspaceType",value);
colorspace=(ColorspaceType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.5;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"smoothing-threshold") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SegmentImage(msl_info->image[n],colorspace,verbose,
geometry_info.rho,geometry_info.sigma);
break;
}
else if (LocaleCompare((const char *) tag, "set") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"clip-mask") == 0)
{
for (j=0; j < msl_info->n; j++)
{
const char
*property;
property=GetImageProperty(msl_info->attributes[j],"id");
if (LocaleCompare(property,value) == 0)
{
SetImageMask(msl_info->image[n],msl_info->image[j]);
break;
}
}
break;
}
if (LocaleCompare(keyword,"clip-path") == 0)
{
for (j=0; j < msl_info->n; j++)
{
const char
*property;
property=GetImageProperty(msl_info->attributes[j],"id");
if (LocaleCompare(property,value) == 0)
{
SetImageClipMask(msl_info->image[n],msl_info->image[j]);
break;
}
}
break;
}
if (LocaleCompare(keyword,"colorspace") == 0)
{
ssize_t
colorspace;
colorspace=(ColorspaceType) ParseCommandOption(
MagickColorspaceOptions,MagickFalse,value);
if (colorspace < 0)
ThrowMSLException(OptionError,"UnrecognizedColorspace",
value);
(void) TransformImageColorspace(msl_info->image[n],
(ColorspaceType) colorspace);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
flags=ParseGeometry(value,&geometry_info);
msl_info->image[n]->x_resolution=geometry_info.rho;
msl_info->image[n]->y_resolution=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
msl_info->image[n]->y_resolution=
msl_info->image[n]->x_resolution;
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword, "opacity") == 0)
{
ssize_t opac = OpaqueOpacity,
len = (ssize_t) strlen( value );
if (value[len-1] == '%') {
char tmp[100];
(void) CopyMagickString(tmp,value,len);
opac = StringToLong( tmp );
opac = (int)(QuantumRange * ((float)opac/100));
} else
opac = StringToLong( value );
(void) SetImageOpacity( msl_info->image[n], (Quantum) opac );
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword, "page") == 0)
{
char
page[MaxTextExtent];
const char
*image_option;
MagickStatusType
flags;
RectangleInfo
geometry;
(void) ResetMagickMemory(&geometry,0,sizeof(geometry));
image_option=GetImageArtifact(msl_info->image[n],"page");
if (image_option != (const char *) NULL)
flags=ParseAbsoluteGeometry(image_option,&geometry);
flags=ParseAbsoluteGeometry(value,&geometry);
(void) FormatLocaleString(page,MaxTextExtent,"%.20gx%.20g",
(double) geometry.width,(double) geometry.height);
if (((flags & XValue) != 0) || ((flags & YValue) != 0))
(void) FormatLocaleString(page,MaxTextExtent,
"%.20gx%.20g%+.20g%+.20g",(double) geometry.width,
(double) geometry.height,(double) geometry.x,(double)
geometry.y);
(void) SetImageOption(msl_info->image_info[n],keyword,page);
msl_info->image_info[n]->page=GetPageGeometry(page);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
(void) SetImageProperty(msl_info->image[n],keyword,value);
break;
}
}
}
break;
}
if (LocaleCompare((const char *) tag,"shade") == 0)
{
Image
*shade_image;
MagickBooleanType
gray;
/*
Shade image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
gray=MagickFalse;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"azimuth") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'E':
case 'e':
{
if (LocaleCompare(keyword,"elevation") == 0)
{
geometry_info.sigma=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
if (LocaleCompare(keyword,"gray") == 0)
{
option=ParseCommandOption(MagickBooleanOptions,MagickFalse,
value);
if (option < 0)
ThrowMSLException(OptionError,"UnrecognizedNoiseType",
value);
gray=(MagickBooleanType) option;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shade_image=ShadeImage(msl_info->image[n],gray,geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (shade_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shade_image;
break;
}
if (LocaleCompare((const char *) tag,"shadow") == 0)
{
Image
*shadow_image;
/*
Shear image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'O':
case 'o':
{
if (LocaleCompare(keyword,"opacity") == 0)
{
geometry_info.rho=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry_info.xi=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry_info.psi=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shadow_image=ShadowImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5),(ssize_t)
ceil(geometry_info.psi-0.5),&msl_info->image[n]->exception);
if (shadow_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shadow_image;
break;
}
if (LocaleCompare((const char *) tag,"sharpen") == 0)
{
double radius = 0.0,
sigma = 1.0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
/*
NOTE: sharpen can have no attributes, since we use all the defaults!
*/
if (attributes != (const xmlChar **) NULL)
{
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'R':
case 'r':
{
if (LocaleCompare(keyword, "radius") == 0)
{
radius = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"sigma") == 0)
{
sigma = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
}
/*
sharpen image.
*/
{
Image
*newImage;
newImage=SharpenImage(msl_info->image[n],radius,sigma,&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
else if (LocaleCompare((const char *) tag,"shave") == 0)
{
/* init the values */
width = height = 0;
x = y = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
(void) ParseMetaGeometry(value,&x,&y,&width,&height);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'H':
case 'h':
{
if (LocaleCompare(keyword,"height") == 0)
{
height = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'W':
case 'w':
{
if (LocaleCompare(keyword,"width") == 0)
{
width = StringToLong( value );
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
Image
*newImage;
RectangleInfo
rectInfo;
rectInfo.height = height;
rectInfo.width = width;
rectInfo.x = x;
rectInfo.y = y;
newImage=ShaveImage(msl_info->image[n], &rectInfo,
&msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
}
break;
}
if (LocaleCompare((const char *) tag,"shear") == 0)
{
Image
*shear_image;
/*
Shear image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword, "fill") == 0)
{
(void) QueryColorDatabase(value,
&msl_info->image[n]->background_color,exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'X':
case 'x':
{
if (LocaleCompare(keyword,"x") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'Y':
case 'y':
{
if (LocaleCompare(keyword,"y") == 0)
{
geometry_info.sigma=StringToLong(value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
shear_image=ShearImage(msl_info->image[n],geometry_info.rho,
geometry_info.sigma,&msl_info->image[n]->exception);
if (shear_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=shear_image;
break;
}
if (LocaleCompare((const char *) tag,"signature") == 0)
{
/*
Signature image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SignatureImage(msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"solarize") == 0)
{
/*
Solarize image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
geometry_info.rho=QuantumRange/2.0;
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'T':
case 't':
{
if (LocaleCompare(keyword,"threshold") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SolarizeImage(msl_info->image[n],geometry_info.rho);
break;
}
if (LocaleCompare((const char *) tag,"spread") == 0)
{
Image
*spread_image;
/*
Spread image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'R':
case 'r':
{
if (LocaleCompare(keyword,"radius") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
spread_image=SpreadImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (spread_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=spread_image;
break;
}
else if (LocaleCompare((const char *) tag,"stegano") == 0)
{
Image *
watermark = (Image*) NULL;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
{
for (j=0; j<msl_info->n;j++)
{
const char *
theAttr = GetImageProperty(msl_info->attributes[j], "id");
if (theAttr && LocaleCompare(theAttr, value) == 0)
{
watermark = msl_info->image[j];
break;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
if ( watermark != (Image*) NULL )
{
Image
*newImage;
newImage=SteganoImage(msl_info->image[n], watermark, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
} else
ThrowMSLException(OptionError,"MissingWatermarkImage",keyword);
}
else if (LocaleCompare((const char *) tag,"stereo") == 0)
{
Image *
stereoImage = (Image*) NULL;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
{
for (j=0; j<msl_info->n;j++)
{
const char *
theAttr = GetImageProperty(msl_info->attributes[j], "id");
if (theAttr && LocaleCompare(theAttr, value) == 0)
{
stereoImage = msl_info->image[j];
break;
}
}
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
if ( stereoImage != (Image*) NULL )
{
Image
*newImage;
newImage=StereoImage(msl_info->image[n], stereoImage, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
} else
ThrowMSLException(OptionError,"Missing stereo image",keyword);
}
if (LocaleCompare((const char *) tag,"strip") == 0)
{
/*
Strip image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
}
(void) StripImage(msl_info->image[n]);
break;
}
if (LocaleCompare((const char *) tag,"swap") == 0)
{
Image
*p,
*q,
*swap;
ssize_t
index,
swap_index;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
index=(-1);
swap_index=(-2);
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"indexes") == 0)
{
flags=ParseGeometry(value,&geometry_info);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) == 0)
swap_index=(ssize_t) geometry_info.sigma;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
/*
Swap images.
*/
p=GetImageFromList(msl_info->image[n],index);
q=GetImageFromList(msl_info->image[n],swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL))
{
ThrowMSLException(OptionError,"NoSuchImage",(const char *) tag);
break;
}
swap=CloneImage(p,0,0,MagickTrue,&p->exception);
ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,&q->exception));
ReplaceImageInList(&q,swap);
msl_info->image[n]=GetFirstImageInList(q);
break;
}
if (LocaleCompare((const char *) tag,"swirl") == 0)
{
Image
*swirl_image;
/*
Swirl image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"degrees") == 0)
{
geometry_info.rho=StringToDouble(value,
(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"geometry") == 0)
{
flags=ParseGeometry(value,&geometry_info);
if ((flags & SigmaValue) == 0)
geometry_info.sigma=1.0;
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
swirl_image=SwirlImage(msl_info->image[n],geometry_info.rho,
&msl_info->image[n]->exception);
if (swirl_image == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=swirl_image;
break;
}
if (LocaleCompare((const char *) tag,"sync") == 0)
{
/*
Sync image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) SyncImage(msl_info->image[n]);
break;
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'T':
case 't':
{
if (LocaleCompare((const char *) tag,"map") == 0)
{
Image
*texture_image;
/*
Texture image.
*/
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
texture_image=NewImageList();
if (attributes != (const xmlChar **) NULL)
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
attribute=InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]);
CloneString(&value,attribute);
switch (*keyword)
{
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"image") == 0)
for (j=0; j < msl_info->n; j++)
{
const char
*attribute;
attribute=GetImageProperty(msl_info->attributes[j],"id");
if ((attribute != (const char *) NULL) &&
(LocaleCompare(attribute,value) == 0))
{
texture_image=CloneImage(msl_info->image[j],0,0,
MagickFalse,exception);
break;
}
}
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",
keyword);
break;
}
}
}
(void) TextureImage(msl_info->image[n],texture_image);
texture_image=DestroyImage(texture_image);
break;
}
else if (LocaleCompare((const char *) tag,"threshold") == 0)
{
/* init the values */
double threshold = 0;
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'T':
case 't':
{
if (LocaleCompare(keyword,"threshold") == 0)
{
threshold = StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
/*
process image.
*/
{
BilevelImageChannel(msl_info->image[n],
(ChannelType) ((ssize_t) (CompositeChannels &~ (ssize_t) OpacityChannel)),
threshold);
break;
}
}
else if (LocaleCompare((const char *) tag, "transparent") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'C':
case 'c':
{
if (LocaleCompare(keyword,"color") == 0)
{
MagickPixelPacket
target;
(void) QueryMagickColor(value,&target,exception);
(void) TransparentPaintImage(msl_info->image[n],&target,
TransparentOpacity,MagickFalse);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
}
break;
}
else if (LocaleCompare((const char *) tag, "trim") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag);
break;
}
/* no attributes here */
/* process the image */
{
Image
*newImage;
RectangleInfo
rectInfo;
/* all zeros on a crop == trim edges! */
rectInfo.height = rectInfo.width = 0;
rectInfo.x = rectInfo.y = 0;
newImage=CropImage(msl_info->image[n],&rectInfo, &msl_info->image[n]->exception);
if (newImage == (Image *) NULL)
break;
msl_info->image[n]=DestroyImage(msl_info->image[n]);
msl_info->image[n]=newImage;
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
case 'W':
case 'w':
{
if (LocaleCompare((const char *) tag,"write") == 0)
{
if (msl_info->image[n] == (Image *) NULL)
{
ThrowMSLException(OptionError,"NoImagesDefined",
(const char *) tag);
break;
}
if (attributes == (const xmlChar **) NULL)
break;
for (i=0; (attributes[i] != (const xmlChar *) NULL); i++)
{
keyword=(const char *) attributes[i++];
CloneString(&value,InterpretImageProperties(msl_info->image_info[n],
msl_info->attributes[n],(const char *) attributes[i]));
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"filename") == 0)
{
(void) CopyMagickString(msl_info->image[n]->filename,value,
MaxTextExtent);
break;
}
(void) SetMSLAttributes(msl_info,keyword,value);
}
default:
{
(void) SetMSLAttributes(msl_info,keyword,value);
break;
}
}
}
/* process */
{
*msl_info->image_info[n]->magick='\0';
(void) WriteImage(msl_info->image_info[n], msl_info->image[n]);
break;
}
}
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag);
break;
}
}
if ( value != NULL )
value=DestroyString(value);
exception=DestroyExceptionInfo(exception);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," )");
}
static void MSLEndElement(void *context,const xmlChar *tag)
{
ssize_t
n;
MSLInfo
*msl_info;
/*
Called when the end of an element has been detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.endElement(%s)",
tag);
msl_info=(MSLInfo *) context;
n=msl_info->n;
switch (*tag)
{
case 'C':
case 'c':
{
if (LocaleCompare((const char *) tag,"comment") == 0 )
{
(void) DeleteImageProperty(msl_info->image[n],"comment");
if (msl_info->content == (char *) NULL)
break;
StripString(msl_info->content);
(void) SetImageProperty(msl_info->image[n],"comment",
msl_info->content);
break;
}
break;
}
case 'G':
case 'g':
{
if (LocaleCompare((const char *) tag, "group") == 0 )
{
if (msl_info->group_info[msl_info->number_groups-1].numImages > 0 )
{
ssize_t i = (ssize_t)
(msl_info->group_info[msl_info->number_groups-1].numImages);
while ( i-- )
{
if (msl_info->image[msl_info->n] != (Image *) NULL)
msl_info->image[msl_info->n]=DestroyImage(msl_info->image[msl_info->n]);
msl_info->attributes[msl_info->n]=DestroyImage(msl_info->attributes[msl_info->n]);
msl_info->image_info[msl_info->n]=DestroyImageInfo(msl_info->image_info[msl_info->n]);
msl_info->n--;
}
}
msl_info->number_groups--;
}
break;
}
case 'I':
case 'i':
{
if (LocaleCompare((const char *) tag, "image") == 0)
MSLPopImage(msl_info);
break;
}
case 'L':
case 'l':
{
if (LocaleCompare((const char *) tag,"label") == 0 )
{
(void) DeleteImageProperty(msl_info->image[n],"label");
if (msl_info->content == (char *) NULL)
break;
StripString(msl_info->content);
(void) SetImageProperty(msl_info->image[n],"label",
msl_info->content);
break;
}
break;
}
case 'M':
case 'm':
{
if (LocaleCompare((const char *) tag, "msl") == 0 )
{
/*
This our base element.
at the moment we don't do anything special
but someday we might!
*/
}
break;
}
default:
break;
}
if (msl_info->content != (char *) NULL)
msl_info->content=DestroyString(msl_info->content);
}
static void MSLCharacters(void *context,const xmlChar *c,int length)
{
MSLInfo
*msl_info;
register char
*p;
register ssize_t
i;
/*
Receiving some characters from the parser.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.characters(%s,%d)",c,length);
msl_info=(MSLInfo *) context;
if (msl_info->content != (char *) NULL)
msl_info->content=(char *) ResizeQuantumMemory(msl_info->content,
strlen(msl_info->content)+length+MaxTextExtent,
sizeof(*msl_info->content));
else
{
msl_info->content=(char *) NULL;
if (~length >= (MaxTextExtent-1))
msl_info->content=(char *) AcquireQuantumMemory(length+MaxTextExtent,
sizeof(*msl_info->content));
if (msl_info->content != (char *) NULL)
*msl_info->content='\0';
}
if (msl_info->content == (char *) NULL)
return;
p=msl_info->content+strlen(msl_info->content);
for (i=0; i < length; i++)
*p++=c[i];
*p='\0';
}
static void MSLReference(void *context,const xmlChar *name)
{
MSLInfo
*msl_info;
xmlParserCtxtPtr
parser;
/*
Called when an entity reference is detected.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.reference(%s)",name);
msl_info=(MSLInfo *) context;
parser=msl_info->parser;
if (*name == '#')
(void) xmlAddChild(parser->node,xmlNewCharRef(msl_info->document,name));
else
(void) xmlAddChild(parser->node,xmlNewReference(msl_info->document,name));
}
static void MSLIgnorableWhitespace(void *context,const xmlChar *c,int length)
{
MSLInfo
*msl_info;
/*
Receiving some ignorable whitespaces from the parser.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.ignorableWhitespace(%.30s, %d)",c,length);
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLProcessingInstructions(void *context,const xmlChar *target,
const xmlChar *data)
{
MSLInfo
*msl_info;
/*
A processing instruction has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.processingInstruction(%s, %s)",
target,data);
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLComment(void *context,const xmlChar *value)
{
MSLInfo
*msl_info;
/*
A comment has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.comment(%s)",value);
msl_info=(MSLInfo *) context;
(void) msl_info;
}
static void MSLWarning(void *context,const char *format,...)
{
char
*message,
reason[MaxTextExtent];
MSLInfo
*msl_info;
va_list
operands;
/**
Display and format a warning messages, gives file, line, position and
extra parameters.
*/
va_start(operands,format);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.warning: ");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands);
msl_info=(MSLInfo *) context;
(void) msl_info;
#if !defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsprintf(reason,format,operands);
#else
(void) vsnprintf(reason,MaxTextExtent,format,operands);
#endif
message=GetExceptionMessage(errno);
ThrowMSLException(CoderError,reason,message);
message=DestroyString(message);
va_end(operands);
}
static void MSLError(void *context,const char *format,...)
{
char
reason[MaxTextExtent];
MSLInfo
*msl_info;
va_list
operands;
/*
Display and format a error formats, gives file, line, position and
extra parameters.
*/
va_start(operands,format);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," SAX.error: ");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),format,operands);
msl_info=(MSLInfo *) context;
(void) msl_info;
#if !defined(MAGICKCORE_HAVE_VSNPRINTF)
(void) vsprintf(reason,format,operands);
#else
(void) vsnprintf(reason,MaxTextExtent,format,operands);
#endif
ThrowMSLException(DelegateFatalError,reason,"SAX error");
va_end(operands);
}
static void MSLCDataBlock(void *context,const xmlChar *value,int length)
{
MSLInfo
*msl_info;
xmlNodePtr
child;
xmlParserCtxtPtr
parser;
/*
Called when a pcdata block has been parsed.
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.pcdata(%s, %d)",value,length);
msl_info=(MSLInfo *) context;
(void) msl_info;
parser=msl_info->parser;
child=xmlGetLastChild(parser->node);
if ((child != (xmlNodePtr) NULL) && (child->type == XML_CDATA_SECTION_NODE))
{
xmlTextConcat(child,value,length);
return;
}
(void) xmlAddChild(parser->node,xmlNewCDataBlock(parser->myDoc,value,length));
}
static void MSLExternalSubset(void *context,const xmlChar *name,
const xmlChar *external_id,const xmlChar *system_id)
{
MSLInfo
*msl_info;
xmlParserCtxt
parser_context;
xmlParserCtxtPtr
parser;
xmlParserInputPtr
input;
/*
Does this document has an external subset?
*/
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" SAX.externalSubset(%s %s %s)",name,
(external_id != (const xmlChar *) NULL ? (const char *) external_id : " "),
(system_id != (const xmlChar *) NULL ? (const char *) system_id : " "));
msl_info=(MSLInfo *) context;
(void) msl_info;
parser=msl_info->parser;
if (((external_id == NULL) && (system_id == NULL)) ||
((parser->validate == 0) || (parser->wellFormed == 0) ||
(msl_info->document == 0)))
return;
input=MSLResolveEntity(context,external_id,system_id);
if (input == NULL)
return;
(void) xmlNewDtd(msl_info->document,name,external_id,system_id);
parser_context=(*parser);
parser->inputTab=(xmlParserInputPtr *) xmlMalloc(5*sizeof(*parser->inputTab));
if (parser->inputTab == (xmlParserInputPtr *) NULL)
{
parser->errNo=XML_ERR_NO_MEMORY;
parser->input=parser_context.input;
parser->inputNr=parser_context.inputNr;
parser->inputMax=parser_context.inputMax;
parser->inputTab=parser_context.inputTab;
return;
}
parser->inputNr=0;
parser->inputMax=5;
parser->input=NULL;
xmlPushInput(parser,input);
(void) xmlSwitchEncoding(parser,xmlDetectCharEncoding(parser->input->cur,4));
if (input->filename == (char *) NULL)
input->filename=(char *) xmlStrdup(system_id);
input->line=1;
input->col=1;
input->base=parser->input->cur;
input->cur=parser->input->cur;
input->free=NULL;
xmlParseExternalSubset(parser,external_id,system_id);
while (parser->inputNr > 1)
(void) xmlPopInput(parser);
xmlFreeInputStream(parser->input);
xmlFree(parser->inputTab);
parser->input=parser_context.input;
parser->inputNr=parser_context.inputNr;
parser->inputMax=parser_context.inputMax;
parser->inputTab=parser_context.inputTab;
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickBooleanType ProcessMSLScript(const ImageInfo *image_info,
Image **image,ExceptionInfo *exception)
{
char
message[MaxTextExtent];
Image
*msl_image;
int
status;
ssize_t
n;
MSLInfo
msl_info;
xmlSAXHandler
sax_modules;
xmlSAXHandlerPtr
sax_handler;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(image != (Image **) NULL);
msl_image=AcquireImage(image_info);
status=OpenBlob(image_info,msl_image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
msl_image->filename);
msl_image=DestroyImageList(msl_image);
return(MagickFalse);
}
msl_image->columns=1;
msl_image->rows=1;
/*
Parse MSL file.
*/
(void) ResetMagickMemory(&msl_info,0,sizeof(msl_info));
msl_info.exception=exception;
msl_info.image_info=(ImageInfo **) AcquireMagickMemory(
sizeof(*msl_info.image_info));
msl_info.draw_info=(DrawInfo **) AcquireMagickMemory(
sizeof(*msl_info.draw_info));
/* top of the stack is the MSL file itself */
msl_info.image=(Image **) AcquireMagickMemory(sizeof(*msl_info.image));
msl_info.attributes=(Image **) AcquireMagickMemory(
sizeof(*msl_info.attributes));
msl_info.group_info=(MSLGroupInfo *) AcquireMagickMemory(
sizeof(*msl_info.group_info));
if ((msl_info.image_info == (ImageInfo **) NULL) ||
(msl_info.image == (Image **) NULL) ||
(msl_info.attributes == (Image **) NULL) ||
(msl_info.group_info == (MSLGroupInfo *) NULL))
ThrowFatalException(ResourceLimitFatalError,
"UnableToInterpretMSLImage");
*msl_info.image_info=CloneImageInfo(image_info);
*msl_info.draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL);
*msl_info.attributes=AcquireImage(image_info);
msl_info.group_info[0].numImages=0;
/* the first slot is used to point to the MSL file image */
*msl_info.image=msl_image;
if (*image != (Image *) NULL)
MSLPushImage(&msl_info,*image);
(void) xmlSubstituteEntitiesDefault(1);
(void) ResetMagickMemory(&sax_modules,0,sizeof(sax_modules));
sax_modules.internalSubset=MSLInternalSubset;
sax_modules.isStandalone=MSLIsStandalone;
sax_modules.hasInternalSubset=MSLHasInternalSubset;
sax_modules.hasExternalSubset=MSLHasExternalSubset;
sax_modules.resolveEntity=MSLResolveEntity;
sax_modules.getEntity=MSLGetEntity;
sax_modules.entityDecl=MSLEntityDeclaration;
sax_modules.notationDecl=MSLNotationDeclaration;
sax_modules.attributeDecl=MSLAttributeDeclaration;
sax_modules.elementDecl=MSLElementDeclaration;
sax_modules.unparsedEntityDecl=MSLUnparsedEntityDeclaration;
sax_modules.setDocumentLocator=MSLSetDocumentLocator;
sax_modules.startDocument=MSLStartDocument;
sax_modules.endDocument=MSLEndDocument;
sax_modules.startElement=MSLStartElement;
sax_modules.endElement=MSLEndElement;
sax_modules.reference=MSLReference;
sax_modules.characters=MSLCharacters;
sax_modules.ignorableWhitespace=MSLIgnorableWhitespace;
sax_modules.processingInstruction=MSLProcessingInstructions;
sax_modules.comment=MSLComment;
sax_modules.warning=MSLWarning;
sax_modules.error=MSLError;
sax_modules.fatalError=MSLError;
sax_modules.getParameterEntity=MSLGetParameterEntity;
sax_modules.cdataBlock=MSLCDataBlock;
sax_modules.externalSubset=MSLExternalSubset;
sax_handler=(&sax_modules);
msl_info.parser=xmlCreatePushParserCtxt(sax_handler,&msl_info,(char *) NULL,0,
msl_image->filename);
while (ReadBlobString(msl_image,message) != (char *) NULL)
{
n=(ssize_t) strlen(message);
if (n == 0)
continue;
status=xmlParseChunk(msl_info.parser,message,(int) n,MagickFalse);
if (status != 0)
break;
(void) xmlParseChunk(msl_info.parser," ",1,MagickFalse);
if (msl_info.exception->severity >= ErrorException)
break;
}
if (msl_info.exception->severity == UndefinedException)
(void) xmlParseChunk(msl_info.parser," ",1,MagickTrue);
xmlFreeParserCtxt(msl_info.parser);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX");
msl_info.group_info=(MSLGroupInfo *) RelinquishMagickMemory(
msl_info.group_info);
if (*image == (Image *) NULL)
*image=(*msl_info.image);
if ((*msl_info.image)->exception.severity != UndefinedException)
return(MagickFalse);
return(MagickTrue);
}
static Image *ReadMSLImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=(Image *) NULL;
(void) ProcessMSLScript(image_info,&image,exception);
return(GetFirstImageInList(image));
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMSLImage() adds attributes for the MSL image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMSLImage method is:
%
% size_t RegisterMSLImage(void)
%
*/
ModuleExport size_t RegisterMSLImage(void)
{
MagickInfo
*entry;
#if defined(MAGICKCORE_XML_DELEGATE)
xmlInitParser();
#endif
entry=SetMagickInfo("MSL");
#if defined(MAGICKCORE_XML_DELEGATE)
entry->decoder=(DecodeImageHandler *) ReadMSLImage;
entry->encoder=(EncodeImageHandler *) WriteMSLImage;
#endif
entry->format_type=ImplicitFormatType;
entry->description=ConstantString("Magick Scripting Language");
entry->module=ConstantString("MSL");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
#if defined(MAGICKCORE_XML_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t M S L A t t r i b u t e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetMSLAttributes() ...
%
% The format of the SetMSLAttributes method is:
%
% MagickBooleanType SetMSLAttributes(MSLInfo *msl_info,
% const char *keyword,const char *value)
%
% A description of each parameter follows:
%
% o msl_info: the MSL info.
%
% o keyword: the keyword.
%
% o value: the value.
%
*/
static MagickBooleanType SetMSLAttributes(MSLInfo *msl_info,const char *keyword,
const char *value)
{
Image
*attributes;
DrawInfo
*draw_info;
ExceptionInfo
*exception;
GeometryInfo
geometry_info;
Image
*image;
ImageInfo
*image_info;
int
flags;
ssize_t
n;
assert(msl_info != (MSLInfo *) NULL);
if (keyword == (const char *) NULL)
return(MagickTrue);
if (value == (const char *) NULL)
return(MagickTrue);
exception=msl_info->exception;
n=msl_info->n;
attributes=msl_info->attributes[n];
image_info=msl_info->image_info[n];
draw_info=msl_info->draw_info[n];
image=msl_info->image[n];
switch (*keyword)
{
case 'A':
case 'a':
{
if (LocaleCompare(keyword,"adjoin") == 0)
{
ssize_t
adjoin;
adjoin=ParseCommandOption(MagickBooleanOptions,MagickFalse,value);
if (adjoin < 0)
ThrowMSLException(OptionError,"UnrecognizedType",value);
image_info->adjoin=(MagickBooleanType) adjoin;
break;
}
if (LocaleCompare(keyword,"alpha") == 0)
{
ssize_t
alpha;
alpha=ParseCommandOption(MagickAlphaOptions,MagickFalse,value);
if (alpha < 0)
ThrowMSLException(OptionError,"UnrecognizedType",value);
if (image != (Image *) NULL)
(void) SetImageAlphaChannel(image,(AlphaChannelType) alpha);
break;
}
if (LocaleCompare(keyword,"antialias") == 0)
{
ssize_t
antialias;
antialias=ParseCommandOption(MagickBooleanOptions,MagickFalse,value);
if (antialias < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",value);
image_info->antialias=(MagickBooleanType) antialias;
break;
}
if (LocaleCompare(keyword,"area-limit") == 0)
{
MagickSizeType
limit;
limit=MagickResourceInfinity;
if (LocaleCompare(value,"unlimited") != 0)
limit=(MagickSizeType) StringToDoubleInterval(value,100.0);
(void) SetMagickResourceLimit(AreaResource,limit);
break;
}
if (LocaleCompare(keyword,"attenuate") == 0)
{
(void) SetImageOption(image_info,keyword,value);
break;
}
if (LocaleCompare(keyword,"authenticate") == 0)
{
(void) CloneString(&image_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'B':
case 'b':
{
if (LocaleCompare(keyword,"background") == 0)
{
(void) QueryColorDatabase(value,&image_info->background_color,
exception);
break;
}
if (LocaleCompare(keyword,"bias") == 0)
{
if (image == (Image *) NULL)
break;
image->bias=StringToDoubleInterval(value,(double) QuantumRange+1.0);
break;
}
if (LocaleCompare(keyword,"blue-primary") == 0)
{
if (image == (Image *) NULL)
break;
flags=ParseGeometry(value,&geometry_info);
image->chromaticity.blue_primary.x=geometry_info.rho;
image->chromaticity.blue_primary.y=geometry_info.sigma;
if ((flags & SigmaValue) == 0)
image->chromaticity.blue_primary.y=
image->chromaticity.blue_primary.x;
break;
}
if (LocaleCompare(keyword,"bordercolor") == 0)
{
(void) QueryColorDatabase(value,&image_info->border_color,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'D':
case 'd':
{
if (LocaleCompare(keyword,"density") == 0)
{
(void) CloneString(&image_info->density,value);
(void) CloneString(&draw_info->density,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"fill") == 0)
{
(void) QueryColorDatabase(value,&draw_info->fill,exception);
(void) SetImageOption(image_info,keyword,value);
break;
}
if (LocaleCompare(keyword,"filename") == 0)
{
(void) CopyMagickString(image_info->filename,value,MaxTextExtent);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gravity") == 0)
{
ssize_t
gravity;
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value);
if (gravity < 0)
ThrowMSLException(OptionError,"UnrecognizedGravityType",value);
(void) SetImageOption(image_info,keyword,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'I':
case 'i':
{
if (LocaleCompare(keyword,"id") == 0)
{
(void) SetImageProperty(attributes,keyword,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'M':
case 'm':
{
if (LocaleCompare(keyword,"magick") == 0)
{
(void) CopyMagickString(image_info->magick,value,MaxTextExtent);
break;
}
if (LocaleCompare(keyword,"mattecolor") == 0)
{
(void) QueryColorDatabase(value,&image_info->matte_color,
exception);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"pointsize") == 0)
{
image_info->pointsize=StringToDouble(value,(char **) NULL);
draw_info->pointsize=StringToDouble(value,(char **) NULL);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
case 'Q':
case 'q':
{
if (LocaleCompare(keyword,"quality") == 0)
{
image_info->quality=StringToLong(value);
if (image == (Image *) NULL)
break;
image->quality=StringToLong(value);
break;
}
break;
}
case 'S':
case 's':
{
if (LocaleCompare(keyword,"size") == 0)
{
(void) CloneString(&image_info->size,value);
break;
}
if (LocaleCompare(keyword,"stroke") == 0)
{
(void) QueryColorDatabase(value,&draw_info->stroke,exception);
(void) SetImageOption(image_info,keyword,value);
break;
}
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
default:
{
ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword);
break;
}
}
return(MagickTrue);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMSLImage() removes format registrations made by the
% MSL module from the list of supported formats.
%
% The format of the UnregisterMSLImage method is:
%
% UnregisterMSLImage(void)
%
*/
ModuleExport void UnregisterMSLImage(void)
{
(void) UnregisterMagickInfo("MSL");
#if defined(MAGICKCORE_XML_DELEGATE)
xmlCleanupParser();
#endif
}
#if defined(MAGICKCORE_XML_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M S L I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMSLImage() writes an image to a file in MVG image format.
%
% The format of the WriteMSLImage method is:
%
% MagickBooleanType WriteMSLImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteMSLImage(const ImageInfo *image_info,Image *image)
{
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
(void) ReferenceImage(image);
(void) ProcessMSLScript(image_info,&image,&image->exception);
return(MagickTrue);
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4789_1 |
crossvul-cpp_data_bad_4717_2 | /*
* verify.c:
*
* Author:
* Mono Project (http://www.mono-project.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
*/
#include <config.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/verify.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/opcodes.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/reflection.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/metadata.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/security-manager.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/mono-basic-block.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/monobitset.h>
#include <string.h>
#include <signal.h>
#include <ctype.h>
static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
static gboolean verify_all = FALSE;
/*
* Set the desired level of checks for the verfier.
*
*/
void
mono_verifier_set_mode (MiniVerifierMode mode)
{
verifier_mode = mode;
}
void
mono_verifier_enable_verify_all ()
{
verify_all = TRUE;
}
#ifndef DISABLE_VERIFIER
/*
* Pull the list of opcodes
*/
#define OPDEF(a,b,c,d,e,f,g,h,i,j) \
a = i,
enum {
#include "mono/cil/opcode.def"
LAST = 0xff
};
#undef OPDEF
#ifdef MONO_VERIFIER_DEBUG
#define VERIFIER_DEBUG(code) do { code } while (0)
#else
#define VERIFIER_DEBUG(code)
#endif
//////////////////////////////////////////////////////////////////
#define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
#define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
#define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
#define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
#define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
#define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = __status; \
vinfo->info.message = ( __msg ); \
vinfo->exception_type = (__exception); \
(__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
} while (0)
//TODO support MONO_VERIFY_REPORT_ALL_ERRORS
#define ADD_VERIFY_ERROR(__ctx, __msg) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE(__ctx, __msg) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define ADD_VERIFY_ERROR2(__ctx, __msg, __exception) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
#define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
#if SIZEOF_VOID_P == 4
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
#else
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
#endif
#define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
#define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
/*Flags to be used with ILCodeDesc::flags */
enum {
/*Instruction has not been processed.*/
IL_CODE_FLAG_NOT_PROCESSED = 0,
/*Instruction was decoded by mono_method_verify loop.*/
IL_CODE_FLAG_SEEN = 1,
/*Instruction was target of a branch or is at a protected block boundary.*/
IL_CODE_FLAG_WAS_TARGET = 2,
/*Used by stack_init to avoid double initialize each entry.*/
IL_CODE_FLAG_STACK_INITED = 4,
/*Used by merge_stacks to decide if it should just copy the eval stack.*/
IL_CODE_STACK_MERGED = 8,
/*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
IL_CODE_DELEGATE_SEQUENCE = 0x10,
/*This is a delegate created from a ldftn to a non final virtual method*/
IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
/*This is a call to a non final virtual method*/
IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
};
typedef enum {
RESULT_VALID,
RESULT_UNVERIFIABLE,
RESULT_INVALID
} verify_result_t;
typedef struct {
MonoType *type;
int stype;
MonoMethod *method;
} ILStackDesc;
typedef struct {
ILStackDesc *stack;
guint16 size, max_size;
guint16 flags;
} ILCodeDesc;
typedef struct {
int max_args;
int max_stack;
int verifiable;
int valid;
int level;
int code_size;
ILCodeDesc *code;
ILCodeDesc eval;
MonoType **params;
GSList *list;
/*Allocated fnptr MonoType that should be freed by us.*/
GSList *funptrs;
/*Type dup'ed exception types from catch blocks.*/
GSList *exception_types;
int num_locals;
MonoType **locals;
/*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
int target;
guint32 ip_offset;
MonoMethodSignature *signature;
MonoMethodHeader *header;
MonoGenericContext *generic_context;
MonoImage *image;
MonoMethod *method;
/*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0"
*on a method that creates a delegate for a non-final virtual method using ldftn*/
gboolean has_this_store;
/*This flag is used to control if the contructor of the parent class has been called.
*If the this pointer is pushed on the eval stack and it's a reference type constructor and
* super_ctor_called is false, the uninitialized flag is set on the pushed value.
*
* Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
* the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
*/
gboolean super_ctor_called;
guint32 prefix_set;
gboolean has_flags;
MonoType *constrained_type;
} VerifyContext;
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
static int
get_stack_type (MonoType *type);
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn);
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
//////////////////////////////////////////////////////////////////
enum {
TYPE_INV = 0, /* leave at 0. */
TYPE_I4 = 1,
TYPE_I8 = 2,
TYPE_NATIVE_INT = 3,
TYPE_R8 = 4,
/* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/
TYPE_PTR = 5,
/* value types and classes */
TYPE_COMPLEX = 6,
/* Number of types, used to define the size of the tables*/
TYPE_MAX = 6,
/* Used by tables to signal that a result is not verifiable*/
NON_VERIFIABLE_RESULT = 0x80,
/*Mask used to extract just the type, excluding flags */
TYPE_MASK = 0x0F,
/* The stack type is a managed pointer, unmask the value to res */
POINTER_MASK = 0x100,
/*Stack type with the pointer mask*/
RAW_TYPE_MASK = 0x10F,
/* Controlled Mutability Manager Pointer */
CMMP_MASK = 0x200,
/* The stack type is a null literal*/
NULL_LITERAL_MASK = 0x400,
/**Used by ldarg.0 and family to let delegate verification happens.*/
THIS_POINTER_MASK = 0x800,
/**Signals that this is a boxed value type*/
BOXED_MASK = 0x1000,
/*This is an unitialized this ref*/
UNINIT_THIS_MASK = 0x2000,
};
static const char* const
type_names [TYPE_MAX + 1] = {
"Invalid",
"Int32",
"Int64",
"Native Int",
"Float64",
"Native Pointer",
"Complex"
};
enum {
PREFIX_UNALIGNED = 1,
PREFIX_VOLATILE = 2,
PREFIX_TAIL = 4,
PREFIX_CONSTRAINED = 8,
PREFIX_READONLY = 16
};
//////////////////////////////////////////////////////////////////
#ifdef ENABLE_VERIFIER_STATS
#define MEM_ALLOC(amt) do { allocated_memory += (amt); working_set += (amt); } while (0)
#define MEM_FREE(amt) do { working_set -= (amt); } while (0)
static int allocated_memory;
static int working_set;
static int max_allocated_memory;
static int max_working_set;
static int total_allocated_memory;
static void
finish_collect_stats (void)
{
max_allocated_memory = MAX (max_allocated_memory, allocated_memory);
max_working_set = MAX (max_working_set, working_set);
total_allocated_memory += allocated_memory;
allocated_memory = working_set = 0;
}
static void
init_verifier_stats (void)
{
static gboolean inited;
if (!inited) {
inited = TRUE;
mono_counters_register ("Maximum memory allocated during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_allocated_memory);
mono_counters_register ("Maximum memory used during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_working_set);
mono_counters_register ("Total memory allocated for verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &total_allocated_memory);
}
}
#else
#define MEM_ALLOC(amt) do {} while (0)
#define MEM_FREE(amt) do { } while (0)
#define finish_collect_stats()
#define init_verifier_stats()
#endif
//////////////////////////////////////////////////////////////////
/*Token validation macros and functions */
#define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
#define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
#define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
#define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
#define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
#define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
#define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
#define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
#define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
#define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
/*
* Verify if @token refers to a valid row on int's table.
*/
static gboolean
token_bounds_check (MonoImage *image, guint32 token)
{
if (image->dynamic)
return mono_reflection_is_valid_dynamic_token ((MonoDynamicImage*)image, token);
return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token);
}
static MonoType *
mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
{
MonoType *res = g_new0 (MonoType, 1);
MEM_ALLOC (sizeof (MonoType));
//FIXME use mono_method_get_signature_full
res->data.method = mono_method_signature (method);
res->type = MONO_TYPE_FNPTR;
ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
return res;
}
/*
* mono_type_is_enum_type:
*
* Returns TRUE if @type is an enum type.
*/
static gboolean
mono_type_is_enum_type (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return TRUE;
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return TRUE;
return FALSE;
}
/*
* mono_type_is_value_type:
*
* Returns TRUE if @type is named after @namespace.@name.
*
*/
static gboolean
mono_type_is_value_type (MonoType *type, const char *namespace, const char *name)
{
return type->type == MONO_TYPE_VALUETYPE &&
!strcmp (namespace, type->data.klass->name_space) &&
!strcmp (name, type->data.klass->name);
}
/*
* Returns TURE if @type is VAR or MVAR
*/
static gboolean
mono_type_is_generic_argument (MonoType *type)
{
return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
}
/*
* mono_type_get_underlying_type_any:
*
* This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
*
* Returns the underlying type of @type regardless if it is byref or not.
*/
static MonoType*
mono_type_get_underlying_type_any (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return mono_class_enum_basetype (type->data.klass);
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return mono_class_enum_basetype (type->data.generic_class->container_class);
return type;
}
static G_GNUC_UNUSED const char*
mono_type_get_stack_name (MonoType *type)
{
return type_names [get_stack_type (type) & TYPE_MASK];
}
#define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
#define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
static gboolean
mono_method_is_constructor (MonoMethod *method)
{
return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
!(method->flags & CTOR_INVALID_FLAGS) &&
!strcmp (".ctor", method->name));
}
static gboolean
mono_class_has_default_constructor (MonoClass *klass)
{
MonoMethod *method;
int i;
mono_class_setup_methods (klass);
if (klass->exception_type)
return FALSE;
for (i = 0; i < klass->method.count; ++i) {
method = klass->methods [i];
if (mono_method_is_constructor (method) &&
mono_method_signature (method) &&
mono_method_signature (method)->param_count == 0 &&
(method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
return TRUE;
}
return FALSE;
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
*/
static gboolean
mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context)
{
int i;
MonoGenericInst *inst;
switch (type->type) {
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
if (!context)
return FALSE;
inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst;
if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc)
return FALSE;
break;
case MONO_TYPE_SZARRAY:
return mono_type_is_valid_type_in_context (&type->data.klass->byval_arg, context);
case MONO_TYPE_ARRAY:
return mono_type_is_valid_type_in_context (&type->data.array->eklass->byval_arg, context);
case MONO_TYPE_PTR:
return mono_type_is_valid_type_in_context (type->data.type, context);
case MONO_TYPE_GENERICINST:
inst = type->data.generic_class->context.class_inst;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!mono_type_is_valid_type_in_context (inst->type_argv [i], context))
return FALSE;
break;
}
return TRUE;
}
/*This function returns NULL if the type is not instantiatable*/
static MonoType*
verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context)
{
MonoError error;
MonoType *result;
result = mono_class_inflate_generic_type_checked (type, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return NULL;
}
return result;
}
static gboolean
is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
MonoError error;
int i;
if (ginst->type_argc != gc->type_argc)
return FALSE;
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass *paramClass;
MonoClass **constraints;
if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
continue;
if (mono_type_is_generic_argument (ginst->type_argv [i]))
continue; //it's not our job to validate type variables
paramClass = mono_class_from_mono_type (ginst->type_argv [i]);
if (paramClass->exception_type != MONO_EXCEPTION_NONE)
return FALSE;
/*it's not safe to call mono_class_init from here*/
if (paramClass->generic_class && !paramClass->inited) {
if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
return FALSE;
}
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
return FALSE;
if (!param_info->constraints)
continue;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *inflated;
inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return FALSE;
}
ctr = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (!mono_class_is_assignable_from_slow (ctr, paramClass))
return FALSE;
}
}
return TRUE;
}
/*
* Return true if @candidate is constraint compatible with @target.
*
* This means that @candidate constraints are a super set of @target constaints
*/
static gboolean
mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoClass *candidate_param_class, MonoGenericContext *context)
{
MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
if ((tmask & cmask) != tmask)
return FALSE;
if (tinfo->constraints) {
MonoClass **target_class, **candidate_class;
for (target_class = tinfo->constraints; *target_class; ++target_class) {
MonoClass *tc;
MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
if (!inflated)
return FALSE;
tc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
/*
* A constraint from @target might inflate into @candidate itself and in that case we don't need
* check it's constraints since it satisfy the constraint by itself.
*/
if (mono_metadata_type_equal (&tc->byval_arg, &candidate_param_class->byval_arg))
continue;
if (!cinfo->constraints)
return FALSE;
for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
MonoClass *cc;
inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
if (!inflated)
return FALSE;
cc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (mono_class_is_assignable_from (tc, cc))
break;
}
if (!*candidate_class)
return FALSE;
}
}
return TRUE;
}
static MonoGenericParam*
verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
{
MonoGenericContainer *gc;
MonoMethod *method = ctx->method;
int num;
num = mono_type_get_generic_param_num (type);
if (type->type == MONO_TYPE_VAR) {
MonoClass *gtd = method->klass;
if (gtd->generic_class)
gtd = gtd->generic_class->container_class;
gc = gtd->generic_container;
} else { //MVAR
MonoMethod *gmd = method;
if (method->is_inflated)
gmd = ((MonoMethodInflated*)method)->declaring;
gc = mono_method_get_generic_container (gmd);
}
if (!gc)
return FALSE;
return mono_generic_container_get_param (gc, num);
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
* This means that it either
*/
static gboolean
is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
{
return mono_type_is_valid_type_in_context (type, ctx->generic_context);
}
static gboolean
is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
if (!is_valid_type_in_context (ctx, type))
return FALSE;
}
return TRUE;
}
static gboolean
generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
MonoGenericParam *target = mono_generic_container_get_param (gc, i);
MonoGenericParam *candidate;
MonoClass *candidate_class;
if (!mono_type_is_generic_argument (type))
continue;
if (!is_valid_type_in_context (ctx, type))
return FALSE;
candidate = verifier_get_generic_param_from_type (ctx, type);
candidate_class = mono_class_from_mono_type (type);
if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, candidate_class, context))
return FALSE;
}
return TRUE;
}
static gboolean
mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
}
static gboolean
mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = klass->generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = gklass->container_class->generic_container;
return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
}
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
if (!gc) /*non-generic inflated method - it's part of a generic type */
return TRUE;
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
return FALSE;
return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
}
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = klass->generic_class;
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = gklass->container_class->generic_container;
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst))
return FALSE;
return is_valid_generic_instantiation (gc, &gklass->context, ginst);
}
static gboolean
mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
{
MonoClass *klass;
if (type == NULL) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return FALSE;
}
if (!is_valid_type_in_context (ctx, type)) {
char *str = mono_type_full_name (type);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
type->type == MONO_TYPE_VAR ? "!" : "!!",
str,
type->type == MONO_TYPE_VAR ? "class" : "method",
ctx->ip_offset),
MONO_EXCEPTION_BAD_IMAGE);
g_free (str);
return FALSE;
}
klass = mono_class_from_mono_type (type);
mono_class_init (klass);
if (mono_loader_get_last_error () || klass->exception_type != MONO_EXCEPTION_NONE) {
if (klass->generic_class && !mono_class_is_valid_generic_instantiation (NULL, klass))
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
else
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
mono_loader_clear_error ();
return FALSE;
}
if (klass->generic_class && klass->generic_class->container_class->exception_type != MONO_EXCEPTION_NONE) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!klass->generic_class)
return TRUE;
if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!mono_class_repect_method_constraints (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s (generic args don't respect target's constraints) at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
return TRUE;
}
static verify_result_t
mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
{
if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
return RESULT_INVALID;
if (!method->is_inflated)
return RESULT_VALID;
if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset), MONO_EXCEPTION_UNVERIFIABLE_IL);
return RESULT_INVALID;
}
if (!mono_method_repect_method_constraints (ctx, method)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s (generic args don't respect target's constraints) at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset));
return RESULT_UNVERIFIABLE;
}
return RESULT_VALID;
}
static MonoClassField*
verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) {
MonoClassField *field;
MonoClass *klass = NULL;
if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
field = mono_field_from_token (ctx->image, token, &klass, ctx->generic_context);
if (!field || !field->parent || !klass || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load field from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
return NULL;
*out_klass = klass;
return field;
}
static MonoMethod*
verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
MonoMethod* method;
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid method token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
method = mono_get_method_full (ctx->image, token, NULL, ctx->generic_context);
if (!method || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load method from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
return NULL;
return method;
}
static MonoType*
verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
MonoType* type;
if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
type = mono_type_get_full (ctx->image, token, ctx->generic_context);
if (!type || mono_loader_get_last_error ()) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load type from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
mono_loader_clear_error ();
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, type))
return NULL;
return type;
}
/* stack_slot_get_type:
*
* Returns the stack type of @value. This value includes POINTER_MASK.
*
* Use this function to checks that account for a managed pointer.
*/
static gint32
stack_slot_get_type (ILStackDesc *value)
{
return value->stype & RAW_TYPE_MASK;
}
/* stack_slot_get_underlying_type:
*
* Returns the stack type of @value. This value does not include POINTER_MASK.
*
* Use this function is cases where the fact that the value could be a managed pointer is
* irrelevant. For example, field load doesn't care about this fact of type on stack.
*/
static gint32
stack_slot_get_underlying_type (ILStackDesc *value)
{
return value->stype & TYPE_MASK;
}
/* stack_slot_is_managed_pointer:
*
* Returns TRUE is @value is a managed pointer.
*/
static gboolean
stack_slot_is_managed_pointer (ILStackDesc *value)
{
return (value->stype & POINTER_MASK) == POINTER_MASK;
}
/* stack_slot_is_managed_mutability_pointer:
*
* Returns TRUE is @value is a managed mutability pointer.
*/
static G_GNUC_UNUSED gboolean
stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
{
return (value->stype & CMMP_MASK) == CMMP_MASK;
}
/* stack_slot_is_null_literal:
*
* Returns TRUE is @value is the null literal.
*/
static gboolean
stack_slot_is_null_literal (ILStackDesc *value)
{
return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
}
/* stack_slot_is_this_pointer:
*
* Returns TRUE is @value is the this literal
*/
static gboolean
stack_slot_is_this_pointer (ILStackDesc *value)
{
return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
}
/* stack_slot_is_boxed_value:
*
* Returns TRUE is @value is a boxed value
*/
static gboolean
stack_slot_is_boxed_value (ILStackDesc *value)
{
return (value->stype & BOXED_MASK) == BOXED_MASK;
}
static const char *
stack_slot_get_name (ILStackDesc *value)
{
return type_names [value->stype & TYPE_MASK];
}
#define APPEND_WITH_PREDICATE(PRED,NAME) do {\
if (PRED (value)) { \
if (!first) \
g_string_append (str, ", "); \
g_string_append (str, NAME); \
first = FALSE; \
} } while (0)
static char*
stack_slot_stack_type_full_name (ILStackDesc *value)
{
GString *str = g_string_new ("");
char *result;
gboolean has_pred = FALSE, first = TRUE;
if ((value->stype & TYPE_MASK) != value->stype) {
g_string_append(str, "[");
APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
has_pred = TRUE;
}
if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
if (!has_pred)
g_string_append(str, "[");
if (!first)
g_string_append (str, ", ");
g_string_append (str, "unboxed");
has_pred = TRUE;
}
if (has_pred)
g_string_append(str, "] ");
g_string_append (str, stack_slot_get_name (value));
result = str->str;
g_string_free (str, FALSE);
return result;
}
static char*
stack_slot_full_name (ILStackDesc *value)
{
char *type_name = mono_type_full_name (value->type);
char *stack_name = stack_slot_stack_type_full_name (value);
char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
g_free (type_name);
g_free (stack_name);
return res;
}
//////////////////////////////////////////////////////////////////
void
mono_free_verify_list (GSList *list)
{
MonoVerifyInfoExtended *info;
GSList *tmp;
for (tmp = list; tmp; tmp = tmp->next) {
info = tmp->data;
g_free (info->info.message);
g_free (info);
}
g_slist_free (list);
}
#define ADD_ERROR(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = MONO_VERIFY_ERROR; \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_WARN(list,code,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = (code); \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_INVALID(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->status = MONO_VERIFY_ERROR; \
vinfo->message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
/*G_BREAKPOINT ();*/ \
goto invalid_cil; \
} while (0)
#define CHECK_STACK_UNDERFLOW(num) \
do { \
if (cur_stack < (num)) \
ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
} while (0)
#define CHECK_STACK_OVERFLOW() \
do { \
if (cur_stack >= max_stack) \
ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
} while (0)
static int
in_any_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 1;
}
return 0;
}
/*
* in_any_exception_block:
*
* Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
*/
static gboolean
in_any_exception_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return TRUE;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return TRUE;
}
return FALSE;
}
/*
* is_valid_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with br and brtrue/false.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
* The major diferent from other similiar functions is that branching into a
* finally/fault block is invalid instead of just unverifiable.
*/
static int
is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching into a finally block is invalid*/
if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
!MONO_OFFSET_IN_HANDLER (clause, offset) &&
MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 1;
}
return 0;
}
/*
* is_valid_cmp_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with binary comparison branching instruction, like beq, bge and similars.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
*
* The major diferences from other similar functions are that most errors lead to invalid
* code and only branching out of finally, filter or fault clauses is unverifiable.
*/
static int
is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching out of a handler or finally*/
if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
MONO_OFFSET_IN_HANDLER (clause, offset) &&
!MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 2;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 2;
}
return 0;
}
/*
* A leave can't escape a finally block
*/
static int
is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
return 0;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 0;
}
return 1;
}
/*
* A rethrow can't happen outside of a catch handler.
*/
static int
is_correct_rethrow (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 1;
}
return 0;
}
/*
* An endfinally can't happen outside of a finally/fault handler.
*/
static int
is_correct_endfinally (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
return 1;
}
return 0;
}
/*
* An endfilter can only happens inside a filter clause.
* In non-strict mode filter is allowed inside the handler clause too
*/
static MonoExceptionClause *
is_correct_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
continue;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return clause;
if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
return clause;
}
return NULL;
}
/*
* Non-strict endfilter can happens inside a try block or any handler block
*/
static int
is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
}
return 0;
}
static gboolean
is_valid_bool_arg (ILStackDesc *arg)
{
if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
return TRUE;
switch (stack_slot_get_underlying_type (arg)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_PTR:
return TRUE;
case TYPE_COMPLEX:
g_assert (arg->type);
switch (arg->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
return TRUE;
case MONO_TYPE_GENERICINST:
/*We need to check if the container class
* of the generic type is a valuetype, iow:
* is it a "class Foo<T>" or a "struct Foo<T>"?
*/
return !arg->type->data.generic_class->container_class->valuetype;
}
default:
return FALSE;
}
}
/*Type manipulation helper*/
/*Returns the byref version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byref (MonoType *type)
{
if (type->byref)
return type;
return &mono_class_from_mono_type (type)->this_arg;
}
/*Returns the byval version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byval (MonoType *type)
{
if (!type->byref)
return type;
return &mono_class_from_mono_type (type)->byval_arg;
}
static MonoType*
mono_type_from_stack_slot (ILStackDesc *slot)
{
if (stack_slot_is_managed_pointer (slot))
return mono_type_get_type_byref (slot->type);
return slot->type;
}
/*Stack manipulation code*/
static void
ensure_stack_size (ILCodeDesc *stack, int required)
{
int new_size = 8;
ILStackDesc *tmp;
if (required < stack->max_size)
return;
/* We don't have to worry about the exponential growth since stack_copy prune unused space */
new_size = MAX (8, MAX (required, stack->max_size * 2));
g_assert (new_size >= stack->size);
g_assert (new_size >= required);
tmp = g_new0 (ILStackDesc, new_size);
MEM_ALLOC (sizeof (ILStackDesc) * new_size);
if (stack->stack) {
if (stack->size)
memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
g_free (stack->stack);
MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
}
stack->stack = tmp;
stack->max_size = new_size;
}
static void
stack_init (VerifyContext *ctx, ILCodeDesc *state)
{
if (state->flags & IL_CODE_FLAG_STACK_INITED)
return;
state->size = state->max_size = 0;
state->flags |= IL_CODE_FLAG_STACK_INITED;
}
static void
stack_copy (ILCodeDesc *to, ILCodeDesc *from)
{
ensure_stack_size (to, from->size);
to->size = from->size;
/*stack copy happens at merge points, which have small stacks*/
if (from->size)
memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
}
static void
copy_stack_value (ILStackDesc *to, ILStackDesc *from)
{
to->stype = from->stype;
to->type = from->type;
to->method = from->method;
}
static int
check_underflow (VerifyContext *ctx, int size)
{
if (ctx->eval.size < size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
return 0;
}
return 1;
}
static int
check_overflow (VerifyContext *ctx)
{
if (ctx->eval.size >= ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
return 0;
}
return 1;
}
/*This reject out PTR, FNPTR and TYPEDBYREF*/
static gboolean
check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
{
if (stack_slot_get_type (value) == TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
/*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
static gboolean
check_unverifiable_type (VerifyContext *ctx, MonoType *type)
{
if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
static ILStackDesc *
stack_push (VerifyContext *ctx)
{
g_assert (ctx->eval.size < ctx->max_stack);
g_assert (ctx->eval.size <= ctx->eval.max_size);
ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
return & ctx->eval.stack [ctx->eval.size++];
}
static ILStackDesc *
stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
{
ILStackDesc *top = stack_push (ctx);
top->stype = stype;
top->type = type;
return top;
}
static ILStackDesc *
stack_pop (VerifyContext *ctx)
{
ILStackDesc *ret;
g_assert (ctx->eval.size > 0);
ret = ctx->eval.stack + --ctx->eval.size;
if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
return ret;
}
/* This function allows to safely pop an unititialized this ptr from
* the eval stack without marking the method as unverifiable.
*/
static ILStackDesc *
stack_pop_safe (VerifyContext *ctx)
{
g_assert (ctx->eval.size > 0);
return ctx->eval.stack + --ctx->eval.size;
}
/*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
static ILStackDesc*
stack_peek (VerifyContext *ctx, int distance)
{
g_assert (ctx->eval.size - distance > 0);
return ctx->eval.stack + (ctx->eval.size - 1 - distance);
}
static ILStackDesc *
stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
{
ILStackDesc *top = stack_push (ctx);
copy_stack_value (top, value);
return top;
}
/* Returns the MonoType associated with the token, or NULL if it is invalid.
*
* A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
* */
static MonoType*
get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
{
MonoType *type;
MonoClass *class;
if (!(type = verifier_load_type (ctx, token, opcode)))
return NULL;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_TYPEDBYREF)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
if (!(class = mono_class_from_mono_type (type)))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
if (class->generic_container && type->type != MONO_TYPE_GENERICINST)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the generic type definition in a boxable type position for %s at 0x%04x", opcode, ctx->ip_offset));
check_unverifiable_type (ctx, type);
return type;
}
/*operation result tables */
static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
};
static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
#ifdef MONO_VERIFIER_DEBUG
/*debug helpers */
static void
dump_stack_value (ILStackDesc *value)
{
printf ("[(%x)(%x)", value->type->type, value->stype);
if (stack_slot_is_this_pointer (value))
printf ("[this] ");
if (stack_slot_is_boxed_value (value))
printf ("[boxed] ");
if (stack_slot_is_null_literal (value))
printf ("[null] ");
if (stack_slot_is_managed_mutability_pointer (value))
printf ("Controled Mutability MP: ");
if (stack_slot_is_managed_pointer (value))
printf ("Managed Pointer to: ");
switch (stack_slot_get_underlying_type (value)) {
case TYPE_INV:
printf ("invalid type]");
return;
case TYPE_I4:
printf ("int32]");
return;
case TYPE_I8:
printf ("int64]");
return;
case TYPE_NATIVE_INT:
printf ("native int]");
return;
case TYPE_R8:
printf ("float64]");
return;
case TYPE_PTR:
printf ("unmanaged pointer]");
return;
case TYPE_COMPLEX:
switch (value->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE:
printf ("complex] (%s)", value->type->data.klass->name);
return;
case MONO_TYPE_STRING:
printf ("complex] (string)");
return;
case MONO_TYPE_OBJECT:
printf ("complex] (object)");
return;
case MONO_TYPE_SZARRAY:
printf ("complex] (%s [])", value->type->data.klass->name);
return;
case MONO_TYPE_ARRAY:
printf ("complex] (%s [%d %d %d])",
value->type->data.array->eklass->name,
value->type->data.array->rank,
value->type->data.array->numsizes,
value->type->data.array->numlobounds);
return;
case MONO_TYPE_GENERICINST:
printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
return;
case MONO_TYPE_VAR:
printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
case MONO_TYPE_MVAR:
printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
default: {
//should be a boxed value
char * name = mono_type_full_name (value->type);
printf ("complex] %s", name);
g_free (name);
return;
}
}
default:
printf ("unknown stack %x type]\n", value->stype);
g_assert_not_reached ();
}
}
static void
dump_stack_state (ILCodeDesc *state)
{
int i;
printf ("(%d) ", state->size);
for (i = 0; i < state->size; ++i)
dump_stack_value (state->stack + i);
printf ("\n");
}
#endif
/*Returns TRUE if candidate array type can be assigned to target.
*Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
*/
static gboolean
is_array_type_compatible (MonoType *target, MonoType *candidate)
{
MonoArrayType *left = target->data.array;
MonoArrayType *right = candidate->data.array;
g_assert (target->type == MONO_TYPE_ARRAY);
g_assert (candidate->type == MONO_TYPE_ARRAY);
if (left->rank != right->rank)
return FALSE;
return mono_class_is_assignable_from (left->eklass, right->eklass);
}
static int
get_stack_type (MonoType *type)
{
int mask = 0;
int type_kind = type->type;
if (type->byref)
mask = POINTER_MASK;
/*TODO handle CMMP_MASK */
handle_enum:
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
return TYPE_I4 | mask;
case MONO_TYPE_I:
case MONO_TYPE_U:
return TYPE_NATIVE_INT | mask;
/* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
return TYPE_PTR | mask;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
return TYPE_COMPLEX | mask;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return TYPE_I8 | mask;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
return TYPE_R8 | mask;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
type = mono_type_get_underlying_type_any (type);
if (!type)
return FALSE;
type_kind = type->type;
goto handle_enum;
} else {
return TYPE_COMPLEX | mask;
}
default:
return TYPE_INV;
}
}
/* convert MonoType to ILStackDesc format (stype) */
static gboolean
set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
{
int mask = 0;
int type_kind = type->type;
if (type->byref || take_addr)
mask = POINTER_MASK;
/* TODO handle CMMP_MASK */
handle_enum:
stack->type = type;
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
stack->stype = TYPE_I4 | mask;
break;
case MONO_TYPE_I:
case MONO_TYPE_U:
stack->stype = TYPE_NATIVE_INT | mask;
break;
/*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
stack->stype = TYPE_PTR | mask;
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
stack->stype = TYPE_COMPLEX | mask;
break;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
stack->stype = TYPE_I8 | mask;
break;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
stack->stype = TYPE_R8 | mask;
break;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
MonoType *utype = mono_type_get_underlying_type_any (type);
if (!utype) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
return FALSE;
}
type = utype;
type_kind = type->type;
goto handle_enum;
} else {
stack->stype = TYPE_COMPLEX | mask;
break;
}
default:
VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
return FALSE;
}
return TRUE;
}
/*
* init_stack_with_value_at_exception_boundary:
*
* Initialize the stack and push a given type.
* The instruction is marked as been on the exception boundary.
*/
static void
init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
{
MonoError error;
MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_get_full_name (klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
g_free (name);
mono_error_cleanup (&error);
return;
}
if (!ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
return;
}
stack_init (ctx, code);
ensure_stack_size (code, 1);
set_stack_value (ctx, code->stack, type, FALSE);
ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
code->size = 1;
code->flags |= IL_CODE_FLAG_WAS_TARGET;
if (mono_type_is_generic_argument (type))
code->stack->stype |= BOXED_MASK;
}
/*Verify if type 'candidate' can be stored in type 'target'.
*
* If strict, check for the underlying type and not the verification stack types
*/
static gboolean
verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
{
#define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
MonoType *original_candidate = candidate;
VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
/*only one is byref */
if (candidate->byref ^ target->byref) {
/* converting from native int to byref*/
if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
return TRUE;
}
return FALSE;
}
strict |= target->byref;
/*From now on we don't care about byref anymore, so it's ok to discard it here*/
candidate = mono_type_get_underlying_type_any (candidate);
handle_enum:
switch (target->type) {
case MONO_TYPE_VOID:
return candidate->type == MONO_TYPE_VOID;
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
case MONO_TYPE_I4:
case MONO_TYPE_U4: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
case MONO_TYPE_R4:
case MONO_TYPE_R8:
if (strict)
return candidate->type == target->type;
return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
case MONO_TYPE_I:
case MONO_TYPE_U: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_PTR:
if (candidate->type != MONO_TYPE_PTR)
return FALSE;
/* check the underlying type */
return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
case MONO_TYPE_FNPTR: {
MonoMethodSignature *left, *right;
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
left = mono_type_get_signature (target);
right = mono_type_get_signature (candidate);
return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
}
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (mono_class_is_nullable (target_klass)) {
if (!mono_class_is_nullable (candidate_klass))
return FALSE;
return target_klass == candidate_klass;
}
return mono_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_STRING:
return candidate->type == MONO_TYPE_STRING;
case MONO_TYPE_CLASS:
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
if (candidate->type == MONO_TYPE_VALUETYPE)
return FALSE;
/* If candidate is an enum it should return true for System.Enum and supertypes.
* That's why here we use the original type and not the underlying type.
*/
return mono_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_SZARRAY: {
MonoClass *left;
MonoClass *right;
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
left = mono_class_from_mono_type (target);
right = mono_class_from_mono_type (candidate);
return mono_class_is_assignable_from (left, right);
}
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_TYPEDBYREF:
return candidate->type == MONO_TYPE_TYPEDBYREF;
case MONO_TYPE_VALUETYPE: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (candidate->type == MONO_TYPE_CLASS)
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (target_klass == candidate_klass)
return TRUE;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
return FALSE;
}
case MONO_TYPE_VAR:
if (candidate->type != MONO_TYPE_VAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
case MONO_TYPE_MVAR:
if (candidate->type != MONO_TYPE_MVAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
default:
VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
return 1;
#undef IS_ONE_OF3
#undef IS_ONE_OF2
}
static gboolean
verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
{
return verify_type_compatibility_full (ctx, target, candidate, FALSE);
}
/*
* Returns the generic param bound to the context been verified.
*
*/
static MonoGenericParam*
get_generic_param (VerifyContext *ctx, MonoType *param)
{
guint16 param_num = mono_type_get_generic_param_num (param);
if (param->type == MONO_TYPE_VAR) {
if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
return NULL;
}
return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
}
/*param must be a MVAR */
if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
return NULL;
}
return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
}
static gboolean
recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level)
{
MonoType *constraint_type = &constraint_class->byval_arg;
if (recursion_level <= 0)
return FALSE;
if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE))
return TRUE;
if (mono_type_is_generic_argument (constraint_type)) {
MonoGenericParam *param = get_generic_param (ctx, constraint_type);
MonoClass **class;
if (!param)
return FALSE;
for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
if (recursive_boxed_constraint_type_check (ctx, type, *class, recursion_level - 1))
return TRUE;
}
}
return FALSE;
}
/*
* is_compatible_boxed_valuetype:
*
* Returns TRUE if @candidate / @stack is a valid boxed valuetype.
*
* @type The source type. It it tested to be of the proper type.
* @candidate type of the boxed valuetype.
* @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
* @strict if TRUE candidate must be boxed compatible to the target type
*
*/
static gboolean
is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
{
if (!stack_slot_is_boxed_value (stack))
return FALSE;
if (type->byref || candidate->byref)
return FALSE;
if (mono_type_is_generic_argument (candidate)) {
MonoGenericParam *param = get_generic_param (ctx, candidate);
MonoClass **class;
if (!param)
return FALSE;
for (class = mono_generic_param_info (param)->constraints; class && *class; ++class) {
/*256 should be enough since there can't be more than 255 generic arguments.*/
if (recursive_boxed_constraint_type_check (ctx, type, *class, 256))
return TRUE;
}
}
if (mono_type_is_generic_argument (type))
return FALSE;
if (!strict)
return TRUE;
return MONO_TYPE_IS_REFERENCE (type) && mono_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
}
static int
verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
{
MonoType *candidate = mono_type_from_stack_slot (stack);
if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
return TRUE;
if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
return TRUE;
if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
return FALSE;
if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
return FALSE;
if (drop_byref)
return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
return verify_type_compatibility_full (ctx, type, candidate, FALSE);
}
static int
verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
{
return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
}
static gboolean
mono_delegate_type_equal (MonoType *target, MonoType *candidate)
{
if (candidate->byref ^ target->byref)
return FALSE;
switch (target->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_TYPEDBYREF:
return candidate->type == target->type;
case MONO_TYPE_PTR:
return mono_delegate_type_equal (target->data.type, candidate->data.type);
case MONO_TYPE_FNPTR:
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
/*FIXME handle nullables and enum*/
return mono_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_CLASS:
return mono_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
case MONO_TYPE_SZARRAY:
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
return mono_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_VALUETYPE:
/*FIXME handle nullables and enum*/
return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
case MONO_TYPE_VAR:
return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
case MONO_TYPE_MVAR:
return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
default:
VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
}
static gboolean
mono_delegate_param_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (method, delegate);
}
static gboolean
mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (delegate, method);
}
/*
* mono_delegate_signature_equal:
*
* Compare two signatures in the way expected by delegates.
*
* This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
*
* FIXME can this function be eliminated and proper metadata functionality be used?
*/
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
{
int i;
int method_offset = is_static_ldftn ? 1 : 0;
if (delegate_sig->param_count + method_offset != method_sig->param_count)
return FALSE;
if (delegate_sig->call_convention != method_sig->call_convention)
return FALSE;
for (i = 0; i < delegate_sig->param_count; i++) {
MonoType *p1 = delegate_sig->params [i];
MonoType *p2 = method_sig->params [i + method_offset];
if (!mono_delegate_param_equal (p1, p2))
return FALSE;
}
if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
return FALSE;
return TRUE;
}
/*
* verify_ldftn_delegate:
*
* Verify properties of ldftn based delegates.
*/
static void
verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
MonoMethod *method = funptr->method;
/*ldftn non-final virtuals only allowed if method is not static,
* the object is a this arg (comes from a ldarg.0), and there is no starg.0.
* This rules doesn't apply if the object on stack is a boxed valuetype.
*/
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED) && !stack_slot_is_boxed_value (value)) {
/*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
/*current method must not be static*/
if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
/*value is the this pointer, loaded using ldarg.0 */
if (!stack_slot_is_this_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object argument, it is not the this pointer, to ldftn with virtual method at 0x%04x", ctx->ip_offset));
ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
}
}
/*
* verify_delegate_compatibility:
*
* Verify delegate creation sequence.
*
*/
static void
verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
#define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
#define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
MonoMethod *invoke, *method;
const guint8 *ip = ctx->header->code;
guint32 ip_offset = ctx->ip_offset;
gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
invoke = mono_get_delegate_invoke (delegate);
method = funptr->method;
if (!method || !mono_method_signature (method)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
if (!invoke || !mono_method_signature (invoke)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
if (is_static_ldftn)
is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Function pointer signature '%s' doesn't match delegate's signature '%s' at 0x%04x", fun_sig, invoke_sig, ctx->ip_offset));
g_free (fun_sig);
g_free (invoke_sig);
}
/*
* Delegate code sequences:
* [-6] ldftn token
* newobj ...
*
*
* [-7] dup
* [-6] ldvirtftn token
* newobj ...
*
* ldftn sequence:*/
if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
verify_ldftn_delegate (ctx, delegate, value, funptr);
} else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
}else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
}
ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
//general tests
if (is_first_arg_bound) {
if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_STATIC) {
if (!stack_slot_is_null_literal (value) && !is_first_arg_bound)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
}
}
if (stack_slot_get_type (value) != TYPE_COMPLEX)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
#undef IS_VALID_OPCODE
#undef IS_LOAD_FUN_PTR
}
/* implement the opcode checks*/
static void
push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
{
ILStackDesc *top;
if (arg >= ctx->max_args) {
if (take_addr)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->params [arg]);
if (ctx->params [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
top = stack_push (ctx);
if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
return;
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
if (take_addr)
ctx->has_this_store = TRUE;
else
top->stype |= THIS_POINTER_MASK;
if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
top->stype |= UNINIT_THIS_MASK;
}
}
}
static void
push_local (VerifyContext *ctx, guint32 arg, int take_addr)
{
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->locals [arg]);
if (ctx->locals [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), ctx->locals [arg], take_addr);
}
}
static void
store_arg (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->max_args) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
if (check_underflow (ctx, 1))
stack_pop (ctx);
return;
}
if (check_underflow (ctx, 1)) {
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
}
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
ctx->has_this_store = 1;
}
static void
store_local (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
return;
}
/*TODO verify definite assigment */
if (check_underflow (ctx, 1)) {
value = stack_pop(ctx);
if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
char *expected = mono_type_full_name (ctx->locals [arg]);
char *found = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
found,
arg,
expected,
ctx->ip_offset));
g_free (expected);
g_free (found);
}
}
}
/*FIXME add and sub needs special care here*/
static void
do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b, *top;
int idxa, idxb, complexMerge = 0;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a)) {
idxa = TYPE_PTR;
complexMerge = 1;
}
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b)) {
idxb = TYPE_PTR;
complexMerge = 2;
}
--idxa;
--idxb;
res = table [idxa][idxb];
VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
top = stack_push (ctx);
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction applyed to ill formed stack (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
copy_stack_value (top, a);
return;
}
if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction is not verifiable (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
res = res & ~NON_VERIFIABLE_RESULT;
}
if (complexMerge && res == TYPE_PTR) {
if (complexMerge == 1)
copy_stack_value (top, a);
else if (complexMerge == 2)
copy_stack_value (top, b);
/*
* There is no need to merge the type of two pointers.
* The only valid operation is subtraction, that returns a native
* int as result and can be used with any 2 pointer kinds.
* This is valid acording to Patition III 1.1.4
*/
} else
top->stype = res;
}
static void
do_boolean_branch_op (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
ILStackDesc *top;
VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (!is_valid_bool_arg (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Argument type %s not valid for brtrue/brfalse at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
check_unmanaged_pointer (ctx, top);
}
static gboolean
stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
{
return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
}
static void
do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
int target = ctx->ip_offset + delta;
VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1: /*FIXME use constants and not magic numbers.*/
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx,
g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
}
static void
do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
if (opcode == CEE_CGT_UN) {
if (stack_slot_get_type (a) == TYPE_COMPLEX && stack_slot_get_type (b) == TYPE_COMPLEX) {
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
return;
}
}
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
if(res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf("Compare instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
static void
do_ret (VerifyContext *ctx)
{
MonoType *ret = ctx->signature->ret;
VERIFIER_DEBUG ( printf ("checking ret\n"); );
if (ret->type != MONO_TYPE_VOID) {
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop(ctx);
if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature ret at 0x%04x", ctx->ip_offset));
return;
}
if (ret->byref || ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
}
if (ctx->eval.size > 0) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
}
if (in_any_block (ctx->header, ctx->ip_offset))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
}
/*
* FIXME we need to fix the case of a non-virtual instance method defined in the parent but call using a token pointing to a subclass.
* This is illegal but mono_get_method_full decoded it.
* TODO handle calling .ctor outside one or calling the .ctor for other class but super
*/
static void
do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual)
{
int param_count, i;
MonoMethodSignature *sig;
ILStackDesc *value;
MonoMethod *method;
gboolean virt_check_this = FALSE;
gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
if (!(method = verifier_load_method (ctx, method_token, virtual ? "callvirt" : "call")))
return;
if (virtual) {
CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
if (method->klass->valuetype) // && !constrained ???
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_STATIC))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !(method->klass->flags & TYPE_ATTRIBUTE_SEALED)) {
virt_check_this = TRUE;
ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
}
}
if (!(sig = mono_method_get_signature_full (method, ctx->image, method_token, ctx->generic_context)))
sig = mono_method_get_signature (method, ctx->image, method_token);
if (!sig) {
char *name = mono_type_get_full_name (method->klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x", name, method->name, ctx->ip_offset));
g_free (name);
return;
}
param_count = sig->param_count + sig->hasthis;
if (!check_underflow (ctx, param_count))
return;
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter with function signature: Calling method with signature (%s) but for argument %d there is a (%s) on stack at 0x%04x", sig_name, i, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset));
if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot pass a byref argument to a tail %s at 0x%04x", virtual ? "callvirt" : "call", ctx->ip_offset));
return;
}
}
if (sig->hasthis) {
MonoType *type = &method->klass->byval_arg;
ILStackDesc copy;
if (mono_method_is_constructor (method) && !method->klass->valuetype) {
if (!mono_method_is_constructor (ctx->method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
if (method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor to a type diferent that this or super at 0x%04x", ctx->ip_offset));
ctx->super_ctor_called = TRUE;
value = stack_pop_safe (ctx);
if ((value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
} else {
value = stack_pop (ctx);
}
copy_stack_value (©, value);
//TODO we should extract this to a 'drop_byref_argument' and use everywhere
//Other parts of the code suffer from the same issue of
copy.type = mono_type_get_type_byval (copy.type);
copy.stype &= ~POINTER_MASK;
if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object diferent thant the this pointer at 0x%04x", ctx->ip_offset));
if (constrained && virtual) {
if (!stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), ctx->constrained_type, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
copy.stype |= BOXED_MASK;
} else {
if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a reference type using a managed pointer to the this arg at 0x%04x", ctx->ip_offset));
if (!virtual && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
if (virtual && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a boxed or literal valuetype to call a valuetype method at 0x%04x", ctx->ip_offset));
}
if (!verify_stack_type_compatibility (ctx, type, ©)) {
char *expected = mono_type_full_name (type);
char *effective = stack_slot_full_name (©);
char *method_name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature expected '%s' but got '%s' for a call to '%s' at 0x%04x",
expected, effective, method_name, ctx->ip_offset));
g_free (method_name);
g_free (effective);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
} else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
if (sig->ret->type != MONO_TYPE_VOID) {
if (check_overflow (ctx)) {
value = stack_push (ctx);
set_stack_value (ctx, value, sig->ret, FALSE);
if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
ctx->prefix_set &= ~PREFIX_READONLY;
value->stype |= CMMP_MASK;
}
}
}
if ((ctx->prefix_set & PREFIX_TAIL)) {
if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
}
}
static void
do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
{
MonoClassField *field;
MonoClass *klass;
if (!check_overflow (ctx))
return;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
return;
}
/*taking the address of initonly field only works from the static constructor */
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
}
static void
do_store_static_field (VerifyContext *ctx, int token) {
MonoClassField *field;
MonoClass *klass;
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
return;
}
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
return;
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
if (!verify_stack_type_compatibility (ctx, field->type, value)) {
char *stack_name = stack_slot_full_name (value);
char *field_name = mono_type_full_name (field->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type in static field store expected '%s' but found '%s' at 0x%04x",
field_name, stack_name, ctx->ip_offset));
g_free (field_name);
g_free (stack_name);
}
}
static gboolean
check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
{
MonoClassField *field;
MonoClass *klass;
gboolean is_pointer;
/*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
return FALSE;
*ret_field = field;
//the value on stack is going to be used as a pointer
is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
return FALSE;
}
g_assert (obj->type);
/*The value on the stack must be a subclass of the defining type of the field*/
/* we need to check if we can load the field from the stack value*/
if (is_pointer) {
if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
} else {
if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a managed pointer to a reference type and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
/*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a boxed valuetype and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
char *found = stack_slot_full_name (obj);
char *expected = mono_type_full_name (&field->parent->byval_arg);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset));
g_free (found);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
}
check_unmanaged_pointer (ctx, obj);
return TRUE;
}
static void
do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
{
ILStackDesc *obj;
MonoClassField *field;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
return;
if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), field->type, take_addr);
}
static void
do_store_field (VerifyContext *ctx, int token)
{
ILStackDesc *value, *obj;
MonoClassField *field;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
value = stack_pop (ctx);
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
return;
if (!verify_stack_type_compatibility (ctx, field->type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
/*TODO proper handle for Nullable<T>*/
static void
do_box_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
MonoClass *klass;
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*box is a nop for reference types*/
if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
return;
}
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
klass = mono_class_from_mono_type (type);
if (mono_class_is_nullable (klass))
type = &mono_class_get_nullable_param (klass)->byval_arg;
stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
}
static void
do_unbox_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
if (!mono_class_from_mono_type (type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
value->stype |= CMMP_MASK;
}
static void
do_unbox_any (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox.any operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_unary_math_op (VerifyContext *ctx, int op)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
break;
case TYPE_R8:
if (op == CEE_NEG)
break;
case TYPE_COMPLEX: /*only enums are ok*/
if (mono_type_is_enum_type (value->type))
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
}
stack_push_stack_val (ctx, value);
}
static void
do_conversion (VerifyContext *ctx, int kind)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_R8:
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type (%s) at stack for conversion operation. Numeric type expected at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
switch (kind) {
case TYPE_I4:
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
break;
case TYPE_I8:
stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
break;
case TYPE_R8:
stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
break;
case TYPE_NATIVE_INT:
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
break;
default:
g_error ("unknown type %02x in conversion", kind);
}
}
static void
do_load_token (VerifyContext *ctx, int token)
{
gpointer handle;
MonoClass *handle_class;
if (!check_overflow (ctx))
return;
switch (token & 0xff000000) {
case MONO_TOKEN_TYPE_DEF:
case MONO_TOKEN_TYPE_REF:
case MONO_TOKEN_TYPE_SPEC:
case MONO_TOKEN_FIELD_DEF:
case MONO_TOKEN_METHOD_DEF:
case MONO_TOKEN_METHOD_SPEC:
case MONO_TOKEN_MEMBER_REF:
if (!token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Table index out of range 0x%x for token %x for ldtoken at 0x%04x", mono_metadata_token_index (token), token, ctx->ip_offset));
return;
}
break;
default:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid table 0x%x for token 0x%x for ldtoken at 0x%04x", mono_metadata_token_table (token), token, ctx->ip_offset));
return;
}
handle = mono_ldtoken (ctx->image, token, &handle_class, ctx->generic_context);
if (!handle) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x", token, ctx->ip_offset));
return;
}
if (handle_class == mono_defaults.typehandle_class) {
mono_type_is_valid_in_context (ctx, (MonoType*)handle);
} else if (handle_class == mono_defaults.methodhandle_class) {
mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
} else if (handle_class == mono_defaults.fieldhandle_class) {
mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
} else {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
}
stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
}
static void
do_ldobj_value (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)
&& stack_slot_get_type (value) != TYPE_NATIVE_INT
&& !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
return;
}
if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
/*We have a byval on the stack, but the comparison must be strict. */
if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_stobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, type, src)) {
char *type_name = mono_type_full_name (type);
char *src_name = stack_slot_full_name (src);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token '%s' and source '%s' of stobj don't match ' at 0x%04x", type_name, src_name, ctx->ip_offset));
g_free (type_name);
g_free (src_name);
}
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_cpobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (src))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_initobj (VerifyContext *ctx, int token)
{
ILStackDesc *obj;
MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
obj = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
stack = mono_type_get_type_byval (obj->type);
if (MONO_TYPE_IS_REFERENCE (stack)) {
if (!verify_type_compatibility (ctx, stack, type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility (ctx, stack, type)) {
char *expected_name = mono_type_full_name (type);
char *stack_name = mono_type_full_name (stack);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Initobj %s not compatible with value on stack %s at 0x%04x", expected_name, stack_name, ctx->ip_offset));
g_free (expected_name);
g_free (stack_name);
}
}
static void
do_newobj (VerifyContext *ctx, int token)
{
ILStackDesc *value;
int i;
MonoMethodSignature *sig;
MonoMethod *method;
gboolean is_delegate = FALSE;
if (!(method = verifier_load_method (ctx, token, "newobj")))
return;
if (!mono_method_is_constructor (method)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
return;
}
if (method->klass->flags & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
if (!mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *from = mono_method_full_name (ctx->method, TRUE);
char *to = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Constructor %s not visible from %s at 0x%04x", to, from, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (from);
g_free (to);
}
//FIXME use mono_method_get_signature_full
sig = mono_method_signature (method);
if (!sig) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
return;
}
if (!check_underflow (ctx, sig->param_count))
return;
is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
if (is_delegate) {
ILStackDesc *funptr;
//first arg is object, second arg is fun ptr
if (sig->param_count != 2) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
funptr = stack_pop (ctx);
value = stack_pop (ctx);
verify_delegate_compatibility (ctx, method->klass, value, funptr);
} else {
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with constructor signature: %s X %s at 0x%04x", sig_name, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
}
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
}
static void
do_cast (VerifyContext *ctx, int token, const char *opcode) {
ILStackDesc *value;
MonoType *type;
gboolean is_boxed;
gboolean do_box;
if (!check_underflow (ctx, 1))
return;
if (!(type = verifier_load_type (ctx, token, opcode)))
return;
if (type->byref) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
return;
}
value = stack_pop (ctx);
is_boxed = stack_slot_is_boxed_value (value);
if (stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
char *name = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a reference type on stack for %s but found %s at 0x%04x", opcode, name, ctx->ip_offset));
g_free (name);
}
switch (value->type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
}
do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
}
static MonoType *
mono_type_from_opcode (int opcode) {
switch (opcode) {
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_STIND_I1:
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_STELEM_I1:
return &mono_defaults.sbyte_class->byval_arg;
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_STIND_I2:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_STELEM_I2:
return &mono_defaults.int16_class->byval_arg;
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_STIND_I4:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_STELEM_I4:
return &mono_defaults.int32_class->byval_arg;
case CEE_LDIND_I8:
case CEE_STIND_I8:
case CEE_LDELEM_I8:
case CEE_STELEM_I8:
return &mono_defaults.int64_class->byval_arg;
case CEE_LDIND_R4:
case CEE_STIND_R4:
case CEE_LDELEM_R4:
case CEE_STELEM_R4:
return &mono_defaults.single_class->byval_arg;
case CEE_LDIND_R8:
case CEE_STIND_R8:
case CEE_LDELEM_R8:
case CEE_STELEM_R8:
return &mono_defaults.double_class->byval_arg;
case CEE_LDIND_I:
case CEE_STIND_I:
case CEE_LDELEM_I:
case CEE_STELEM_I:
return &mono_defaults.int_class->byval_arg;
case CEE_LDIND_REF:
case CEE_STIND_REF:
case CEE_LDELEM_REF:
case CEE_STELEM_REF:
return &mono_defaults.object_class->byval_arg;
default:
g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
return NULL;
}
}
static void
do_load_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
return;
}
if (opcode == CEE_LDIND_REF) {
if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
} else {
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
}
}
static void
do_store_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *addr, *val;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
val = stack_pop (ctx);
addr = stack_pop (ctx);
check_unmanaged_pointer (ctx, addr);
if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
return;
}
if (stack_slot_is_managed_mutability_pointer (addr)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
return;
}
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
}
static void
do_newarr (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
}
/*FIXME handle arrays that are not 0-indexed*/
static void
do_ldlen (VerifyContext *ctx)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
}
/*FIXME handle arrays that are not 0-indexed*/
/*FIXME handle readonly prefix and CMMP*/
static void
do_ldelema (VerifyContext *ctx, int klass_token)
{
ILStackDesc *index, *array, *res;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
gboolean valid;
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelema is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
} else {
valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
}
if (!valid)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
}
}
res = stack_push (ctx);
set_stack_value (ctx, res, type, TRUE);
if (ctx->prefix_set & PREFIX_READONLY) {
ctx->prefix_set &= ~PREFIX_READONLY;
res->stype |= CMMP_MASK;
}
}
/*
* FIXME handle arrays that are not 0-indexed
* FIXME handle readonly prefix and CMMP
*/
static void
do_ldelem (VerifyContext *ctx, int opcode, int token)
{
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
ILStackDesc *index, *array;
MonoType *type;
if (!check_underflow (ctx, 2))
return;
if (opcode == CEE_LDELEM) {
if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (opcode == CEE_LDELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
type = &array->type->data.klass->byval_arg;
} else {
MonoType *candidate = &array->type->data.klass->byval_arg;
if (IS_STRICT_MODE (ctx)) {
MonoType *underlying_type = mono_type_get_underlying_type_any (type);
MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
if ((IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I, MONO_TYPE_U)) ||
(IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
}
}
set_stack_value (ctx, stack_push (ctx), type, FALSE);
#undef IS_ONE_OF2
}
/*
* FIXME handle arrays that are not 0-indexed
*/
static void
do_stelem (VerifyContext *ctx, int opcode, int token)
{
ILStackDesc *index, *array, *value;
MonoType *type;
if (!check_underflow (ctx, 3))
return;
if (opcode == CEE_STELEM) {
if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
value = stack_pop (ctx);
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for stdelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for stelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
} else {
if (opcode == CEE_STELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
}
}
}
if (opcode == CEE_STELEM_REF) {
if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (opcode != CEE_STELEM_REF) {
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
}
}
static void
do_throw (VerifyContext *ctx)
{
ILStackDesc *exception;
if (!check_underflow (ctx, 1))
return;
exception = stack_pop (ctx);
if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
char *name = mono_type_full_name (exception->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type but found unboxed %s at 0x%04x ", name, ctx->ip_offset));
g_free (name);
}
/*The stack is left empty after a throw*/
ctx->eval.size = 0;
}
static void
do_endfilter (VerifyContext *ctx)
{
MonoExceptionClause *clause;
if (IS_STRICT_MODE (ctx)) {
if (ctx->eval.size != 1)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
}
if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
if (IS_STRICT_MODE (ctx)) {
if (ctx->ip_offset != clause->handler_offset - 2)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
} else {
if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
}
} else {
if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
else
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
}
ctx->eval.size = 0;
}
static void
do_leave (VerifyContext *ctx, int delta)
{
int target = ((gint32)ctx->ip_offset) + delta;
if (target >= ctx->code_size || target < 0)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
ctx->eval.size = 0;
}
/*
* do_static_branch:
*
* Verify br and br.s opcodes.
*/
static void
do_static_branch (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
}
ctx->target = target;
}
static void
do_switch (VerifyContext *ctx, int count, const unsigned char *data)
{
int i, base = ctx->ip_offset + 5 + count * 4;
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
for (i = 0; i < count; ++i) {
int target = base + read32 (data + i * 4);
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
return;
}
merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
}
}
static void
do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual)
{
ILStackDesc *top;
MonoMethod *method;
if (virtual && !check_underflow (ctx, 1))
return;
if (!virtual && !check_overflow (ctx))
return;
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!(method = verifier_load_method (ctx, token, virtual ? "ldvirtfrn" : "ldftn")))
return;
if (mono_method_is_constructor (method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
if (virtual) {
ILStackDesc *top = stack_pop (ctx);
if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
if (method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
}
if (!mono_method_can_access_method_full (ctx->method, method, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Loaded method is not visible for ldftn/ldvirtftn at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
top->method = method;
}
static void
do_sizeof (VerifyContext *ctx, int token)
{
MonoType *type;
if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!(type = verifier_load_type (ctx, token, "sizeof")))
return;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
return;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
return;
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
}
/* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
static void
do_localloc (VerifyContext *ctx)
{
ILStackDesc *top;
if (ctx->eval.size != 1) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
/*TODO verify top type*/
top = stack_pop (ctx);
set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
}
static void
do_ldstr (VerifyContext *ctx, guint32 token)
{
GSList *error = NULL;
if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!ctx->image->dynamic && !mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
if (error)
ctx->list = g_slist_concat (ctx->list, error);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (check_overflow (ctx))
stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
}
static void
do_refanyval (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanyval, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, TRUE);
}
static void
do_refanytype (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanytype, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
}
static void
do_mkrefany (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (top)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a managed pointer for mkrefany, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
}else {
MonoType *stack_type = mono_type_get_type_byval (top->type);
if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
}
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
}
static void
do_ckfinite (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (stack_slot_get_underlying_type (top) != TYPE_R8)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected float32 or float64 on stack for ckfinit but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
stack_push_stack_val (ctx, top);
}
/*
* merge_stacks:
* Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
*
* @from holds new values for a given control path
* @to holds the current values of a given control path
*
* TODO we can eliminate the from argument as all callers pass &ctx->eval
*/
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
{
MonoError error;
int i, j, k;
stack_init (ctx, to);
if (start) {
if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
from->size = 0;
else
stack_copy (&ctx->eval, to);
goto end_verify;
} else if (!(to->flags & IL_CODE_STACK_MERGED)) {
stack_copy (to, &ctx->eval);
goto end_verify;
}
VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
if (from->size != to->size) {
VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not merge stacks, different sizes (%d x %d) at 0x%04x", from->size, to->size, ctx->ip_offset));
goto end_verify;
}
//FIXME we need to preserve CMMP attributes
//FIXME we must take null literals into consideration.
for (i = 0; i < from->size; ++i) {
ILStackDesc *new_slot = from->stack + i;
ILStackDesc *old_slot = to->stack + i;
MonoType *new_type = mono_type_from_stack_slot (new_slot);
MonoType *old_type = mono_type_from_stack_slot (old_slot);
MonoClass *old_class = mono_class_from_mono_type (old_type);
MonoClass *new_class = mono_class_from_mono_type (new_type);
MonoClass *match_class = NULL;
// S := T then U = S (new value is compatible with current value, keep current)
if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
copy_stack_value (new_slot, old_slot);
continue;
}
// T := S then U = T (old value is compatible with current value, use new)
if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
copy_stack_value (old_slot, new_slot);
continue;
}
if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
goto end_verify;
}
//both are reference types, use closest common super type
if (!mono_class_from_mono_type (old_type)->valuetype
&& !mono_class_from_mono_type (new_type)->valuetype
&& !stack_slot_is_managed_pointer (old_slot)
&& !stack_slot_is_managed_pointer (new_slot)) {
for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
match_class = old_class->supertypes [j];
goto match_found;
}
}
mono_class_setup_interfaces (old_class, &error);
if (!mono_error_ok (&error)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset));
mono_error_cleanup (&error);
goto end_verify;
}
for (j = 0; j < old_class->interface_count; ++j) {
for (k = 0; k < new_class->interface_count; ++k) {
if (mono_metadata_type_equal (&old_class->interfaces [j]->byval_arg, &new_class->interfaces [k]->byval_arg)) {
match_class = old_class->interfaces [j];
goto match_found;
}
}
}
//No decent super type found, use object
match_class = mono_defaults.object_class;
goto match_found;
} else if (is_compatible_boxed_valuetype (ctx,old_type, new_type, new_slot, FALSE) || is_compatible_boxed_valuetype (ctx, new_type, old_type, old_slot, FALSE)) {
match_class = mono_defaults.object_class;
goto match_found;
}
{
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
}
set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
goto end_verify;
match_found:
g_assert (match_class);
set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
continue;
}
end_verify:
if (external)
to->flags |= IL_CODE_FLAG_WAS_TARGET;
to->flags |= IL_CODE_STACK_MERGED;
}
#define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
#define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
/*
* is_clause_in_range :
*
* Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
*/
static gboolean
is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset >= start && clause->try_offset < end)
return TRUE;
if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
return TRUE;
return FALSE;
}
/*
* is_clause_inside_range :
*
* Returns TRUE if @clause lies completely inside the @start - @end range.
*/
static gboolean
is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
return FALSE;
if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
return FALSE;
return TRUE;
}
/*
* is_clause_nested :
*
* Returns TRUE if @nested is nested in @clause.
*/
static gboolean
is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
{
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
return TRUE;
return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
}
/* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
* the each pair of exception must have the following properties:
* - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
* - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
* - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
*/
static void
verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
{
/*clause is nested*/
if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
return;
}
/*wrong nesting order.*/
if (is_clause_nested (clause, to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
return;
}
/*mutual protection*/
if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
/*handlers are not disjoint*/
if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
return;
}
/* handlers are not catch or filter */
if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
return;
}
/*OK*/
return;
}
/*not completelly disjoint*/
if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
}
#define code_bounds_check(size) \
if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
break; \
} \
static gboolean
mono_opcode_is_prefix (int op)
{
switch (op) {
case MONO_CEE_UNALIGNED_:
case MONO_CEE_VOLATILE_:
case MONO_CEE_TAIL_:
case MONO_CEE_CONSTRAINED_:
case MONO_CEE_READONLY_:
return TRUE;
}
return FALSE;
}
/*
* FIXME: need to distinguish between valid and verifiable.
* Need to keep track of types on the stack.
* Verify types for opcodes.
*/
GSList*
mono_method_verify (MonoMethod *method, int level)
{
MonoError error;
const unsigned char *ip, *code_start;
const unsigned char *end;
MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
int i, n, need_merge = 0, start = 0;
guint token, ip_offset = 0, prefix = 0;
MonoGenericContext *generic_context = NULL;
MonoImage *image;
VerifyContext ctx;
GSList *tmp;
VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
init_verifier_stats ();
if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
return NULL;
}
memset (&ctx, 0, sizeof (VerifyContext));
//FIXME use mono_method_get_signature_full
ctx.signature = mono_method_signature (method);
if (!ctx.signature) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
finish_collect_stats ();
return ctx.list;
}
ctx.header = mono_method_get_header (method);
if (!ctx.header) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header"));
finish_collect_stats ();
return ctx.list;
}
ctx.method = method;
code_start = ip = ctx.header->code;
end = ip + ctx.header->code_size;
ctx.image = image = method->klass->image;
ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
ctx.max_stack = ctx.header->max_stack;
ctx.verifiable = ctx.valid = 1;
ctx.level = level;
ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
ctx.code_size = ctx.header->code_size;
MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
ctx.num_locals = ctx.header->num_locals;
ctx.locals = g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
if (ctx.num_locals > 0 && !ctx.header->init_locals)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
ctx.params = g_new (MonoType*, ctx.max_args);
MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
if (ctx.signature->hasthis)
ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
if (ctx.signature->is_inflated)
ctx.generic_context = generic_context = mono_method_get_context (method);
if (!generic_context && (method->klass->generic_container || method->is_generic)) {
if (method->is_generic)
ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
else
ctx.generic_context = generic_context = &method->klass->generic_container->context;
}
for (i = 0; i < ctx.num_locals; ++i) {
MonoType *uninflated = ctx.locals [i];
ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.num_locals = i;
ctx.max_args = 0;
goto cleanup;
}
}
for (i = 0; i < ctx.max_args; ++i) {
MonoType *uninflated = ctx.params [i];
ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.max_args = i;
goto cleanup;
}
}
stack_init (&ctx, &ctx.eval);
for (i = 0; i < ctx.num_locals; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
break;
if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.locals [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
g_free (name);
break;
}
}
for (i = 0; i < ctx.max_args; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
break;
if (get_stack_type (ctx.params [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.params [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
g_free (name);
break;
}
}
if (!ctx.valid)
goto cleanup;
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
VERIFIER_DEBUG (printf ("clause try %x len %x filter at %x handler at %x len %x\n", clause->try_offset, clause->try_len, clause->data.filter_offset, clause->handler_offset, clause->handler_len); );
if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
if (clause->try_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
if (clause->handler_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
if (clause->data.filter_offset > ctx.code_size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
if (clause->data.filter_offset >= clause->handler_offset)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
}
for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
if (!ctx.valid)
break;
ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->try_offset + clause->try_len < ctx.code_size)
ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->handler_offset + clause->handler_len < ctx.code_size)
ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
if (!clause->data.catch_class) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
break;
}
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
}
else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
}
}
original_bb = bb = mono_basic_block_split (method, &error);
if (!mono_error_ok (&error)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
mono_error_cleanup (&error);
goto cleanup;
}
g_assert (bb);
while (ip < end && ctx.valid) {
ip_offset = ip - code_start;
{
const unsigned char *ip_copy = ip;
int size, op;
if (ip_offset > bb->end) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
goto cleanup;
}
if (ip_offset == bb->end)
bb = bb->next;
size = mono_opcode_value_and_size (&ip_copy, end, &op);
if (size == -1) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
goto cleanup;
}
if (ADD_IS_GREATER_OR_OVF (ip_offset, size, bb->end)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
goto cleanup;
}
/*Last Instruction*/
if (ip_offset + size == bb->end && mono_opcode_is_prefix (op)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets between prefix '%s' and instruction at 0x%04x", mono_opcode_name (op), ip_offset));
goto cleanup;
}
if (bb->dead) {
/*FIXME remove this once we move all bad branch checking code to use BB only*/
ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
ip += size;
continue;
}
}
ctx.ip_offset = ip_offset = ip - code_start;
/*We need to check against fallthrou in and out of protected blocks.
* For fallout we check the once a protected block ends, if the start flag is not set.
* Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
* TODO convert these checks to be done using flags and not this loop
*/
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
start = 1;
}
if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
start = 1;
}
if (clause->handler_offset == ip_offset && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
start = 1;
}
}
if (!ctx.valid)
break;
if (need_merge) {
VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
need_merge = 0;
}
merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
start = 0;
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
#ifdef MONO_VERIFIER_DEBUG
{
char *discode;
discode = mono_disasm_code_one (NULL, method, ip, NULL);
discode [strlen (discode) - 1] = 0; /* no \n */
g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
g_free (discode);
}
dump_stack_state (&ctx.code [ip_offset]);
dump_stack_state (&ctx.eval);
#endif
switch (*ip) {
case CEE_NOP:
case CEE_BREAK:
++ip;
break;
case CEE_LDARG_0:
case CEE_LDARG_1:
case CEE_LDARG_2:
case CEE_LDARG_3:
push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
++ip;
break;
case CEE_LDARG_S:
case CEE_LDARGA_S:
code_bounds_check (2);
push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
ip += 2;
break;
case CEE_ADD_OVF_UN:
do_binop (&ctx, *ip, add_ovf_un_table);
++ip;
break;
case CEE_SUB_OVF_UN:
do_binop (&ctx, *ip, sub_ovf_un_table);
++ip;
break;
case CEE_ADD_OVF:
case CEE_SUB_OVF:
case CEE_MUL_OVF:
case CEE_MUL_OVF_UN:
do_binop (&ctx, *ip, bin_ovf_table);
++ip;
break;
case CEE_ADD:
do_binop (&ctx, *ip, add_table);
++ip;
break;
case CEE_SUB:
do_binop (&ctx, *ip, sub_table);
++ip;
break;
case CEE_MUL:
case CEE_DIV:
case CEE_REM:
do_binop (&ctx, *ip, bin_op_table);
++ip;
break;
case CEE_AND:
case CEE_DIV_UN:
case CEE_OR:
case CEE_REM_UN:
case CEE_XOR:
do_binop (&ctx, *ip, int_bin_op_table);
++ip;
break;
case CEE_SHL:
case CEE_SHR:
case CEE_SHR_UN:
do_binop (&ctx, *ip, shift_op_table);
++ip;
break;
case CEE_POP:
if (!check_underflow (&ctx, 1))
break;
stack_pop_safe (&ctx);
++ip;
break;
case CEE_RET:
do_ret (&ctx);
++ip;
start = 1;
break;
case CEE_LDLOC_0:
case CEE_LDLOC_1:
case CEE_LDLOC_2:
case CEE_LDLOC_3:
/*TODO support definite assignment verification? */
push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
++ip;
break;
case CEE_STLOC_0:
case CEE_STLOC_1:
case CEE_STLOC_2:
case CEE_STLOC_3:
store_local (&ctx, *ip - CEE_STLOC_0);
++ip;
break;
case CEE_STLOC_S:
code_bounds_check (2);
store_local (&ctx, ip [1]);
ip += 2;
break;
case CEE_STARG_S:
code_bounds_check (2);
store_arg (&ctx, ip [1]);
ip += 2;
break;
case CEE_LDC_I4_M1:
case CEE_LDC_I4_0:
case CEE_LDC_I4_1:
case CEE_LDC_I4_2:
case CEE_LDC_I4_3:
case CEE_LDC_I4_4:
case CEE_LDC_I4_5:
case CEE_LDC_I4_6:
case CEE_LDC_I4_7:
case CEE_LDC_I4_8:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
++ip;
break;
case CEE_LDC_I4_S:
code_bounds_check (2);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 2;
break;
case CEE_LDC_I4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 5;
break;
case CEE_LDC_I8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
ip += 9;
break;
case CEE_LDC_R4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 5;
break;
case CEE_LDC_R8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 9;
break;
case CEE_LDNULL:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
++ip;
break;
case CEE_BEQ_S:
case CEE_BNE_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
ip += 2;
need_merge = 1;
break;
case CEE_BGE_S:
case CEE_BGT_S:
case CEE_BLE_S:
case CEE_BLT_S:
case CEE_BGE_UN_S:
case CEE_BGT_UN_S:
case CEE_BLE_UN_S:
case CEE_BLT_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
ip += 2;
need_merge = 1;
break;
case CEE_BEQ:
case CEE_BNE_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
ip += 5;
need_merge = 1;
break;
case CEE_BGE:
case CEE_BGT:
case CEE_BLE:
case CEE_BLT:
case CEE_BGE_UN:
case CEE_BGT_UN:
case CEE_BLE_UN:
case CEE_BLT_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
ip += 5;
need_merge = 1;
break;
case CEE_LDLOC_S:
case CEE_LDLOCA_S:
code_bounds_check (2);
push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
ip += 2;
break;
case CEE_UNUSED99:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_DUP: {
ILStackDesc *top;
if (!check_underflow (&ctx, 1))
break;
if (!check_overflow (&ctx))
break;
top = stack_push (&ctx);
copy_stack_value (top, stack_peek (&ctx, 1));
++ip;
break;
}
case CEE_JMP:
code_bounds_check (5);
if (ctx.eval.size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
token = read32 (ip + 1);
if (in_any_block (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
/*
* FIXME: check signature, retval, arguments etc.
*/
ip += 5;
break;
case CEE_CALL:
case CEE_CALLVIRT:
code_bounds_check (5);
do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
ip += 5;
break;
case CEE_CALLI:
code_bounds_check (5);
token = read32 (ip + 1);
/*
* FIXME: check signature, retval, arguments etc.
* FIXME: check requirements for tail call
*/
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
ip += 5;
break;
case CEE_BR_S:
code_bounds_check (2);
do_static_branch (&ctx, (signed char)ip [1] + 2);
need_merge = 1;
ip += 2;
start = 1;
break;
case CEE_BRFALSE_S:
case CEE_BRTRUE_S:
code_bounds_check (2);
do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
ip += 2;
need_merge = 1;
break;
case CEE_BR:
code_bounds_check (5);
do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
need_merge = 1;
ip += 5;
start = 1;
break;
case CEE_BRFALSE:
case CEE_BRTRUE:
code_bounds_check (5);
do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
ip += 5;
need_merge = 1;
break;
case CEE_SWITCH: {
guint32 entries;
code_bounds_check (5);
entries = read32 (ip + 1);
if (entries > 0xFFFFFFFFU / sizeof (guint32))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
ip += 5;
code_bounds_check (sizeof (guint32) * entries);
do_switch (&ctx, entries, ip);
ip += sizeof (guint32) * entries;
break;
}
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_LDIND_I8:
case CEE_LDIND_I:
case CEE_LDIND_R4:
case CEE_LDIND_R8:
case CEE_LDIND_REF:
do_load_indirect (&ctx, *ip);
++ip;
break;
case CEE_STIND_REF:
case CEE_STIND_I1:
case CEE_STIND_I2:
case CEE_STIND_I4:
case CEE_STIND_I8:
case CEE_STIND_R4:
case CEE_STIND_R8:
case CEE_STIND_I:
do_store_indirect (&ctx, *ip);
++ip;
break;
case CEE_NOT:
case CEE_NEG:
do_unary_math_op (&ctx, *ip);
++ip;
break;
case CEE_CONV_I1:
case CEE_CONV_I2:
case CEE_CONV_I4:
case CEE_CONV_U1:
case CEE_CONV_U2:
case CEE_CONV_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_I8:
case CEE_CONV_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_R4:
case CEE_CONV_R8:
case CEE_CONV_R_UN:
do_conversion (&ctx, TYPE_R8);
++ip;
break;
case CEE_CONV_I:
case CEE_CONV_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_CPOBJ:
code_bounds_check (5);
do_cpobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDOBJ:
code_bounds_check (5);
do_ldobj_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDSTR:
code_bounds_check (5);
do_ldstr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWOBJ:
code_bounds_check (5);
do_newobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CASTCLASS:
case CEE_ISINST:
code_bounds_check (5);
do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
ip += 5;
break;
case CEE_UNUSED58:
case CEE_UNUSED1:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_UNBOX:
code_bounds_check (5);
do_unbox_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_THROW:
do_throw (&ctx);
start = 1;
++ip;
break;
case CEE_LDFLD:
case CEE_LDFLDA:
code_bounds_check (5);
do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
ip += 5;
break;
case CEE_LDSFLD:
case CEE_LDSFLDA:
code_bounds_check (5);
do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
ip += 5;
break;
case CEE_STFLD:
code_bounds_check (5);
do_store_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STSFLD:
code_bounds_check (5);
do_store_static_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STOBJ:
code_bounds_check (5);
do_stobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1_UN:
case CEE_CONV_OVF_I2_UN:
case CEE_CONV_OVF_I4_UN:
case CEE_CONV_OVF_U1_UN:
case CEE_CONV_OVF_U2_UN:
case CEE_CONV_OVF_U4_UN:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8_UN:
case CEE_CONV_OVF_U8_UN:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I_UN:
case CEE_CONV_OVF_U_UN:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_BOX:
code_bounds_check (5);
do_box_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWARR:
code_bounds_check (5);
do_newarr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDLEN:
do_ldlen (&ctx);
++ip;
break;
case CEE_LDELEMA:
code_bounds_check (5);
do_ldelema (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_LDELEM_I8:
case CEE_LDELEM_I:
case CEE_LDELEM_R4:
case CEE_LDELEM_R8:
case CEE_LDELEM_REF:
do_ldelem (&ctx, *ip, 0);
++ip;
break;
case CEE_STELEM_I:
case CEE_STELEM_I1:
case CEE_STELEM_I2:
case CEE_STELEM_I4:
case CEE_STELEM_I8:
case CEE_STELEM_R4:
case CEE_STELEM_R8:
case CEE_STELEM_REF:
do_stelem (&ctx, *ip, 0);
++ip;
break;
case CEE_LDELEM:
code_bounds_check (5);
do_ldelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_STELEM:
code_bounds_check (5);
do_stelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_UNBOX_ANY:
code_bounds_check (5);
do_unbox_any (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1:
case CEE_CONV_OVF_U1:
case CEE_CONV_OVF_I2:
case CEE_CONV_OVF_U2:
case CEE_CONV_OVF_I4:
case CEE_CONV_OVF_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8:
case CEE_CONV_OVF_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I:
case CEE_CONV_OVF_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_REFANYVAL:
code_bounds_check (5);
do_refanyval (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CKFINITE:
do_ckfinite (&ctx);
++ip;
break;
case CEE_MKREFANY:
code_bounds_check (5);
do_mkrefany (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDTOKEN:
code_bounds_check (5);
do_load_token (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_ENDFINALLY:
if (!is_correct_endfinally (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_LEAVE:
code_bounds_check (5);
do_leave (&ctx, read32 (ip + 1) + 5);
ip += 5;
start = 1;
break;
case CEE_LEAVE_S:
code_bounds_check (2);
do_leave (&ctx, (signed char)ip [1] + 2);
ip += 2;
start = 1;
break;
case CEE_PREFIX1:
code_bounds_check (2);
++ip;
switch (*ip) {
case CEE_STLOC:
code_bounds_check (3);
store_local (&ctx, read16 (ip + 1));
ip += 3;
break;
case CEE_CEQ:
do_cmp_op (&ctx, cmp_br_eq_op, *ip);
++ip;
break;
case CEE_CGT:
case CEE_CGT_UN:
case CEE_CLT:
case CEE_CLT_UN:
do_cmp_op (&ctx, cmp_br_op, *ip);
++ip;
break;
case CEE_STARG:
code_bounds_check (3);
store_arg (&ctx, read16 (ip + 1) );
ip += 3;
break;
case CEE_ARGLIST:
if (!check_overflow (&ctx))
break;
if (ctx.signature->call_convention != MONO_CALL_VARARG)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
++ip;
break;
case CEE_LDFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
ip += 5;
break;
case CEE_LDVIRTFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
ip += 5;
break;
case CEE_LDARG:
case CEE_LDARGA:
code_bounds_check (3);
push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
ip += 3;
break;
case CEE_LDLOC:
case CEE_LDLOCA:
code_bounds_check (3);
push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
ip += 3;
break;
case CEE_LOCALLOC:
do_localloc (&ctx);
++ip;
break;
case CEE_UNUSED56:
case CEE_UNUSED57:
case CEE_UNUSED70:
case CEE_UNUSED:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_ENDFILTER:
do_endfilter (&ctx);
start = 1;
++ip;
break;
case CEE_UNALIGNED_:
code_bounds_check (2);
prefix |= PREFIX_UNALIGNED;
ip += 2;
break;
case CEE_VOLATILE_:
prefix |= PREFIX_VOLATILE;
++ip;
break;
case CEE_TAIL_:
prefix |= PREFIX_TAIL;
++ip;
if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
break;
case CEE_INITOBJ:
code_bounds_check (5);
do_initobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONSTRAINED_:
code_bounds_check (5);
ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
prefix |= PREFIX_CONSTRAINED;
ip += 5;
break;
case CEE_READONLY_:
prefix |= PREFIX_READONLY;
ip++;
break;
case CEE_CPBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_INITBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_NO_:
ip += 2;
break;
case CEE_RETHROW:
if (!is_correct_rethrow (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_SIZEOF:
code_bounds_check (5);
do_sizeof (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_REFANYTYPE:
do_refanytype (&ctx);
++ip;
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
if (prefix) {
if (!ctx.prefix_set) //first prefix
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
ctx.prefix_set |= prefix;
ctx.has_flags = TRUE;
prefix = 0;
} else {
if (!ctx.has_flags)
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
if (ctx.prefix_set & PREFIX_CONSTRAINED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_READONLY)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_VOLATILE)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_UNALIGNED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
ctx.prefix_set = prefix = 0;
ctx.has_flags = FALSE;
}
}
/*
* if ip != end we overflowed: mark as error.
*/
if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
}
/*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of intruction at 0x%04x", i));
if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
}
if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid call to a non-final virtual function in method with stdarg.0 or ldarga.0 at 0x%04x", i));
}
if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
char *method_name = mono_method_full_name (ctx.method, TRUE);
char *type = mono_type_get_full_name (ctx.method->klass);
if (ctx.method->klass->parent && ctx.method->klass->parent->exception_type != MONO_EXCEPTION_NONE)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor due to a TypeLoadException on base type.", method_name, type));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
g_free (method_name);
g_free (type);
}
cleanup:
if (ctx.code) {
for (i = 0; i < ctx.header->code_size; ++i) {
if (ctx.code [i].stack)
g_free (ctx.code [i].stack);
}
}
for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
g_free (tmp->data);
g_slist_free (ctx.funptrs);
for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
mono_metadata_free_type (tmp->data);
g_slist_free (ctx.exception_types);
for (i = 0; i < ctx.num_locals; ++i) {
if (ctx.locals [i])
mono_metadata_free_type (ctx.locals [i]);
}
for (i = 0; i < ctx.max_args; ++i) {
if (ctx.params [i])
mono_metadata_free_type (ctx.params [i]);
}
if (ctx.eval.stack)
g_free (ctx.eval.stack);
if (ctx.code)
g_free (ctx.code);
g_free (ctx.locals);
g_free (ctx.params);
mono_basic_block_free (original_bb);
mono_metadata_free_mh (ctx.header);
finish_collect_stats ();
return ctx.list;
}
char*
mono_verify_corlib ()
{
/* This is a public API function so cannot be removed */
return NULL;
}
/*
* Returns true if @method needs to be verified.
*
*/
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
return mono_verifier_is_enabled_for_class (method->klass) && method->wrapper_type == MONO_WRAPPER_NONE;
}
/*
* Returns true if @klass need to be verified.
*
*/
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
}
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
return mono_verifier_is_class_full_trust (method->klass);
}
/*
* Returns if @klass is under full trust or not.
*
* TODO This code doesn't take CAS into account.
*
* Under verify_all all user code must be verifiable if no security option was set
*
*/
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
gboolean trusted_location = (mono_security_get_mode () != MONO_SECURITY_MODE_CORE_CLR) ?
(klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
return trusted_location || klass->image == mono_defaults.corlib;
return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
{
return mono_method_verify (method,
(verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
| (!mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
| (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
}
static int
get_field_end (MonoClassField *field)
{
int align;
int size = mono_type_size (field->type, &align);
if (size == 0)
size = 4; /*FIXME Is this a safe bet?*/
return size + field->offset;
}
static gboolean
verify_class_for_overlapping_reference_fields (MonoClass *class)
{
int i = 0, j;
gpointer iter = NULL;
MonoClassField *field;
gboolean is_fulltrust = mono_verifier_is_class_full_trust (class);
/*We can't skip types with !has_references since this is calculated after we have run.*/
if (!((class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT))
return TRUE;
/*We must check for stuff overlapping reference fields.
The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
*/
while ((field = mono_class_get_fields (class, &iter))) {
int fieldEnd = get_field_end (field);
gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
++i;
if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
for (j = i; j < class->field.count; ++j) {
MonoClassField *other = &class->fields [j];
int otherEnd = get_field_end (other);
if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
continue;
if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
return FALSE;
}
}
return TRUE;
}
static guint
field_hash (gconstpointer key)
{
const MonoClassField *field = key;
return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
}
static gboolean
field_equals (gconstpointer _a, gconstpointer _b)
{
const MonoClassField *a = _a;
const MonoClassField *b = _b;
return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
}
static gboolean
verify_class_fields (MonoClass *class)
{
gpointer iter = NULL;
MonoClassField *field;
MonoGenericContext *context = mono_class_get_context (class);
GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
if (class->generic_container)
context = &class->generic_container->context;
while ((field = mono_class_get_fields (class, &iter)) != NULL) {
if (!mono_type_is_valid_type_in_context (field->type, context)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
if (g_hash_table_lookup (unique_fields, field)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
g_hash_table_insert (unique_fields, field, field);
}
g_hash_table_destroy (unique_fields);
return TRUE;
}
static gboolean
verify_interfaces (MonoClass *class)
{
int i;
for (i = 0; i < class->interface_count; ++i) {
MonoClass *iface = class->interfaces [i];
if (!(iface->flags & TYPE_ATTRIBUTE_INTERFACE))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout_with_target (MonoClass *class, MonoClass *target_class)
{
int type;
gpointer iter = NULL;
MonoClassField *field;
MonoClass *field_class;
if (!class->valuetype)
return TRUE;
type = class->byval_arg.type;
/*primitive type fields are not properly decoded*/
if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
return TRUE;
while ((field = mono_class_get_fields (class, &iter)) != NULL) {
if (!field->type)
return FALSE;
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
if (field_class == target_class || class == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout (MonoClass *class)
{
gboolean res;
res = verify_valuetype_layout_with_target (class, class);
return res;
}
static gboolean
recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type)
{
int idx;
MonoClass **constraints;
MonoGenericParamInfo *param_info;
g_assert (mono_type_is_generic_argument (type));
idx = mono_type_get_generic_param_num (type);
if (mono_bitset_test_fast (used_args, idx))
return FALSE;
mono_bitset_set_fast (used_args, idx);
param_info = mono_generic_container_get_param_info (gc, idx);
if (!param_info->constraints)
return TRUE;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
return FALSE;
}
return TRUE;
}
static gboolean
verify_generic_parameters (MonoClass *class)
{
int i;
MonoGenericContainer *gc = class->generic_container;
MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0);
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass **constraints;
if (!param_info->constraints)
continue;
mono_bitset_clear_all (used_args);
mono_bitset_set_fast (used_args, i);
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context))
goto fail;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
goto fail;
}
}
mono_bitset_free (used_args);
return TRUE;
fail:
mono_bitset_free (used_args);
return FALSE;
}
/*
* Check if the class is verifiable.
*
* Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
* field and invalid generic instantiation are fatal errors.
*
* This method must be safe to be called from mono_class_init and all code must be carefull about that.
*
*/
gboolean
mono_verifier_verify_class (MonoClass *class)
{
/*Neither <Module>, object or ifaces have parent.*/
if (!class->parent &&
class != mono_defaults.object_class &&
!MONO_CLASS_IS_INTERFACE (class) &&
(!class->image->dynamic && class->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
return FALSE;
if (class->parent && MONO_CLASS_IS_INTERFACE (class->parent))
return FALSE;
if (class->generic_container && (class->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_EXPLICIT_LAYOUT)
return FALSE;
if (class->generic_container && !verify_generic_parameters (class))
return FALSE;
if (!verify_class_for_overlapping_reference_fields (class))
return FALSE;
if (class->generic_class && !mono_class_is_valid_generic_instantiation (NULL, class))
return FALSE;
if (class->generic_class == NULL && !verify_class_fields (class))
return FALSE;
if (class->valuetype && !verify_valuetype_layout (class))
return FALSE;
if (!verify_interfaces (class))
return FALSE;
return TRUE;
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
{
return mono_class_is_valid_generic_instantiation (NULL, class);
}
#else
gboolean
mono_verifier_verify_class (MonoClass *class)
{
/* The verifier was disabled at compile time */
return TRUE;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility)
{
/* The verifier was disabled at compile time */
return NULL;
}
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return FALSE;
}
GSList*
mono_method_verify (MonoMethod *method, int level)
{
/* The verifier was disabled at compile time */
return NULL;
}
void
mono_free_verify_list (GSList *list)
{
/* The verifier was disabled at compile time */
/* will always be null if verifier is disabled */
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *class)
{
return TRUE;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_4717_2 |
crossvul-cpp_data_good_3012_2 | /*
* fs/f2fs/super.c
*
* Copyright (c) 2012 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/statfs.h>
#include <linux/buffer_head.h>
#include <linux/backing-dev.h>
#include <linux/kthread.h>
#include <linux/parser.h>
#include <linux/mount.h>
#include <linux/seq_file.h>
#include <linux/proc_fs.h>
#include <linux/random.h>
#include <linux/exportfs.h>
#include <linux/blkdev.h>
#include <linux/quotaops.h>
#include <linux/f2fs_fs.h>
#include <linux/sysfs.h>
#include <linux/quota.h>
#include "f2fs.h"
#include "node.h"
#include "segment.h"
#include "xattr.h"
#include "gc.h"
#include "trace.h"
#define CREATE_TRACE_POINTS
#include <trace/events/f2fs.h>
static struct kmem_cache *f2fs_inode_cachep;
#ifdef CONFIG_F2FS_FAULT_INJECTION
char *fault_name[FAULT_MAX] = {
[FAULT_KMALLOC] = "kmalloc",
[FAULT_PAGE_ALLOC] = "page alloc",
[FAULT_ALLOC_NID] = "alloc nid",
[FAULT_ORPHAN] = "orphan",
[FAULT_BLOCK] = "no more block",
[FAULT_DIR_DEPTH] = "too big dir depth",
[FAULT_EVICT_INODE] = "evict_inode fail",
[FAULT_TRUNCATE] = "truncate fail",
[FAULT_IO] = "IO error",
[FAULT_CHECKPOINT] = "checkpoint error",
};
static void f2fs_build_fault_attr(struct f2fs_sb_info *sbi,
unsigned int rate)
{
struct f2fs_fault_info *ffi = &sbi->fault_info;
if (rate) {
atomic_set(&ffi->inject_ops, 0);
ffi->inject_rate = rate;
ffi->inject_type = (1 << FAULT_MAX) - 1;
} else {
memset(ffi, 0, sizeof(struct f2fs_fault_info));
}
}
#endif
/* f2fs-wide shrinker description */
static struct shrinker f2fs_shrinker_info = {
.scan_objects = f2fs_shrink_scan,
.count_objects = f2fs_shrink_count,
.seeks = DEFAULT_SEEKS,
};
enum {
Opt_gc_background,
Opt_disable_roll_forward,
Opt_norecovery,
Opt_discard,
Opt_nodiscard,
Opt_noheap,
Opt_heap,
Opt_user_xattr,
Opt_nouser_xattr,
Opt_acl,
Opt_noacl,
Opt_active_logs,
Opt_disable_ext_identify,
Opt_inline_xattr,
Opt_noinline_xattr,
Opt_inline_data,
Opt_inline_dentry,
Opt_noinline_dentry,
Opt_flush_merge,
Opt_noflush_merge,
Opt_nobarrier,
Opt_fastboot,
Opt_extent_cache,
Opt_noextent_cache,
Opt_noinline_data,
Opt_data_flush,
Opt_mode,
Opt_io_size_bits,
Opt_fault_injection,
Opt_lazytime,
Opt_nolazytime,
Opt_quota,
Opt_noquota,
Opt_usrquota,
Opt_grpquota,
Opt_prjquota,
Opt_usrjquota,
Opt_grpjquota,
Opt_prjjquota,
Opt_offusrjquota,
Opt_offgrpjquota,
Opt_offprjjquota,
Opt_jqfmt_vfsold,
Opt_jqfmt_vfsv0,
Opt_jqfmt_vfsv1,
Opt_err,
};
static match_table_t f2fs_tokens = {
{Opt_gc_background, "background_gc=%s"},
{Opt_disable_roll_forward, "disable_roll_forward"},
{Opt_norecovery, "norecovery"},
{Opt_discard, "discard"},
{Opt_nodiscard, "nodiscard"},
{Opt_noheap, "no_heap"},
{Opt_heap, "heap"},
{Opt_user_xattr, "user_xattr"},
{Opt_nouser_xattr, "nouser_xattr"},
{Opt_acl, "acl"},
{Opt_noacl, "noacl"},
{Opt_active_logs, "active_logs=%u"},
{Opt_disable_ext_identify, "disable_ext_identify"},
{Opt_inline_xattr, "inline_xattr"},
{Opt_noinline_xattr, "noinline_xattr"},
{Opt_inline_data, "inline_data"},
{Opt_inline_dentry, "inline_dentry"},
{Opt_noinline_dentry, "noinline_dentry"},
{Opt_flush_merge, "flush_merge"},
{Opt_noflush_merge, "noflush_merge"},
{Opt_nobarrier, "nobarrier"},
{Opt_fastboot, "fastboot"},
{Opt_extent_cache, "extent_cache"},
{Opt_noextent_cache, "noextent_cache"},
{Opt_noinline_data, "noinline_data"},
{Opt_data_flush, "data_flush"},
{Opt_mode, "mode=%s"},
{Opt_io_size_bits, "io_bits=%u"},
{Opt_fault_injection, "fault_injection=%u"},
{Opt_lazytime, "lazytime"},
{Opt_nolazytime, "nolazytime"},
{Opt_quota, "quota"},
{Opt_noquota, "noquota"},
{Opt_usrquota, "usrquota"},
{Opt_grpquota, "grpquota"},
{Opt_prjquota, "prjquota"},
{Opt_usrjquota, "usrjquota=%s"},
{Opt_grpjquota, "grpjquota=%s"},
{Opt_prjjquota, "prjjquota=%s"},
{Opt_offusrjquota, "usrjquota="},
{Opt_offgrpjquota, "grpjquota="},
{Opt_offprjjquota, "prjjquota="},
{Opt_jqfmt_vfsold, "jqfmt=vfsold"},
{Opt_jqfmt_vfsv0, "jqfmt=vfsv0"},
{Opt_jqfmt_vfsv1, "jqfmt=vfsv1"},
{Opt_err, NULL},
};
void f2fs_msg(struct super_block *sb, const char *level, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
printk_ratelimited("%sF2FS-fs (%s): %pV\n", level, sb->s_id, &vaf);
va_end(args);
}
static void init_once(void *foo)
{
struct f2fs_inode_info *fi = (struct f2fs_inode_info *) foo;
inode_init_once(&fi->vfs_inode);
}
#ifdef CONFIG_QUOTA
static const char * const quotatypes[] = INITQFNAMES;
#define QTYPE2NAME(t) (quotatypes[t])
static int f2fs_set_qf_name(struct super_block *sb, int qtype,
substring_t *args)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
char *qname;
int ret = -EINVAL;
if (sb_any_quota_loaded(sb) && !sbi->s_qf_names[qtype]) {
f2fs_msg(sb, KERN_ERR,
"Cannot change journaled "
"quota options when quota turned on");
return -EINVAL;
}
qname = match_strdup(args);
if (!qname) {
f2fs_msg(sb, KERN_ERR,
"Not enough memory for storing quotafile name");
return -EINVAL;
}
if (sbi->s_qf_names[qtype]) {
if (strcmp(sbi->s_qf_names[qtype], qname) == 0)
ret = 0;
else
f2fs_msg(sb, KERN_ERR,
"%s quota file already specified",
QTYPE2NAME(qtype));
goto errout;
}
if (strchr(qname, '/')) {
f2fs_msg(sb, KERN_ERR,
"quotafile must be on filesystem root");
goto errout;
}
sbi->s_qf_names[qtype] = qname;
set_opt(sbi, QUOTA);
return 0;
errout:
kfree(qname);
return ret;
}
static int f2fs_clear_qf_name(struct super_block *sb, int qtype)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
if (sb_any_quota_loaded(sb) && sbi->s_qf_names[qtype]) {
f2fs_msg(sb, KERN_ERR, "Cannot change journaled quota options"
" when quota turned on");
return -EINVAL;
}
kfree(sbi->s_qf_names[qtype]);
sbi->s_qf_names[qtype] = NULL;
return 0;
}
static int f2fs_check_quota_options(struct f2fs_sb_info *sbi)
{
/*
* We do the test below only for project quotas. 'usrquota' and
* 'grpquota' mount options are allowed even without quota feature
* to support legacy quotas in quota files.
*/
if (test_opt(sbi, PRJQUOTA) && !f2fs_sb_has_project_quota(sbi->sb)) {
f2fs_msg(sbi->sb, KERN_ERR, "Project quota feature not enabled. "
"Cannot enable project quota enforcement.");
return -1;
}
if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA] ||
sbi->s_qf_names[PRJQUOTA]) {
if (test_opt(sbi, USRQUOTA) && sbi->s_qf_names[USRQUOTA])
clear_opt(sbi, USRQUOTA);
if (test_opt(sbi, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA])
clear_opt(sbi, GRPQUOTA);
if (test_opt(sbi, PRJQUOTA) && sbi->s_qf_names[PRJQUOTA])
clear_opt(sbi, PRJQUOTA);
if (test_opt(sbi, GRPQUOTA) || test_opt(sbi, USRQUOTA) ||
test_opt(sbi, PRJQUOTA)) {
f2fs_msg(sbi->sb, KERN_ERR, "old and new quota "
"format mixing");
return -1;
}
if (!sbi->s_jquota_fmt) {
f2fs_msg(sbi->sb, KERN_ERR, "journaled quota format "
"not specified");
return -1;
}
}
return 0;
}
#endif
static int parse_options(struct super_block *sb, char *options)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
struct request_queue *q;
substring_t args[MAX_OPT_ARGS];
char *p, *name;
int arg = 0;
#ifdef CONFIG_QUOTA
int ret;
#endif
if (!options)
return 0;
while ((p = strsep(&options, ",")) != NULL) {
int token;
if (!*p)
continue;
/*
* Initialize args struct so we know whether arg was
* found; some options take optional arguments.
*/
args[0].to = args[0].from = NULL;
token = match_token(p, f2fs_tokens, args);
switch (token) {
case Opt_gc_background:
name = match_strdup(&args[0]);
if (!name)
return -ENOMEM;
if (strlen(name) == 2 && !strncmp(name, "on", 2)) {
set_opt(sbi, BG_GC);
clear_opt(sbi, FORCE_FG_GC);
} else if (strlen(name) == 3 && !strncmp(name, "off", 3)) {
clear_opt(sbi, BG_GC);
clear_opt(sbi, FORCE_FG_GC);
} else if (strlen(name) == 4 && !strncmp(name, "sync", 4)) {
set_opt(sbi, BG_GC);
set_opt(sbi, FORCE_FG_GC);
} else {
kfree(name);
return -EINVAL;
}
kfree(name);
break;
case Opt_disable_roll_forward:
set_opt(sbi, DISABLE_ROLL_FORWARD);
break;
case Opt_norecovery:
/* this option mounts f2fs with ro */
set_opt(sbi, DISABLE_ROLL_FORWARD);
if (!f2fs_readonly(sb))
return -EINVAL;
break;
case Opt_discard:
q = bdev_get_queue(sb->s_bdev);
if (blk_queue_discard(q)) {
set_opt(sbi, DISCARD);
} else if (!f2fs_sb_mounted_blkzoned(sb)) {
f2fs_msg(sb, KERN_WARNING,
"mounting with \"discard\" option, but "
"the device does not support discard");
}
break;
case Opt_nodiscard:
if (f2fs_sb_mounted_blkzoned(sb)) {
f2fs_msg(sb, KERN_WARNING,
"discard is required for zoned block devices");
return -EINVAL;
}
clear_opt(sbi, DISCARD);
break;
case Opt_noheap:
set_opt(sbi, NOHEAP);
break;
case Opt_heap:
clear_opt(sbi, NOHEAP);
break;
#ifdef CONFIG_F2FS_FS_XATTR
case Opt_user_xattr:
set_opt(sbi, XATTR_USER);
break;
case Opt_nouser_xattr:
clear_opt(sbi, XATTR_USER);
break;
case Opt_inline_xattr:
set_opt(sbi, INLINE_XATTR);
break;
case Opt_noinline_xattr:
clear_opt(sbi, INLINE_XATTR);
break;
#else
case Opt_user_xattr:
f2fs_msg(sb, KERN_INFO,
"user_xattr options not supported");
break;
case Opt_nouser_xattr:
f2fs_msg(sb, KERN_INFO,
"nouser_xattr options not supported");
break;
case Opt_inline_xattr:
f2fs_msg(sb, KERN_INFO,
"inline_xattr options not supported");
break;
case Opt_noinline_xattr:
f2fs_msg(sb, KERN_INFO,
"noinline_xattr options not supported");
break;
#endif
#ifdef CONFIG_F2FS_FS_POSIX_ACL
case Opt_acl:
set_opt(sbi, POSIX_ACL);
break;
case Opt_noacl:
clear_opt(sbi, POSIX_ACL);
break;
#else
case Opt_acl:
f2fs_msg(sb, KERN_INFO, "acl options not supported");
break;
case Opt_noacl:
f2fs_msg(sb, KERN_INFO, "noacl options not supported");
break;
#endif
case Opt_active_logs:
if (args->from && match_int(args, &arg))
return -EINVAL;
if (arg != 2 && arg != 4 && arg != NR_CURSEG_TYPE)
return -EINVAL;
sbi->active_logs = arg;
break;
case Opt_disable_ext_identify:
set_opt(sbi, DISABLE_EXT_IDENTIFY);
break;
case Opt_inline_data:
set_opt(sbi, INLINE_DATA);
break;
case Opt_inline_dentry:
set_opt(sbi, INLINE_DENTRY);
break;
case Opt_noinline_dentry:
clear_opt(sbi, INLINE_DENTRY);
break;
case Opt_flush_merge:
set_opt(sbi, FLUSH_MERGE);
break;
case Opt_noflush_merge:
clear_opt(sbi, FLUSH_MERGE);
break;
case Opt_nobarrier:
set_opt(sbi, NOBARRIER);
break;
case Opt_fastboot:
set_opt(sbi, FASTBOOT);
break;
case Opt_extent_cache:
set_opt(sbi, EXTENT_CACHE);
break;
case Opt_noextent_cache:
clear_opt(sbi, EXTENT_CACHE);
break;
case Opt_noinline_data:
clear_opt(sbi, INLINE_DATA);
break;
case Opt_data_flush:
set_opt(sbi, DATA_FLUSH);
break;
case Opt_mode:
name = match_strdup(&args[0]);
if (!name)
return -ENOMEM;
if (strlen(name) == 8 &&
!strncmp(name, "adaptive", 8)) {
if (f2fs_sb_mounted_blkzoned(sb)) {
f2fs_msg(sb, KERN_WARNING,
"adaptive mode is not allowed with "
"zoned block device feature");
kfree(name);
return -EINVAL;
}
set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE);
} else if (strlen(name) == 3 &&
!strncmp(name, "lfs", 3)) {
set_opt_mode(sbi, F2FS_MOUNT_LFS);
} else {
kfree(name);
return -EINVAL;
}
kfree(name);
break;
case Opt_io_size_bits:
if (args->from && match_int(args, &arg))
return -EINVAL;
if (arg > __ilog2_u32(BIO_MAX_PAGES)) {
f2fs_msg(sb, KERN_WARNING,
"Not support %d, larger than %d",
1 << arg, BIO_MAX_PAGES);
return -EINVAL;
}
sbi->write_io_size_bits = arg;
break;
case Opt_fault_injection:
if (args->from && match_int(args, &arg))
return -EINVAL;
#ifdef CONFIG_F2FS_FAULT_INJECTION
f2fs_build_fault_attr(sbi, arg);
set_opt(sbi, FAULT_INJECTION);
#else
f2fs_msg(sb, KERN_INFO,
"FAULT_INJECTION was not selected");
#endif
break;
case Opt_lazytime:
sb->s_flags |= MS_LAZYTIME;
break;
case Opt_nolazytime:
sb->s_flags &= ~MS_LAZYTIME;
break;
#ifdef CONFIG_QUOTA
case Opt_quota:
case Opt_usrquota:
set_opt(sbi, USRQUOTA);
break;
case Opt_grpquota:
set_opt(sbi, GRPQUOTA);
break;
case Opt_prjquota:
set_opt(sbi, PRJQUOTA);
break;
case Opt_usrjquota:
ret = f2fs_set_qf_name(sb, USRQUOTA, &args[0]);
if (ret)
return ret;
break;
case Opt_grpjquota:
ret = f2fs_set_qf_name(sb, GRPQUOTA, &args[0]);
if (ret)
return ret;
break;
case Opt_prjjquota:
ret = f2fs_set_qf_name(sb, PRJQUOTA, &args[0]);
if (ret)
return ret;
break;
case Opt_offusrjquota:
ret = f2fs_clear_qf_name(sb, USRQUOTA);
if (ret)
return ret;
break;
case Opt_offgrpjquota:
ret = f2fs_clear_qf_name(sb, GRPQUOTA);
if (ret)
return ret;
break;
case Opt_offprjjquota:
ret = f2fs_clear_qf_name(sb, PRJQUOTA);
if (ret)
return ret;
break;
case Opt_jqfmt_vfsold:
sbi->s_jquota_fmt = QFMT_VFS_OLD;
break;
case Opt_jqfmt_vfsv0:
sbi->s_jquota_fmt = QFMT_VFS_V0;
break;
case Opt_jqfmt_vfsv1:
sbi->s_jquota_fmt = QFMT_VFS_V1;
break;
case Opt_noquota:
clear_opt(sbi, QUOTA);
clear_opt(sbi, USRQUOTA);
clear_opt(sbi, GRPQUOTA);
clear_opt(sbi, PRJQUOTA);
break;
#else
case Opt_quota:
case Opt_usrquota:
case Opt_grpquota:
case Opt_prjquota:
case Opt_usrjquota:
case Opt_grpjquota:
case Opt_prjjquota:
case Opt_offusrjquota:
case Opt_offgrpjquota:
case Opt_offprjjquota:
case Opt_jqfmt_vfsold:
case Opt_jqfmt_vfsv0:
case Opt_jqfmt_vfsv1:
case Opt_noquota:
f2fs_msg(sb, KERN_INFO,
"quota operations not supported");
break;
#endif
default:
f2fs_msg(sb, KERN_ERR,
"Unrecognized mount option \"%s\" or missing value",
p);
return -EINVAL;
}
}
#ifdef CONFIG_QUOTA
if (f2fs_check_quota_options(sbi))
return -EINVAL;
#endif
if (F2FS_IO_SIZE_BITS(sbi) && !test_opt(sbi, LFS)) {
f2fs_msg(sb, KERN_ERR,
"Should set mode=lfs with %uKB-sized IO",
F2FS_IO_SIZE_KB(sbi));
return -EINVAL;
}
return 0;
}
static struct inode *f2fs_alloc_inode(struct super_block *sb)
{
struct f2fs_inode_info *fi;
fi = kmem_cache_alloc(f2fs_inode_cachep, GFP_F2FS_ZERO);
if (!fi)
return NULL;
init_once((void *) fi);
/* Initialize f2fs-specific inode info */
fi->vfs_inode.i_version = 1;
atomic_set(&fi->dirty_pages, 0);
fi->i_current_depth = 1;
fi->i_advise = 0;
init_rwsem(&fi->i_sem);
INIT_LIST_HEAD(&fi->dirty_list);
INIT_LIST_HEAD(&fi->gdirty_list);
INIT_LIST_HEAD(&fi->inmem_pages);
mutex_init(&fi->inmem_lock);
init_rwsem(&fi->dio_rwsem[READ]);
init_rwsem(&fi->dio_rwsem[WRITE]);
init_rwsem(&fi->i_mmap_sem);
init_rwsem(&fi->i_xattr_sem);
#ifdef CONFIG_QUOTA
memset(&fi->i_dquot, 0, sizeof(fi->i_dquot));
fi->i_reserved_quota = 0;
#endif
/* Will be used by directory only */
fi->i_dir_level = F2FS_SB(sb)->dir_level;
return &fi->vfs_inode;
}
static int f2fs_drop_inode(struct inode *inode)
{
int ret;
/*
* This is to avoid a deadlock condition like below.
* writeback_single_inode(inode)
* - f2fs_write_data_page
* - f2fs_gc -> iput -> evict
* - inode_wait_for_writeback(inode)
*/
if ((!inode_unhashed(inode) && inode->i_state & I_SYNC)) {
if (!inode->i_nlink && !is_bad_inode(inode)) {
/* to avoid evict_inode call simultaneously */
atomic_inc(&inode->i_count);
spin_unlock(&inode->i_lock);
/* some remained atomic pages should discarded */
if (f2fs_is_atomic_file(inode))
drop_inmem_pages(inode);
/* should remain fi->extent_tree for writepage */
f2fs_destroy_extent_node(inode);
sb_start_intwrite(inode->i_sb);
f2fs_i_size_write(inode, 0);
if (F2FS_HAS_BLOCKS(inode))
f2fs_truncate(inode);
sb_end_intwrite(inode->i_sb);
fscrypt_put_encryption_info(inode, NULL);
spin_lock(&inode->i_lock);
atomic_dec(&inode->i_count);
}
trace_f2fs_drop_inode(inode, 0);
return 0;
}
ret = generic_drop_inode(inode);
trace_f2fs_drop_inode(inode, ret);
return ret;
}
int f2fs_inode_dirtied(struct inode *inode, bool sync)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
int ret = 0;
spin_lock(&sbi->inode_lock[DIRTY_META]);
if (is_inode_flag_set(inode, FI_DIRTY_INODE)) {
ret = 1;
} else {
set_inode_flag(inode, FI_DIRTY_INODE);
stat_inc_dirty_inode(sbi, DIRTY_META);
}
if (sync && list_empty(&F2FS_I(inode)->gdirty_list)) {
list_add_tail(&F2FS_I(inode)->gdirty_list,
&sbi->inode_list[DIRTY_META]);
inc_page_count(sbi, F2FS_DIRTY_IMETA);
}
spin_unlock(&sbi->inode_lock[DIRTY_META]);
return ret;
}
void f2fs_inode_synced(struct inode *inode)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
spin_lock(&sbi->inode_lock[DIRTY_META]);
if (!is_inode_flag_set(inode, FI_DIRTY_INODE)) {
spin_unlock(&sbi->inode_lock[DIRTY_META]);
return;
}
if (!list_empty(&F2FS_I(inode)->gdirty_list)) {
list_del_init(&F2FS_I(inode)->gdirty_list);
dec_page_count(sbi, F2FS_DIRTY_IMETA);
}
clear_inode_flag(inode, FI_DIRTY_INODE);
clear_inode_flag(inode, FI_AUTO_RECOVER);
stat_dec_dirty_inode(F2FS_I_SB(inode), DIRTY_META);
spin_unlock(&sbi->inode_lock[DIRTY_META]);
}
/*
* f2fs_dirty_inode() is called from __mark_inode_dirty()
*
* We should call set_dirty_inode to write the dirty inode through write_inode.
*/
static void f2fs_dirty_inode(struct inode *inode, int flags)
{
struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
if (inode->i_ino == F2FS_NODE_INO(sbi) ||
inode->i_ino == F2FS_META_INO(sbi))
return;
if (flags == I_DIRTY_TIME)
return;
if (is_inode_flag_set(inode, FI_AUTO_RECOVER))
clear_inode_flag(inode, FI_AUTO_RECOVER);
f2fs_inode_dirtied(inode, false);
}
static void f2fs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(f2fs_inode_cachep, F2FS_I(inode));
}
static void f2fs_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, f2fs_i_callback);
}
static void destroy_percpu_info(struct f2fs_sb_info *sbi)
{
percpu_counter_destroy(&sbi->alloc_valid_block_count);
percpu_counter_destroy(&sbi->total_valid_inode_count);
}
static void destroy_device_list(struct f2fs_sb_info *sbi)
{
int i;
for (i = 0; i < sbi->s_ndevs; i++) {
blkdev_put(FDEV(i).bdev, FMODE_EXCL);
#ifdef CONFIG_BLK_DEV_ZONED
kfree(FDEV(i).blkz_type);
#endif
}
kfree(sbi->devs);
}
static void f2fs_put_super(struct super_block *sb)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
int i;
f2fs_quota_off_umount(sb);
/* prevent remaining shrinker jobs */
mutex_lock(&sbi->umount_mutex);
/*
* We don't need to do checkpoint when superblock is clean.
* But, the previous checkpoint was not done by umount, it needs to do
* clean checkpoint again.
*/
if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) ||
!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
struct cp_control cpc = {
.reason = CP_UMOUNT,
};
write_checkpoint(sbi, &cpc);
}
/* be sure to wait for any on-going discard commands */
f2fs_wait_discard_bios(sbi, true);
if (f2fs_discard_en(sbi) && !sbi->discard_blks) {
struct cp_control cpc = {
.reason = CP_UMOUNT | CP_TRIMMED,
};
write_checkpoint(sbi, &cpc);
}
/* write_checkpoint can update stat informaion */
f2fs_destroy_stats(sbi);
/*
* normally superblock is clean, so we need to release this.
* In addition, EIO will skip do checkpoint, we need this as well.
*/
release_ino_entry(sbi, true);
f2fs_leave_shrinker(sbi);
mutex_unlock(&sbi->umount_mutex);
/* our cp_error case, we can wait for any writeback page */
f2fs_flush_merged_writes(sbi);
iput(sbi->node_inode);
iput(sbi->meta_inode);
/* destroy f2fs internal modules */
destroy_node_manager(sbi);
destroy_segment_manager(sbi);
kfree(sbi->ckpt);
f2fs_unregister_sysfs(sbi);
sb->s_fs_info = NULL;
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->raw_super);
destroy_device_list(sbi);
mempool_destroy(sbi->write_io_dummy);
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
destroy_percpu_info(sbi);
for (i = 0; i < NR_PAGE_TYPE; i++)
kfree(sbi->write_io[i]);
kfree(sbi);
}
int f2fs_sync_fs(struct super_block *sb, int sync)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
int err = 0;
trace_f2fs_sync_fs(sb, sync);
if (unlikely(is_sbi_flag_set(sbi, SBI_POR_DOING)))
return -EAGAIN;
if (sync) {
struct cp_control cpc;
cpc.reason = __get_cp_reason(sbi);
mutex_lock(&sbi->gc_mutex);
err = write_checkpoint(sbi, &cpc);
mutex_unlock(&sbi->gc_mutex);
}
f2fs_trace_ios(NULL, 1);
return err;
}
static int f2fs_freeze(struct super_block *sb)
{
if (f2fs_readonly(sb))
return 0;
/* IO error happened before */
if (unlikely(f2fs_cp_error(F2FS_SB(sb))))
return -EIO;
/* must be clean, since sync_filesystem() was already called */
if (is_sbi_flag_set(F2FS_SB(sb), SBI_IS_DIRTY))
return -EINVAL;
return 0;
}
static int f2fs_unfreeze(struct super_block *sb)
{
return 0;
}
#ifdef CONFIG_QUOTA
static int f2fs_statfs_project(struct super_block *sb,
kprojid_t projid, struct kstatfs *buf)
{
struct kqid qid;
struct dquot *dquot;
u64 limit;
u64 curblock;
qid = make_kqid_projid(projid);
dquot = dqget(sb, qid);
if (IS_ERR(dquot))
return PTR_ERR(dquot);
spin_lock(&dq_data_lock);
limit = (dquot->dq_dqb.dqb_bsoftlimit ?
dquot->dq_dqb.dqb_bsoftlimit :
dquot->dq_dqb.dqb_bhardlimit) >> sb->s_blocksize_bits;
if (limit && buf->f_blocks > limit) {
curblock = dquot->dq_dqb.dqb_curspace >> sb->s_blocksize_bits;
buf->f_blocks = limit;
buf->f_bfree = buf->f_bavail =
(buf->f_blocks > curblock) ?
(buf->f_blocks - curblock) : 0;
}
limit = dquot->dq_dqb.dqb_isoftlimit ?
dquot->dq_dqb.dqb_isoftlimit :
dquot->dq_dqb.dqb_ihardlimit;
if (limit && buf->f_files > limit) {
buf->f_files = limit;
buf->f_ffree =
(buf->f_files > dquot->dq_dqb.dqb_curinodes) ?
(buf->f_files - dquot->dq_dqb.dqb_curinodes) : 0;
}
spin_unlock(&dq_data_lock);
dqput(dquot);
return 0;
}
#endif
static int f2fs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct f2fs_sb_info *sbi = F2FS_SB(sb);
u64 id = huge_encode_dev(sb->s_bdev->bd_dev);
block_t total_count, user_block_count, start_count, ovp_count;
u64 avail_node_count;
total_count = le64_to_cpu(sbi->raw_super->block_count);
user_block_count = sbi->user_block_count;
start_count = le32_to_cpu(sbi->raw_super->segment0_blkaddr);
ovp_count = SM_I(sbi)->ovp_segments << sbi->log_blocks_per_seg;
buf->f_type = F2FS_SUPER_MAGIC;
buf->f_bsize = sbi->blocksize;
buf->f_blocks = total_count - start_count;
buf->f_bfree = user_block_count - valid_user_blocks(sbi) + ovp_count;
buf->f_bavail = user_block_count - valid_user_blocks(sbi) -
sbi->reserved_blocks;
avail_node_count = sbi->total_node_count - F2FS_RESERVED_NODE_NUM;
if (avail_node_count > user_block_count) {
buf->f_files = user_block_count;
buf->f_ffree = buf->f_bavail;
} else {
buf->f_files = avail_node_count;
buf->f_ffree = min(avail_node_count - valid_node_count(sbi),
buf->f_bavail);
}
buf->f_namelen = F2FS_NAME_LEN;
buf->f_fsid.val[0] = (u32)id;
buf->f_fsid.val[1] = (u32)(id >> 32);
#ifdef CONFIG_QUOTA
if (is_inode_flag_set(dentry->d_inode, FI_PROJ_INHERIT) &&
sb_has_quota_limits_enabled(sb, PRJQUOTA)) {
f2fs_statfs_project(sb, F2FS_I(dentry->d_inode)->i_projid, buf);
}
#endif
return 0;
}
static inline void f2fs_show_quota_options(struct seq_file *seq,
struct super_block *sb)
{
#ifdef CONFIG_QUOTA
struct f2fs_sb_info *sbi = F2FS_SB(sb);
if (sbi->s_jquota_fmt) {
char *fmtname = "";
switch (sbi->s_jquota_fmt) {
case QFMT_VFS_OLD:
fmtname = "vfsold";
break;
case QFMT_VFS_V0:
fmtname = "vfsv0";
break;
case QFMT_VFS_V1:
fmtname = "vfsv1";
break;
}
seq_printf(seq, ",jqfmt=%s", fmtname);
}
if (sbi->s_qf_names[USRQUOTA])
seq_show_option(seq, "usrjquota", sbi->s_qf_names[USRQUOTA]);
if (sbi->s_qf_names[GRPQUOTA])
seq_show_option(seq, "grpjquota", sbi->s_qf_names[GRPQUOTA]);
if (sbi->s_qf_names[PRJQUOTA])
seq_show_option(seq, "prjjquota", sbi->s_qf_names[PRJQUOTA]);
#endif
}
static int f2fs_show_options(struct seq_file *seq, struct dentry *root)
{
struct f2fs_sb_info *sbi = F2FS_SB(root->d_sb);
if (!f2fs_readonly(sbi->sb) && test_opt(sbi, BG_GC)) {
if (test_opt(sbi, FORCE_FG_GC))
seq_printf(seq, ",background_gc=%s", "sync");
else
seq_printf(seq, ",background_gc=%s", "on");
} else {
seq_printf(seq, ",background_gc=%s", "off");
}
if (test_opt(sbi, DISABLE_ROLL_FORWARD))
seq_puts(seq, ",disable_roll_forward");
if (test_opt(sbi, DISCARD))
seq_puts(seq, ",discard");
if (test_opt(sbi, NOHEAP))
seq_puts(seq, ",no_heap");
else
seq_puts(seq, ",heap");
#ifdef CONFIG_F2FS_FS_XATTR
if (test_opt(sbi, XATTR_USER))
seq_puts(seq, ",user_xattr");
else
seq_puts(seq, ",nouser_xattr");
if (test_opt(sbi, INLINE_XATTR))
seq_puts(seq, ",inline_xattr");
else
seq_puts(seq, ",noinline_xattr");
#endif
#ifdef CONFIG_F2FS_FS_POSIX_ACL
if (test_opt(sbi, POSIX_ACL))
seq_puts(seq, ",acl");
else
seq_puts(seq, ",noacl");
#endif
if (test_opt(sbi, DISABLE_EXT_IDENTIFY))
seq_puts(seq, ",disable_ext_identify");
if (test_opt(sbi, INLINE_DATA))
seq_puts(seq, ",inline_data");
else
seq_puts(seq, ",noinline_data");
if (test_opt(sbi, INLINE_DENTRY))
seq_puts(seq, ",inline_dentry");
else
seq_puts(seq, ",noinline_dentry");
if (!f2fs_readonly(sbi->sb) && test_opt(sbi, FLUSH_MERGE))
seq_puts(seq, ",flush_merge");
if (test_opt(sbi, NOBARRIER))
seq_puts(seq, ",nobarrier");
if (test_opt(sbi, FASTBOOT))
seq_puts(seq, ",fastboot");
if (test_opt(sbi, EXTENT_CACHE))
seq_puts(seq, ",extent_cache");
else
seq_puts(seq, ",noextent_cache");
if (test_opt(sbi, DATA_FLUSH))
seq_puts(seq, ",data_flush");
seq_puts(seq, ",mode=");
if (test_opt(sbi, ADAPTIVE))
seq_puts(seq, "adaptive");
else if (test_opt(sbi, LFS))
seq_puts(seq, "lfs");
seq_printf(seq, ",active_logs=%u", sbi->active_logs);
if (F2FS_IO_SIZE_BITS(sbi))
seq_printf(seq, ",io_size=%uKB", F2FS_IO_SIZE_KB(sbi));
#ifdef CONFIG_F2FS_FAULT_INJECTION
if (test_opt(sbi, FAULT_INJECTION))
seq_printf(seq, ",fault_injection=%u",
sbi->fault_info.inject_rate);
#endif
#ifdef CONFIG_QUOTA
if (test_opt(sbi, QUOTA))
seq_puts(seq, ",quota");
if (test_opt(sbi, USRQUOTA))
seq_puts(seq, ",usrquota");
if (test_opt(sbi, GRPQUOTA))
seq_puts(seq, ",grpquota");
if (test_opt(sbi, PRJQUOTA))
seq_puts(seq, ",prjquota");
#endif
f2fs_show_quota_options(seq, sbi->sb);
return 0;
}
static void default_options(struct f2fs_sb_info *sbi)
{
/* init some FS parameters */
sbi->active_logs = NR_CURSEG_TYPE;
set_opt(sbi, BG_GC);
set_opt(sbi, INLINE_XATTR);
set_opt(sbi, INLINE_DATA);
set_opt(sbi, INLINE_DENTRY);
set_opt(sbi, EXTENT_CACHE);
set_opt(sbi, NOHEAP);
sbi->sb->s_flags |= MS_LAZYTIME;
set_opt(sbi, FLUSH_MERGE);
if (f2fs_sb_mounted_blkzoned(sbi->sb)) {
set_opt_mode(sbi, F2FS_MOUNT_LFS);
set_opt(sbi, DISCARD);
} else {
set_opt_mode(sbi, F2FS_MOUNT_ADAPTIVE);
}
#ifdef CONFIG_F2FS_FS_XATTR
set_opt(sbi, XATTR_USER);
#endif
#ifdef CONFIG_F2FS_FS_POSIX_ACL
set_opt(sbi, POSIX_ACL);
#endif
#ifdef CONFIG_F2FS_FAULT_INJECTION
f2fs_build_fault_attr(sbi, 0);
#endif
}
static int f2fs_remount(struct super_block *sb, int *flags, char *data)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
struct f2fs_mount_info org_mount_opt;
unsigned long old_sb_flags;
int err, active_logs;
bool need_restart_gc = false;
bool need_stop_gc = false;
bool no_extent_cache = !test_opt(sbi, EXTENT_CACHE);
#ifdef CONFIG_F2FS_FAULT_INJECTION
struct f2fs_fault_info ffi = sbi->fault_info;
#endif
#ifdef CONFIG_QUOTA
int s_jquota_fmt;
char *s_qf_names[MAXQUOTAS];
int i, j;
#endif
/*
* Save the old mount options in case we
* need to restore them.
*/
org_mount_opt = sbi->mount_opt;
old_sb_flags = sb->s_flags;
active_logs = sbi->active_logs;
#ifdef CONFIG_QUOTA
s_jquota_fmt = sbi->s_jquota_fmt;
for (i = 0; i < MAXQUOTAS; i++) {
if (sbi->s_qf_names[i]) {
s_qf_names[i] = kstrdup(sbi->s_qf_names[i],
GFP_KERNEL);
if (!s_qf_names[i]) {
for (j = 0; j < i; j++)
kfree(s_qf_names[j]);
return -ENOMEM;
}
} else {
s_qf_names[i] = NULL;
}
}
#endif
/* recover superblocks we couldn't write due to previous RO mount */
if (!(*flags & MS_RDONLY) && is_sbi_flag_set(sbi, SBI_NEED_SB_WRITE)) {
err = f2fs_commit_super(sbi, false);
f2fs_msg(sb, KERN_INFO,
"Try to recover all the superblocks, ret: %d", err);
if (!err)
clear_sbi_flag(sbi, SBI_NEED_SB_WRITE);
}
default_options(sbi);
/* parse mount options */
err = parse_options(sb, data);
if (err)
goto restore_opts;
/*
* Previous and new state of filesystem is RO,
* so skip checking GC and FLUSH_MERGE conditions.
*/
if (f2fs_readonly(sb) && (*flags & MS_RDONLY))
goto skip;
if (!f2fs_readonly(sb) && (*flags & MS_RDONLY)) {
err = dquot_suspend(sb, -1);
if (err < 0)
goto restore_opts;
} else {
/* dquot_resume needs RW */
sb->s_flags &= ~MS_RDONLY;
dquot_resume(sb, -1);
}
/* disallow enable/disable extent_cache dynamically */
if (no_extent_cache == !!test_opt(sbi, EXTENT_CACHE)) {
err = -EINVAL;
f2fs_msg(sbi->sb, KERN_WARNING,
"switch extent_cache option is not allowed");
goto restore_opts;
}
/*
* We stop the GC thread if FS is mounted as RO
* or if background_gc = off is passed in mount
* option. Also sync the filesystem.
*/
if ((*flags & MS_RDONLY) || !test_opt(sbi, BG_GC)) {
if (sbi->gc_thread) {
stop_gc_thread(sbi);
need_restart_gc = true;
}
} else if (!sbi->gc_thread) {
err = start_gc_thread(sbi);
if (err)
goto restore_opts;
need_stop_gc = true;
}
if (*flags & MS_RDONLY) {
writeback_inodes_sb(sb, WB_REASON_SYNC);
sync_inodes_sb(sb);
set_sbi_flag(sbi, SBI_IS_DIRTY);
set_sbi_flag(sbi, SBI_IS_CLOSE);
f2fs_sync_fs(sb, 1);
clear_sbi_flag(sbi, SBI_IS_CLOSE);
}
/*
* We stop issue flush thread if FS is mounted as RO
* or if flush_merge is not passed in mount option.
*/
if ((*flags & MS_RDONLY) || !test_opt(sbi, FLUSH_MERGE)) {
clear_opt(sbi, FLUSH_MERGE);
destroy_flush_cmd_control(sbi, false);
} else {
err = create_flush_cmd_control(sbi);
if (err)
goto restore_gc;
}
skip:
#ifdef CONFIG_QUOTA
/* Release old quota file names */
for (i = 0; i < MAXQUOTAS; i++)
kfree(s_qf_names[i]);
#endif
/* Update the POSIXACL Flag */
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0);
return 0;
restore_gc:
if (need_restart_gc) {
if (start_gc_thread(sbi))
f2fs_msg(sbi->sb, KERN_WARNING,
"background gc thread has stopped");
} else if (need_stop_gc) {
stop_gc_thread(sbi);
}
restore_opts:
#ifdef CONFIG_QUOTA
sbi->s_jquota_fmt = s_jquota_fmt;
for (i = 0; i < MAXQUOTAS; i++) {
kfree(sbi->s_qf_names[i]);
sbi->s_qf_names[i] = s_qf_names[i];
}
#endif
sbi->mount_opt = org_mount_opt;
sbi->active_logs = active_logs;
sb->s_flags = old_sb_flags;
#ifdef CONFIG_F2FS_FAULT_INJECTION
sbi->fault_info = ffi;
#endif
return err;
}
#ifdef CONFIG_QUOTA
/* Read data from quotafile */
static ssize_t f2fs_quota_read(struct super_block *sb, int type, char *data,
size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
struct address_space *mapping = inode->i_mapping;
block_t blkidx = F2FS_BYTES_TO_BLK(off);
int offset = off & (sb->s_blocksize - 1);
int tocopy;
size_t toread;
loff_t i_size = i_size_read(inode);
struct page *page;
char *kaddr;
if (off > i_size)
return 0;
if (off + len > i_size)
len = i_size - off;
toread = len;
while (toread > 0) {
tocopy = min_t(unsigned long, sb->s_blocksize - offset, toread);
repeat:
page = read_mapping_page(mapping, blkidx, NULL);
if (IS_ERR(page))
return PTR_ERR(page);
lock_page(page);
if (unlikely(page->mapping != mapping)) {
f2fs_put_page(page, 1);
goto repeat;
}
if (unlikely(!PageUptodate(page))) {
f2fs_put_page(page, 1);
return -EIO;
}
kaddr = kmap_atomic(page);
memcpy(data, kaddr + offset, tocopy);
kunmap_atomic(kaddr);
f2fs_put_page(page, 1);
offset = 0;
toread -= tocopy;
data += tocopy;
blkidx++;
}
return len;
}
/* Write to quotafile */
static ssize_t f2fs_quota_write(struct super_block *sb, int type,
const char *data, size_t len, loff_t off)
{
struct inode *inode = sb_dqopt(sb)->files[type];
struct address_space *mapping = inode->i_mapping;
const struct address_space_operations *a_ops = mapping->a_ops;
int offset = off & (sb->s_blocksize - 1);
size_t towrite = len;
struct page *page;
char *kaddr;
int err = 0;
int tocopy;
while (towrite > 0) {
tocopy = min_t(unsigned long, sb->s_blocksize - offset,
towrite);
err = a_ops->write_begin(NULL, mapping, off, tocopy, 0,
&page, NULL);
if (unlikely(err))
break;
kaddr = kmap_atomic(page);
memcpy(kaddr + offset, data, tocopy);
kunmap_atomic(kaddr);
flush_dcache_page(page);
a_ops->write_end(NULL, mapping, off, tocopy, tocopy,
page, NULL);
offset = 0;
towrite -= tocopy;
off += tocopy;
data += tocopy;
cond_resched();
}
if (len == towrite)
return 0;
inode->i_version++;
inode->i_mtime = inode->i_ctime = current_time(inode);
f2fs_mark_inode_dirty_sync(inode, false);
return len - towrite;
}
static struct dquot **f2fs_get_dquots(struct inode *inode)
{
return F2FS_I(inode)->i_dquot;
}
static qsize_t *f2fs_get_reserved_space(struct inode *inode)
{
return &F2FS_I(inode)->i_reserved_quota;
}
static int f2fs_quota_on_mount(struct f2fs_sb_info *sbi, int type)
{
return dquot_quota_on_mount(sbi->sb, sbi->s_qf_names[type],
sbi->s_jquota_fmt, type);
}
void f2fs_enable_quota_files(struct f2fs_sb_info *sbi)
{
int i, ret;
for (i = 0; i < MAXQUOTAS; i++) {
if (sbi->s_qf_names[i]) {
ret = f2fs_quota_on_mount(sbi, i);
if (ret < 0)
f2fs_msg(sbi->sb, KERN_ERR,
"Cannot turn on journaled "
"quota: error %d", ret);
}
}
}
static int f2fs_quota_sync(struct super_block *sb, int type)
{
struct quota_info *dqopt = sb_dqopt(sb);
int cnt;
int ret;
ret = dquot_writeback_dquots(sb, type);
if (ret)
return ret;
/*
* Now when everything is written we can discard the pagecache so
* that userspace sees the changes.
*/
for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
if (type != -1 && cnt != type)
continue;
if (!sb_has_quota_active(sb, cnt))
continue;
ret = filemap_write_and_wait(dqopt->files[cnt]->i_mapping);
if (ret)
return ret;
inode_lock(dqopt->files[cnt]);
truncate_inode_pages(&dqopt->files[cnt]->i_data, 0);
inode_unlock(dqopt->files[cnt]);
}
return 0;
}
static int f2fs_quota_on(struct super_block *sb, int type, int format_id,
const struct path *path)
{
struct inode *inode;
int err;
err = f2fs_quota_sync(sb, type);
if (err)
return err;
err = dquot_quota_on(sb, type, format_id, path);
if (err)
return err;
inode = d_inode(path->dentry);
inode_lock(inode);
F2FS_I(inode)->i_flags |= FS_NOATIME_FL | FS_IMMUTABLE_FL;
inode_set_flags(inode, S_NOATIME | S_IMMUTABLE,
S_NOATIME | S_IMMUTABLE);
inode_unlock(inode);
f2fs_mark_inode_dirty_sync(inode, false);
return 0;
}
static int f2fs_quota_off(struct super_block *sb, int type)
{
struct inode *inode = sb_dqopt(sb)->files[type];
int err;
if (!inode || !igrab(inode))
return dquot_quota_off(sb, type);
f2fs_quota_sync(sb, type);
err = dquot_quota_off(sb, type);
if (err)
goto out_put;
inode_lock(inode);
F2FS_I(inode)->i_flags &= ~(FS_NOATIME_FL | FS_IMMUTABLE_FL);
inode_set_flags(inode, 0, S_NOATIME | S_IMMUTABLE);
inode_unlock(inode);
f2fs_mark_inode_dirty_sync(inode, false);
out_put:
iput(inode);
return err;
}
void f2fs_quota_off_umount(struct super_block *sb)
{
int type;
for (type = 0; type < MAXQUOTAS; type++)
f2fs_quota_off(sb, type);
}
int f2fs_get_projid(struct inode *inode, kprojid_t *projid)
{
*projid = F2FS_I(inode)->i_projid;
return 0;
}
static const struct dquot_operations f2fs_quota_operations = {
.get_reserved_space = f2fs_get_reserved_space,
.write_dquot = dquot_commit,
.acquire_dquot = dquot_acquire,
.release_dquot = dquot_release,
.mark_dirty = dquot_mark_dquot_dirty,
.write_info = dquot_commit_info,
.alloc_dquot = dquot_alloc,
.destroy_dquot = dquot_destroy,
.get_projid = f2fs_get_projid,
.get_next_id = dquot_get_next_id,
};
static const struct quotactl_ops f2fs_quotactl_ops = {
.quota_on = f2fs_quota_on,
.quota_off = f2fs_quota_off,
.quota_sync = f2fs_quota_sync,
.get_state = dquot_get_state,
.set_info = dquot_set_dqinfo,
.get_dqblk = dquot_get_dqblk,
.set_dqblk = dquot_set_dqblk,
.get_nextdqblk = dquot_get_next_dqblk,
};
#else
void f2fs_quota_off_umount(struct super_block *sb)
{
}
#endif
static const struct super_operations f2fs_sops = {
.alloc_inode = f2fs_alloc_inode,
.drop_inode = f2fs_drop_inode,
.destroy_inode = f2fs_destroy_inode,
.write_inode = f2fs_write_inode,
.dirty_inode = f2fs_dirty_inode,
.show_options = f2fs_show_options,
#ifdef CONFIG_QUOTA
.quota_read = f2fs_quota_read,
.quota_write = f2fs_quota_write,
.get_dquots = f2fs_get_dquots,
#endif
.evict_inode = f2fs_evict_inode,
.put_super = f2fs_put_super,
.sync_fs = f2fs_sync_fs,
.freeze_fs = f2fs_freeze,
.unfreeze_fs = f2fs_unfreeze,
.statfs = f2fs_statfs,
.remount_fs = f2fs_remount,
};
#ifdef CONFIG_F2FS_FS_ENCRYPTION
static int f2fs_get_context(struct inode *inode, void *ctx, size_t len)
{
return f2fs_getxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION,
F2FS_XATTR_NAME_ENCRYPTION_CONTEXT,
ctx, len, NULL);
}
static int f2fs_set_context(struct inode *inode, const void *ctx, size_t len,
void *fs_data)
{
return f2fs_setxattr(inode, F2FS_XATTR_INDEX_ENCRYPTION,
F2FS_XATTR_NAME_ENCRYPTION_CONTEXT,
ctx, len, fs_data, XATTR_CREATE);
}
static unsigned f2fs_max_namelen(struct inode *inode)
{
return S_ISLNK(inode->i_mode) ?
inode->i_sb->s_blocksize : F2FS_NAME_LEN;
}
static const struct fscrypt_operations f2fs_cryptops = {
.key_prefix = "f2fs:",
.get_context = f2fs_get_context,
.set_context = f2fs_set_context,
.is_encrypted = f2fs_encrypted_inode,
.empty_dir = f2fs_empty_dir,
.max_namelen = f2fs_max_namelen,
};
#else
static const struct fscrypt_operations f2fs_cryptops = {
.is_encrypted = f2fs_encrypted_inode,
};
#endif
static struct inode *f2fs_nfs_get_inode(struct super_block *sb,
u64 ino, u32 generation)
{
struct f2fs_sb_info *sbi = F2FS_SB(sb);
struct inode *inode;
if (check_nid_range(sbi, ino))
return ERR_PTR(-ESTALE);
/*
* f2fs_iget isn't quite right if the inode is currently unallocated!
* However f2fs_iget currently does appropriate checks to handle stale
* inodes so everything is OK.
*/
inode = f2fs_iget(sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
if (unlikely(generation && inode->i_generation != generation)) {
/* we didn't find the right inode.. */
iput(inode);
return ERR_PTR(-ESTALE);
}
return inode;
}
static struct dentry *f2fs_fh_to_dentry(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
f2fs_nfs_get_inode);
}
static struct dentry *f2fs_fh_to_parent(struct super_block *sb, struct fid *fid,
int fh_len, int fh_type)
{
return generic_fh_to_parent(sb, fid, fh_len, fh_type,
f2fs_nfs_get_inode);
}
static const struct export_operations f2fs_export_ops = {
.fh_to_dentry = f2fs_fh_to_dentry,
.fh_to_parent = f2fs_fh_to_parent,
.get_parent = f2fs_get_parent,
};
static loff_t max_file_blocks(void)
{
loff_t result = 0;
loff_t leaf_count = ADDRS_PER_BLOCK;
/*
* note: previously, result is equal to (DEF_ADDRS_PER_INODE -
* F2FS_INLINE_XATTR_ADDRS), but now f2fs try to reserve more
* space in inode.i_addr, it will be more safe to reassign
* result as zero.
*/
/* two direct node blocks */
result += (leaf_count * 2);
/* two indirect node blocks */
leaf_count *= NIDS_PER_BLOCK;
result += (leaf_count * 2);
/* one double indirect node block */
leaf_count *= NIDS_PER_BLOCK;
result += leaf_count;
return result;
}
static int __f2fs_commit_super(struct buffer_head *bh,
struct f2fs_super_block *super)
{
lock_buffer(bh);
if (super)
memcpy(bh->b_data + F2FS_SUPER_OFFSET, super, sizeof(*super));
set_buffer_uptodate(bh);
set_buffer_dirty(bh);
unlock_buffer(bh);
/* it's rare case, we can do fua all the time */
return __sync_dirty_buffer(bh, REQ_SYNC | REQ_PREFLUSH | REQ_FUA);
}
static inline bool sanity_check_area_boundary(struct f2fs_sb_info *sbi,
struct buffer_head *bh)
{
struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
(bh->b_data + F2FS_SUPER_OFFSET);
struct super_block *sb = sbi->sb;
u32 segment0_blkaddr = le32_to_cpu(raw_super->segment0_blkaddr);
u32 cp_blkaddr = le32_to_cpu(raw_super->cp_blkaddr);
u32 sit_blkaddr = le32_to_cpu(raw_super->sit_blkaddr);
u32 nat_blkaddr = le32_to_cpu(raw_super->nat_blkaddr);
u32 ssa_blkaddr = le32_to_cpu(raw_super->ssa_blkaddr);
u32 main_blkaddr = le32_to_cpu(raw_super->main_blkaddr);
u32 segment_count_ckpt = le32_to_cpu(raw_super->segment_count_ckpt);
u32 segment_count_sit = le32_to_cpu(raw_super->segment_count_sit);
u32 segment_count_nat = le32_to_cpu(raw_super->segment_count_nat);
u32 segment_count_ssa = le32_to_cpu(raw_super->segment_count_ssa);
u32 segment_count_main = le32_to_cpu(raw_super->segment_count_main);
u32 segment_count = le32_to_cpu(raw_super->segment_count);
u32 log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
u64 main_end_blkaddr = main_blkaddr +
(segment_count_main << log_blocks_per_seg);
u64 seg_end_blkaddr = segment0_blkaddr +
(segment_count << log_blocks_per_seg);
if (segment0_blkaddr != cp_blkaddr) {
f2fs_msg(sb, KERN_INFO,
"Mismatch start address, segment0(%u) cp_blkaddr(%u)",
segment0_blkaddr, cp_blkaddr);
return true;
}
if (cp_blkaddr + (segment_count_ckpt << log_blocks_per_seg) !=
sit_blkaddr) {
f2fs_msg(sb, KERN_INFO,
"Wrong CP boundary, start(%u) end(%u) blocks(%u)",
cp_blkaddr, sit_blkaddr,
segment_count_ckpt << log_blocks_per_seg);
return true;
}
if (sit_blkaddr + (segment_count_sit << log_blocks_per_seg) !=
nat_blkaddr) {
f2fs_msg(sb, KERN_INFO,
"Wrong SIT boundary, start(%u) end(%u) blocks(%u)",
sit_blkaddr, nat_blkaddr,
segment_count_sit << log_blocks_per_seg);
return true;
}
if (nat_blkaddr + (segment_count_nat << log_blocks_per_seg) !=
ssa_blkaddr) {
f2fs_msg(sb, KERN_INFO,
"Wrong NAT boundary, start(%u) end(%u) blocks(%u)",
nat_blkaddr, ssa_blkaddr,
segment_count_nat << log_blocks_per_seg);
return true;
}
if (ssa_blkaddr + (segment_count_ssa << log_blocks_per_seg) !=
main_blkaddr) {
f2fs_msg(sb, KERN_INFO,
"Wrong SSA boundary, start(%u) end(%u) blocks(%u)",
ssa_blkaddr, main_blkaddr,
segment_count_ssa << log_blocks_per_seg);
return true;
}
if (main_end_blkaddr > seg_end_blkaddr) {
f2fs_msg(sb, KERN_INFO,
"Wrong MAIN_AREA boundary, start(%u) end(%u) block(%u)",
main_blkaddr,
segment0_blkaddr +
(segment_count << log_blocks_per_seg),
segment_count_main << log_blocks_per_seg);
return true;
} else if (main_end_blkaddr < seg_end_blkaddr) {
int err = 0;
char *res;
/* fix in-memory information all the time */
raw_super->segment_count = cpu_to_le32((main_end_blkaddr -
segment0_blkaddr) >> log_blocks_per_seg);
if (f2fs_readonly(sb) || bdev_read_only(sb->s_bdev)) {
set_sbi_flag(sbi, SBI_NEED_SB_WRITE);
res = "internally";
} else {
err = __f2fs_commit_super(bh, NULL);
res = err ? "failed" : "done";
}
f2fs_msg(sb, KERN_INFO,
"Fix alignment : %s, start(%u) end(%u) block(%u)",
res, main_blkaddr,
segment0_blkaddr +
(segment_count << log_blocks_per_seg),
segment_count_main << log_blocks_per_seg);
if (err)
return true;
}
return false;
}
static int sanity_check_raw_super(struct f2fs_sb_info *sbi,
struct buffer_head *bh)
{
struct f2fs_super_block *raw_super = (struct f2fs_super_block *)
(bh->b_data + F2FS_SUPER_OFFSET);
struct super_block *sb = sbi->sb;
unsigned int blocksize;
if (F2FS_SUPER_MAGIC != le32_to_cpu(raw_super->magic)) {
f2fs_msg(sb, KERN_INFO,
"Magic Mismatch, valid(0x%x) - read(0x%x)",
F2FS_SUPER_MAGIC, le32_to_cpu(raw_super->magic));
return 1;
}
/* Currently, support only 4KB page cache size */
if (F2FS_BLKSIZE != PAGE_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid page_cache_size (%lu), supports only 4KB\n",
PAGE_SIZE);
return 1;
}
/* Currently, support only 4KB block size */
blocksize = 1 << le32_to_cpu(raw_super->log_blocksize);
if (blocksize != F2FS_BLKSIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid blocksize (%u), supports only 4KB\n",
blocksize);
return 1;
}
/* check log blocks per segment */
if (le32_to_cpu(raw_super->log_blocks_per_seg) != 9) {
f2fs_msg(sb, KERN_INFO,
"Invalid log blocks per segment (%u)\n",
le32_to_cpu(raw_super->log_blocks_per_seg));
return 1;
}
/* Currently, support 512/1024/2048/4096 bytes sector size */
if (le32_to_cpu(raw_super->log_sectorsize) >
F2FS_MAX_LOG_SECTOR_SIZE ||
le32_to_cpu(raw_super->log_sectorsize) <
F2FS_MIN_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO, "Invalid log sectorsize (%u)",
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
if (le32_to_cpu(raw_super->log_sectors_per_block) +
le32_to_cpu(raw_super->log_sectorsize) !=
F2FS_MAX_LOG_SECTOR_SIZE) {
f2fs_msg(sb, KERN_INFO,
"Invalid log sectors per block(%u) log sectorsize(%u)",
le32_to_cpu(raw_super->log_sectors_per_block),
le32_to_cpu(raw_super->log_sectorsize));
return 1;
}
/* check reserved ino info */
if (le32_to_cpu(raw_super->node_ino) != 1 ||
le32_to_cpu(raw_super->meta_ino) != 2 ||
le32_to_cpu(raw_super->root_ino) != 3) {
f2fs_msg(sb, KERN_INFO,
"Invalid Fs Meta Ino: node(%u) meta(%u) root(%u)",
le32_to_cpu(raw_super->node_ino),
le32_to_cpu(raw_super->meta_ino),
le32_to_cpu(raw_super->root_ino));
return 1;
}
if (le32_to_cpu(raw_super->segment_count) > F2FS_MAX_SEGMENT) {
f2fs_msg(sb, KERN_INFO,
"Invalid segment count (%u)",
le32_to_cpu(raw_super->segment_count));
return 1;
}
/* check CP/SIT/NAT/SSA/MAIN_AREA area boundary */
if (sanity_check_area_boundary(sbi, bh))
return 1;
return 0;
}
int sanity_check_ckpt(struct f2fs_sb_info *sbi)
{
unsigned int total, fsmeta;
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
struct f2fs_checkpoint *ckpt = F2FS_CKPT(sbi);
unsigned int ovp_segments, reserved_segments;
unsigned int main_segs, blocks_per_seg;
int i;
total = le32_to_cpu(raw_super->segment_count);
fsmeta = le32_to_cpu(raw_super->segment_count_ckpt);
fsmeta += le32_to_cpu(raw_super->segment_count_sit);
fsmeta += le32_to_cpu(raw_super->segment_count_nat);
fsmeta += le32_to_cpu(ckpt->rsvd_segment_count);
fsmeta += le32_to_cpu(raw_super->segment_count_ssa);
if (unlikely(fsmeta >= total))
return 1;
ovp_segments = le32_to_cpu(ckpt->overprov_segment_count);
reserved_segments = le32_to_cpu(ckpt->rsvd_segment_count);
if (unlikely(fsmeta < F2FS_MIN_SEGMENTS ||
ovp_segments == 0 || reserved_segments == 0)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Wrong layout: check mkfs.f2fs version");
return 1;
}
main_segs = le32_to_cpu(raw_super->segment_count_main);
blocks_per_seg = sbi->blocks_per_seg;
for (i = 0; i < NR_CURSEG_NODE_TYPE; i++) {
if (le32_to_cpu(ckpt->cur_node_segno[i]) >= main_segs ||
le16_to_cpu(ckpt->cur_node_blkoff[i]) >= blocks_per_seg)
return 1;
}
for (i = 0; i < NR_CURSEG_DATA_TYPE; i++) {
if (le32_to_cpu(ckpt->cur_data_segno[i]) >= main_segs ||
le16_to_cpu(ckpt->cur_data_blkoff[i]) >= blocks_per_seg)
return 1;
}
if (unlikely(f2fs_cp_error(sbi))) {
f2fs_msg(sbi->sb, KERN_ERR, "A bug case: need to run fsck");
return 1;
}
return 0;
}
static void init_sb_info(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = sbi->raw_super;
int i, j;
sbi->log_sectors_per_block =
le32_to_cpu(raw_super->log_sectors_per_block);
sbi->log_blocksize = le32_to_cpu(raw_super->log_blocksize);
sbi->blocksize = 1 << sbi->log_blocksize;
sbi->log_blocks_per_seg = le32_to_cpu(raw_super->log_blocks_per_seg);
sbi->blocks_per_seg = 1 << sbi->log_blocks_per_seg;
sbi->segs_per_sec = le32_to_cpu(raw_super->segs_per_sec);
sbi->secs_per_zone = le32_to_cpu(raw_super->secs_per_zone);
sbi->total_sections = le32_to_cpu(raw_super->section_count);
sbi->total_node_count =
(le32_to_cpu(raw_super->segment_count_nat) / 2)
* sbi->blocks_per_seg * NAT_ENTRY_PER_BLOCK;
sbi->root_ino_num = le32_to_cpu(raw_super->root_ino);
sbi->node_ino_num = le32_to_cpu(raw_super->node_ino);
sbi->meta_ino_num = le32_to_cpu(raw_super->meta_ino);
sbi->cur_victim_sec = NULL_SECNO;
sbi->max_victim_search = DEF_MAX_VICTIM_SEARCH;
sbi->dir_level = DEF_DIR_LEVEL;
sbi->interval_time[CP_TIME] = DEF_CP_INTERVAL;
sbi->interval_time[REQ_TIME] = DEF_IDLE_INTERVAL;
clear_sbi_flag(sbi, SBI_NEED_FSCK);
for (i = 0; i < NR_COUNT_TYPE; i++)
atomic_set(&sbi->nr_pages[i], 0);
atomic_set(&sbi->wb_sync_req, 0);
INIT_LIST_HEAD(&sbi->s_list);
mutex_init(&sbi->umount_mutex);
for (i = 0; i < NR_PAGE_TYPE - 1; i++)
for (j = HOT; j < NR_TEMP_TYPE; j++)
mutex_init(&sbi->wio_mutex[i][j]);
spin_lock_init(&sbi->cp_lock);
}
static int init_percpu_info(struct f2fs_sb_info *sbi)
{
int err;
err = percpu_counter_init(&sbi->alloc_valid_block_count, 0, GFP_KERNEL);
if (err)
return err;
return percpu_counter_init(&sbi->total_valid_inode_count, 0,
GFP_KERNEL);
}
#ifdef CONFIG_BLK_DEV_ZONED
static int init_blkz_info(struct f2fs_sb_info *sbi, int devi)
{
struct block_device *bdev = FDEV(devi).bdev;
sector_t nr_sectors = bdev->bd_part->nr_sects;
sector_t sector = 0;
struct blk_zone *zones;
unsigned int i, nr_zones;
unsigned int n = 0;
int err = -EIO;
if (!f2fs_sb_mounted_blkzoned(sbi->sb))
return 0;
if (sbi->blocks_per_blkz && sbi->blocks_per_blkz !=
SECTOR_TO_BLOCK(bdev_zone_sectors(bdev)))
return -EINVAL;
sbi->blocks_per_blkz = SECTOR_TO_BLOCK(bdev_zone_sectors(bdev));
if (sbi->log_blocks_per_blkz && sbi->log_blocks_per_blkz !=
__ilog2_u32(sbi->blocks_per_blkz))
return -EINVAL;
sbi->log_blocks_per_blkz = __ilog2_u32(sbi->blocks_per_blkz);
FDEV(devi).nr_blkz = SECTOR_TO_BLOCK(nr_sectors) >>
sbi->log_blocks_per_blkz;
if (nr_sectors & (bdev_zone_sectors(bdev) - 1))
FDEV(devi).nr_blkz++;
FDEV(devi).blkz_type = kmalloc(FDEV(devi).nr_blkz, GFP_KERNEL);
if (!FDEV(devi).blkz_type)
return -ENOMEM;
#define F2FS_REPORT_NR_ZONES 4096
zones = kcalloc(F2FS_REPORT_NR_ZONES, sizeof(struct blk_zone),
GFP_KERNEL);
if (!zones)
return -ENOMEM;
/* Get block zones type */
while (zones && sector < nr_sectors) {
nr_zones = F2FS_REPORT_NR_ZONES;
err = blkdev_report_zones(bdev, sector,
zones, &nr_zones,
GFP_KERNEL);
if (err)
break;
if (!nr_zones) {
err = -EIO;
break;
}
for (i = 0; i < nr_zones; i++) {
FDEV(devi).blkz_type[n] = zones[i].type;
sector += zones[i].len;
n++;
}
}
kfree(zones);
return err;
}
#endif
/*
* Read f2fs raw super block.
* Because we have two copies of super block, so read both of them
* to get the first valid one. If any one of them is broken, we pass
* them recovery flag back to the caller.
*/
static int read_raw_super_block(struct f2fs_sb_info *sbi,
struct f2fs_super_block **raw_super,
int *valid_super_block, int *recovery)
{
struct super_block *sb = sbi->sb;
int block;
struct buffer_head *bh;
struct f2fs_super_block *super;
int err = 0;
super = kzalloc(sizeof(struct f2fs_super_block), GFP_KERNEL);
if (!super)
return -ENOMEM;
for (block = 0; block < 2; block++) {
bh = sb_bread(sb, block);
if (!bh) {
f2fs_msg(sb, KERN_ERR, "Unable to read %dth superblock",
block + 1);
err = -EIO;
continue;
}
/* sanity checking of raw super */
if (sanity_check_raw_super(sbi, bh)) {
f2fs_msg(sb, KERN_ERR,
"Can't find valid F2FS filesystem in %dth superblock",
block + 1);
err = -EINVAL;
brelse(bh);
continue;
}
if (!*raw_super) {
memcpy(super, bh->b_data + F2FS_SUPER_OFFSET,
sizeof(*super));
*valid_super_block = block;
*raw_super = super;
}
brelse(bh);
}
/* Fail to read any one of the superblocks*/
if (err < 0)
*recovery = 1;
/* No valid superblock */
if (!*raw_super)
kfree(super);
else
err = 0;
return err;
}
int f2fs_commit_super(struct f2fs_sb_info *sbi, bool recover)
{
struct buffer_head *bh;
int err;
if ((recover && f2fs_readonly(sbi->sb)) ||
bdev_read_only(sbi->sb->s_bdev)) {
set_sbi_flag(sbi, SBI_NEED_SB_WRITE);
return -EROFS;
}
/* write back-up superblock first */
bh = sb_getblk(sbi->sb, sbi->valid_super_block ? 0: 1);
if (!bh)
return -EIO;
err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi));
brelse(bh);
/* if we are in recovery path, skip writing valid superblock */
if (recover || err)
return err;
/* write current valid superblock */
bh = sb_getblk(sbi->sb, sbi->valid_super_block);
if (!bh)
return -EIO;
err = __f2fs_commit_super(bh, F2FS_RAW_SUPER(sbi));
brelse(bh);
return err;
}
static int f2fs_scan_devices(struct f2fs_sb_info *sbi)
{
struct f2fs_super_block *raw_super = F2FS_RAW_SUPER(sbi);
unsigned int max_devices = MAX_DEVICES;
int i;
/* Initialize single device information */
if (!RDEV(0).path[0]) {
if (!bdev_is_zoned(sbi->sb->s_bdev))
return 0;
max_devices = 1;
}
/*
* Initialize multiple devices information, or single
* zoned block device information.
*/
sbi->devs = kcalloc(max_devices, sizeof(struct f2fs_dev_info),
GFP_KERNEL);
if (!sbi->devs)
return -ENOMEM;
for (i = 0; i < max_devices; i++) {
if (i > 0 && !RDEV(i).path[0])
break;
if (max_devices == 1) {
/* Single zoned block device mount */
FDEV(0).bdev =
blkdev_get_by_dev(sbi->sb->s_bdev->bd_dev,
sbi->sb->s_mode, sbi->sb->s_type);
} else {
/* Multi-device mount */
memcpy(FDEV(i).path, RDEV(i).path, MAX_PATH_LEN);
FDEV(i).total_segments =
le32_to_cpu(RDEV(i).total_segments);
if (i == 0) {
FDEV(i).start_blk = 0;
FDEV(i).end_blk = FDEV(i).start_blk +
(FDEV(i).total_segments <<
sbi->log_blocks_per_seg) - 1 +
le32_to_cpu(raw_super->segment0_blkaddr);
} else {
FDEV(i).start_blk = FDEV(i - 1).end_blk + 1;
FDEV(i).end_blk = FDEV(i).start_blk +
(FDEV(i).total_segments <<
sbi->log_blocks_per_seg) - 1;
}
FDEV(i).bdev = blkdev_get_by_path(FDEV(i).path,
sbi->sb->s_mode, sbi->sb->s_type);
}
if (IS_ERR(FDEV(i).bdev))
return PTR_ERR(FDEV(i).bdev);
/* to release errored devices */
sbi->s_ndevs = i + 1;
#ifdef CONFIG_BLK_DEV_ZONED
if (bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HM &&
!f2fs_sb_mounted_blkzoned(sbi->sb)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Zoned block device feature not enabled\n");
return -EINVAL;
}
if (bdev_zoned_model(FDEV(i).bdev) != BLK_ZONED_NONE) {
if (init_blkz_info(sbi, i)) {
f2fs_msg(sbi->sb, KERN_ERR,
"Failed to initialize F2FS blkzone information");
return -EINVAL;
}
if (max_devices == 1)
break;
f2fs_msg(sbi->sb, KERN_INFO,
"Mount Device [%2d]: %20s, %8u, %8x - %8x (zone: %s)",
i, FDEV(i).path,
FDEV(i).total_segments,
FDEV(i).start_blk, FDEV(i).end_blk,
bdev_zoned_model(FDEV(i).bdev) == BLK_ZONED_HA ?
"Host-aware" : "Host-managed");
continue;
}
#endif
f2fs_msg(sbi->sb, KERN_INFO,
"Mount Device [%2d]: %20s, %8u, %8x - %8x",
i, FDEV(i).path,
FDEV(i).total_segments,
FDEV(i).start_blk, FDEV(i).end_blk);
}
f2fs_msg(sbi->sb, KERN_INFO,
"IO Block Size: %8d KB", F2FS_IO_SIZE_KB(sbi));
return 0;
}
static int f2fs_fill_super(struct super_block *sb, void *data, int silent)
{
struct f2fs_sb_info *sbi;
struct f2fs_super_block *raw_super;
struct inode *root;
int err;
bool retry = true, need_fsck = false;
char *options = NULL;
int recovery, i, valid_super_block;
struct curseg_info *seg_i;
try_onemore:
err = -EINVAL;
raw_super = NULL;
valid_super_block = -1;
recovery = 0;
/* allocate memory for f2fs-specific super block info */
sbi = kzalloc(sizeof(struct f2fs_sb_info), GFP_KERNEL);
if (!sbi)
return -ENOMEM;
sbi->sb = sb;
/* Load the checksum driver */
sbi->s_chksum_driver = crypto_alloc_shash("crc32", 0, 0);
if (IS_ERR(sbi->s_chksum_driver)) {
f2fs_msg(sb, KERN_ERR, "Cannot load crc32 driver.");
err = PTR_ERR(sbi->s_chksum_driver);
sbi->s_chksum_driver = NULL;
goto free_sbi;
}
/* set a block size */
if (unlikely(!sb_set_blocksize(sb, F2FS_BLKSIZE))) {
f2fs_msg(sb, KERN_ERR, "unable to set blocksize");
goto free_sbi;
}
err = read_raw_super_block(sbi, &raw_super, &valid_super_block,
&recovery);
if (err)
goto free_sbi;
sb->s_fs_info = sbi;
sbi->raw_super = raw_super;
/* precompute checksum seed for metadata */
if (f2fs_sb_has_inode_chksum(sb))
sbi->s_chksum_seed = f2fs_chksum(sbi, ~0, raw_super->uuid,
sizeof(raw_super->uuid));
/*
* The BLKZONED feature indicates that the drive was formatted with
* zone alignment optimization. This is optional for host-aware
* devices, but mandatory for host-managed zoned block devices.
*/
#ifndef CONFIG_BLK_DEV_ZONED
if (f2fs_sb_mounted_blkzoned(sb)) {
f2fs_msg(sb, KERN_ERR,
"Zoned block device support is not enabled\n");
err = -EOPNOTSUPP;
goto free_sb_buf;
}
#endif
default_options(sbi);
/* parse mount options */
options = kstrdup((const char *)data, GFP_KERNEL);
if (data && !options) {
err = -ENOMEM;
goto free_sb_buf;
}
err = parse_options(sb, options);
if (err)
goto free_options;
sbi->max_file_blocks = max_file_blocks();
sb->s_maxbytes = sbi->max_file_blocks <<
le32_to_cpu(raw_super->log_blocksize);
sb->s_max_links = F2FS_LINK_MAX;
get_random_bytes(&sbi->s_next_generation, sizeof(u32));
#ifdef CONFIG_QUOTA
sb->dq_op = &f2fs_quota_operations;
sb->s_qcop = &f2fs_quotactl_ops;
sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP | QTYPE_MASK_PRJ;
#endif
sb->s_op = &f2fs_sops;
sb->s_cop = &f2fs_cryptops;
sb->s_xattr = f2fs_xattr_handlers;
sb->s_export_op = &f2fs_export_ops;
sb->s_magic = F2FS_SUPER_MAGIC;
sb->s_time_gran = 1;
sb->s_flags = (sb->s_flags & ~MS_POSIXACL) |
(test_opt(sbi, POSIX_ACL) ? MS_POSIXACL : 0);
memcpy(&sb->s_uuid, raw_super->uuid, sizeof(raw_super->uuid));
/* init f2fs-specific super block info */
sbi->valid_super_block = valid_super_block;
mutex_init(&sbi->gc_mutex);
mutex_init(&sbi->cp_mutex);
init_rwsem(&sbi->node_write);
init_rwsem(&sbi->node_change);
/* disallow all the data/node/meta page writes */
set_sbi_flag(sbi, SBI_POR_DOING);
spin_lock_init(&sbi->stat_lock);
/* init iostat info */
spin_lock_init(&sbi->iostat_lock);
sbi->iostat_enable = false;
for (i = 0; i < NR_PAGE_TYPE; i++) {
int n = (i == META) ? 1: NR_TEMP_TYPE;
int j;
sbi->write_io[i] = kmalloc(n * sizeof(struct f2fs_bio_info),
GFP_KERNEL);
if (!sbi->write_io[i]) {
err = -ENOMEM;
goto free_options;
}
for (j = HOT; j < n; j++) {
init_rwsem(&sbi->write_io[i][j].io_rwsem);
sbi->write_io[i][j].sbi = sbi;
sbi->write_io[i][j].bio = NULL;
spin_lock_init(&sbi->write_io[i][j].io_lock);
INIT_LIST_HEAD(&sbi->write_io[i][j].io_list);
}
}
init_rwsem(&sbi->cp_rwsem);
init_waitqueue_head(&sbi->cp_wait);
init_sb_info(sbi);
err = init_percpu_info(sbi);
if (err)
goto free_options;
if (F2FS_IO_SIZE(sbi) > 1) {
sbi->write_io_dummy =
mempool_create_page_pool(2 * (F2FS_IO_SIZE(sbi) - 1), 0);
if (!sbi->write_io_dummy) {
err = -ENOMEM;
goto free_options;
}
}
/* get an inode for meta space */
sbi->meta_inode = f2fs_iget(sb, F2FS_META_INO(sbi));
if (IS_ERR(sbi->meta_inode)) {
f2fs_msg(sb, KERN_ERR, "Failed to read F2FS meta data inode");
err = PTR_ERR(sbi->meta_inode);
goto free_io_dummy;
}
err = get_valid_checkpoint(sbi);
if (err) {
f2fs_msg(sb, KERN_ERR, "Failed to get valid F2FS checkpoint");
goto free_meta_inode;
}
/* Initialize device list */
err = f2fs_scan_devices(sbi);
if (err) {
f2fs_msg(sb, KERN_ERR, "Failed to find devices");
goto free_devices;
}
sbi->total_valid_node_count =
le32_to_cpu(sbi->ckpt->valid_node_count);
percpu_counter_set(&sbi->total_valid_inode_count,
le32_to_cpu(sbi->ckpt->valid_inode_count));
sbi->user_block_count = le64_to_cpu(sbi->ckpt->user_block_count);
sbi->total_valid_block_count =
le64_to_cpu(sbi->ckpt->valid_block_count);
sbi->last_valid_block_count = sbi->total_valid_block_count;
sbi->reserved_blocks = 0;
for (i = 0; i < NR_INODE_TYPE; i++) {
INIT_LIST_HEAD(&sbi->inode_list[i]);
spin_lock_init(&sbi->inode_lock[i]);
}
init_extent_cache_info(sbi);
init_ino_entry_info(sbi);
/* setup f2fs internal modules */
err = build_segment_manager(sbi);
if (err) {
f2fs_msg(sb, KERN_ERR,
"Failed to initialize F2FS segment manager");
goto free_sm;
}
err = build_node_manager(sbi);
if (err) {
f2fs_msg(sb, KERN_ERR,
"Failed to initialize F2FS node manager");
goto free_nm;
}
/* For write statistics */
if (sb->s_bdev->bd_part)
sbi->sectors_written_start =
(u64)part_stat_read(sb->s_bdev->bd_part, sectors[1]);
/* Read accumulated write IO statistics if exists */
seg_i = CURSEG_I(sbi, CURSEG_HOT_NODE);
if (__exist_node_summaries(sbi))
sbi->kbytes_written =
le64_to_cpu(seg_i->journal->info.kbytes_written);
build_gc_manager(sbi);
/* get an inode for node space */
sbi->node_inode = f2fs_iget(sb, F2FS_NODE_INO(sbi));
if (IS_ERR(sbi->node_inode)) {
f2fs_msg(sb, KERN_ERR, "Failed to read node inode");
err = PTR_ERR(sbi->node_inode);
goto free_nm;
}
f2fs_join_shrinker(sbi);
err = f2fs_build_stats(sbi);
if (err)
goto free_nm;
/* read root inode and dentry */
root = f2fs_iget(sb, F2FS_ROOT_INO(sbi));
if (IS_ERR(root)) {
f2fs_msg(sb, KERN_ERR, "Failed to read root inode");
err = PTR_ERR(root);
goto free_node_inode;
}
if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) {
iput(root);
err = -EINVAL;
goto free_node_inode;
}
sb->s_root = d_make_root(root); /* allocate root dentry */
if (!sb->s_root) {
err = -ENOMEM;
goto free_root_inode;
}
err = f2fs_register_sysfs(sbi);
if (err)
goto free_root_inode;
/* if there are nt orphan nodes free them */
err = recover_orphan_inodes(sbi);
if (err)
goto free_sysfs;
/* recover fsynced data */
if (!test_opt(sbi, DISABLE_ROLL_FORWARD)) {
/*
* mount should be failed, when device has readonly mode, and
* previous checkpoint was not done by clean system shutdown.
*/
if (bdev_read_only(sb->s_bdev) &&
!is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) {
err = -EROFS;
goto free_meta;
}
if (need_fsck)
set_sbi_flag(sbi, SBI_NEED_FSCK);
if (!retry)
goto skip_recovery;
err = recover_fsync_data(sbi, false);
if (err < 0) {
need_fsck = true;
f2fs_msg(sb, KERN_ERR,
"Cannot recover all fsync data errno=%d", err);
goto free_meta;
}
} else {
err = recover_fsync_data(sbi, true);
if (!f2fs_readonly(sb) && err > 0) {
err = -EINVAL;
f2fs_msg(sb, KERN_ERR,
"Need to recover fsync data");
goto free_sysfs;
}
}
skip_recovery:
/* recover_fsync_data() cleared this already */
clear_sbi_flag(sbi, SBI_POR_DOING);
/*
* If filesystem is not mounted as read-only then
* do start the gc_thread.
*/
if (test_opt(sbi, BG_GC) && !f2fs_readonly(sb)) {
/* After POR, we can run background GC thread.*/
err = start_gc_thread(sbi);
if (err)
goto free_meta;
}
kfree(options);
/* recover broken superblock */
if (recovery) {
err = f2fs_commit_super(sbi, true);
f2fs_msg(sb, KERN_INFO,
"Try to recover %dth superblock, ret: %d",
sbi->valid_super_block ? 1 : 2, err);
}
f2fs_msg(sbi->sb, KERN_NOTICE, "Mounted with checkpoint version = %llx",
cur_cp_version(F2FS_CKPT(sbi)));
f2fs_update_time(sbi, CP_TIME);
f2fs_update_time(sbi, REQ_TIME);
return 0;
free_meta:
f2fs_sync_inode_meta(sbi);
/*
* Some dirty meta pages can be produced by recover_orphan_inodes()
* failed by EIO. Then, iput(node_inode) can trigger balance_fs_bg()
* followed by write_checkpoint() through f2fs_write_node_pages(), which
* falls into an infinite loop in sync_meta_pages().
*/
truncate_inode_pages_final(META_MAPPING(sbi));
free_sysfs:
f2fs_unregister_sysfs(sbi);
free_root_inode:
dput(sb->s_root);
sb->s_root = NULL;
free_node_inode:
truncate_inode_pages_final(NODE_MAPPING(sbi));
mutex_lock(&sbi->umount_mutex);
release_ino_entry(sbi, true);
f2fs_leave_shrinker(sbi);
iput(sbi->node_inode);
mutex_unlock(&sbi->umount_mutex);
f2fs_destroy_stats(sbi);
free_nm:
destroy_node_manager(sbi);
free_sm:
destroy_segment_manager(sbi);
free_devices:
destroy_device_list(sbi);
kfree(sbi->ckpt);
free_meta_inode:
make_bad_inode(sbi->meta_inode);
iput(sbi->meta_inode);
free_io_dummy:
mempool_destroy(sbi->write_io_dummy);
free_options:
for (i = 0; i < NR_PAGE_TYPE; i++)
kfree(sbi->write_io[i]);
destroy_percpu_info(sbi);
#ifdef CONFIG_QUOTA
for (i = 0; i < MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
kfree(options);
free_sb_buf:
kfree(raw_super);
free_sbi:
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi);
/* give only one another chance */
if (retry) {
retry = false;
shrink_dcache_sb(sb);
goto try_onemore;
}
return err;
}
static struct dentry *f2fs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *data)
{
return mount_bdev(fs_type, flags, dev_name, data, f2fs_fill_super);
}
static void kill_f2fs_super(struct super_block *sb)
{
if (sb->s_root) {
set_sbi_flag(F2FS_SB(sb), SBI_IS_CLOSE);
stop_gc_thread(F2FS_SB(sb));
stop_discard_thread(F2FS_SB(sb));
}
kill_block_super(sb);
}
static struct file_system_type f2fs_fs_type = {
.owner = THIS_MODULE,
.name = "f2fs",
.mount = f2fs_mount,
.kill_sb = kill_f2fs_super,
.fs_flags = FS_REQUIRES_DEV,
};
MODULE_ALIAS_FS("f2fs");
static int __init init_inodecache(void)
{
f2fs_inode_cachep = kmem_cache_create("f2fs_inode_cache",
sizeof(struct f2fs_inode_info), 0,
SLAB_RECLAIM_ACCOUNT|SLAB_ACCOUNT, NULL);
if (!f2fs_inode_cachep)
return -ENOMEM;
return 0;
}
static void destroy_inodecache(void)
{
/*
* Make sure all delayed rcu free inodes are flushed before we
* destroy cache.
*/
rcu_barrier();
kmem_cache_destroy(f2fs_inode_cachep);
}
static int __init init_f2fs_fs(void)
{
int err;
f2fs_build_trace_ios();
err = init_inodecache();
if (err)
goto fail;
err = create_node_manager_caches();
if (err)
goto free_inodecache;
err = create_segment_manager_caches();
if (err)
goto free_node_manager_caches;
err = create_checkpoint_caches();
if (err)
goto free_segment_manager_caches;
err = create_extent_cache();
if (err)
goto free_checkpoint_caches;
err = f2fs_init_sysfs();
if (err)
goto free_extent_cache;
err = register_shrinker(&f2fs_shrinker_info);
if (err)
goto free_sysfs;
err = register_filesystem(&f2fs_fs_type);
if (err)
goto free_shrinker;
err = f2fs_create_root_stats();
if (err)
goto free_filesystem;
return 0;
free_filesystem:
unregister_filesystem(&f2fs_fs_type);
free_shrinker:
unregister_shrinker(&f2fs_shrinker_info);
free_sysfs:
f2fs_exit_sysfs();
free_extent_cache:
destroy_extent_cache();
free_checkpoint_caches:
destroy_checkpoint_caches();
free_segment_manager_caches:
destroy_segment_manager_caches();
free_node_manager_caches:
destroy_node_manager_caches();
free_inodecache:
destroy_inodecache();
fail:
return err;
}
static void __exit exit_f2fs_fs(void)
{
f2fs_destroy_root_stats();
unregister_filesystem(&f2fs_fs_type);
unregister_shrinker(&f2fs_shrinker_info);
f2fs_exit_sysfs();
destroy_extent_cache();
destroy_checkpoint_caches();
destroy_segment_manager_caches();
destroy_node_manager_caches();
destroy_inodecache();
f2fs_destroy_trace_ios();
}
module_init(init_f2fs_fs)
module_exit(exit_f2fs_fs)
MODULE_AUTHOR("Samsung Electronics's Praesto Team");
MODULE_DESCRIPTION("Flash Friendly File System");
MODULE_LICENSE("GPL");
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_3012_2 |
crossvul-cpp_data_good_4904_0 | /*-
* Copyright (c) 2004-2013 Tim Kientzle
* Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
* Copyright (c) 2013 Konrad Kleine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "archive_platform.h"
__FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_zip.c 201102 2009-12-28 03:11:36Z kientzle $");
/*
* The definitive documentation of the Zip file format is:
* http://www.pkware.com/documents/casestudies/APPNOTE.TXT
*
* The Info-Zip project has pioneered various extensions to better
* support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
* "Ux", and 0x7875 "ux" extensions for time and ownership
* information.
*
* History of this code: The streaming Zip reader was first added to
* libarchive in January 2005. Support for seekable input sources was
* added in Nov 2011. Zip64 support (including a significant code
* refactoring) was added in 2014.
*/
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_ZLIB_H
#include <zlib.h>
#endif
#include "archive.h"
#include "archive_digest_private.h"
#include "archive_cryptor_private.h"
#include "archive_endian.h"
#include "archive_entry.h"
#include "archive_entry_locale.h"
#include "archive_hmac_private.h"
#include "archive_private.h"
#include "archive_rb.h"
#include "archive_read_private.h"
#ifndef HAVE_ZLIB_H
#include "archive_crc32.h"
#endif
struct zip_entry {
struct archive_rb_node node;
struct zip_entry *next;
int64_t local_header_offset;
int64_t compressed_size;
int64_t uncompressed_size;
int64_t gid;
int64_t uid;
struct archive_string rsrcname;
time_t mtime;
time_t atime;
time_t ctime;
uint32_t crc32;
uint16_t mode;
uint16_t zip_flags; /* From GP Flags Field */
unsigned char compression;
unsigned char system; /* From "version written by" */
unsigned char flags; /* Our extra markers. */
unsigned char decdat;/* Used for Decryption check */
/* WinZip AES encryption extra field should be available
* when compression is 99. */
struct {
/* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
unsigned vendor;
#define AES_VENDOR_AE_1 0x0001
#define AES_VENDOR_AE_2 0x0002
/* AES encryption strength:
* 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
unsigned strength;
/* Actual compression method. */
unsigned char compression;
} aes_extra;
};
struct trad_enc_ctx {
uint32_t keys[3];
};
/* Bits used in zip_flags. */
#define ZIP_ENCRYPTED (1 << 0)
#define ZIP_LENGTH_AT_END (1 << 3)
#define ZIP_STRONG_ENCRYPTED (1 << 6)
#define ZIP_UTF8_NAME (1 << 11)
/* See "7.2 Single Password Symmetric Encryption Method"
in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
#define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
/* Bits used in flags. */
#define LA_USED_ZIP64 (1 << 0)
#define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
/*
* See "WinZip - AES Encryption Information"
* http://www.winzip.com/aes_info.htm
*/
/* Value used in compression method. */
#define WINZIP_AES_ENCRYPTION 99
/* Authentication code size. */
#define AUTH_CODE_SIZE 10
/**/
#define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
struct zip {
/* Structural information about the archive. */
struct archive_string format_name;
int64_t central_directory_offset;
size_t central_directory_entries_total;
size_t central_directory_entries_on_this_disk;
int has_encrypted_entries;
/* List of entries (seekable Zip only) */
struct zip_entry *zip_entries;
struct archive_rb_tree tree;
struct archive_rb_tree tree_rsrc;
/* Bytes read but not yet consumed via __archive_read_consume() */
size_t unconsumed;
/* Information about entry we're currently reading. */
struct zip_entry *entry;
int64_t entry_bytes_remaining;
/* These count the number of bytes actually read for the entry. */
int64_t entry_compressed_bytes_read;
int64_t entry_uncompressed_bytes_read;
/* Running CRC32 of the decompressed data */
unsigned long entry_crc32;
unsigned long (*crc32func)(unsigned long, const void *,
size_t);
char ignore_crc32;
/* Flags to mark progress of decompression. */
char decompress_init;
char end_of_entry;
#ifdef HAVE_ZLIB_H
unsigned char *uncompressed_buffer;
size_t uncompressed_buffer_size;
z_stream stream;
char stream_valid;
#endif
struct archive_string_conv *sconv;
struct archive_string_conv *sconv_default;
struct archive_string_conv *sconv_utf8;
int init_default_conversion;
int process_mac_extensions;
char init_decryption;
/* Decryption buffer. */
unsigned char *decrypted_buffer;
unsigned char *decrypted_ptr;
size_t decrypted_buffer_size;
size_t decrypted_bytes_remaining;
size_t decrypted_unconsumed_bytes;
/* Traditional PKWARE decryption. */
struct trad_enc_ctx tctx;
char tctx_valid;
/* WinZip AES decyption. */
/* Contexts used for AES decryption. */
archive_crypto_ctx cctx;
char cctx_valid;
archive_hmac_sha1_ctx hctx;
char hctx_valid;
/* Strong encryption's decryption header information. */
unsigned iv_size;
unsigned alg_id;
unsigned bit_len;
unsigned flags;
unsigned erd_size;
unsigned v_size;
unsigned v_crc32;
uint8_t *iv;
uint8_t *erd;
uint8_t *v_data;
};
/* Many systems define min or MIN, but not all. */
#define zipmin(a,b) ((a) < (b) ? (a) : (b))
/* ------------------------------------------------------------------------ */
/*
Traditional PKWARE Decryption functions.
*/
static void
trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
{
uint8_t t;
#define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
ctx->keys[0] = CRC32(ctx->keys[0], c);
ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
t = (ctx->keys[1] >> 24) & 0xff;
ctx->keys[2] = CRC32(ctx->keys[2], t);
#undef CRC32
}
static uint8_t
trad_enc_decypt_byte(struct trad_enc_ctx *ctx)
{
unsigned temp = ctx->keys[2] | 2;
return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
}
static void
trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
size_t in_len, uint8_t *out, size_t out_len)
{
unsigned i, max;
max = (unsigned)((in_len < out_len)? in_len: out_len);
for (i = 0; i < max; i++) {
uint8_t t = in[i] ^ trad_enc_decypt_byte(ctx);
out[i] = t;
trad_enc_update_keys(ctx, t);
}
}
static int
trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
const uint8_t *key, size_t key_len, uint8_t *crcchk)
{
uint8_t header[12];
if (key_len < 12) {
*crcchk = 0xff;
return -1;
}
ctx->keys[0] = 305419896L;
ctx->keys[1] = 591751049L;
ctx->keys[2] = 878082192L;
for (;pw_len; --pw_len)
trad_enc_update_keys(ctx, *pw++);
trad_enc_decrypt_update(ctx, key, 12, header, 12);
/* Return the last byte for CRC check. */
*crcchk = header[11];
return 0;
}
#if 0
static void
crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
int key_size)
{
#define MD_SIZE 20
archive_sha1_ctx ctx;
unsigned char md1[MD_SIZE];
unsigned char md2[MD_SIZE * 2];
unsigned char mkb[64];
int i;
archive_sha1_init(&ctx);
archive_sha1_update(&ctx, p, size);
archive_sha1_final(&ctx, md1);
memset(mkb, 0x36, sizeof(mkb));
for (i = 0; i < MD_SIZE; i++)
mkb[i] ^= md1[i];
archive_sha1_init(&ctx);
archive_sha1_update(&ctx, mkb, sizeof(mkb));
archive_sha1_final(&ctx, md2);
memset(mkb, 0x5C, sizeof(mkb));
for (i = 0; i < MD_SIZE; i++)
mkb[i] ^= md1[i];
archive_sha1_init(&ctx);
archive_sha1_update(&ctx, mkb, sizeof(mkb));
archive_sha1_final(&ctx, md2 + MD_SIZE);
if (key_size > 32)
key_size = 32;
memcpy(key, md2, key_size);
#undef MD_SIZE
}
#endif
/*
* Common code for streaming or seeking modes.
*
* Includes code to read local file headers, decompress data
* from entry bodies, and common API.
*/
static unsigned long
real_crc32(unsigned long crc, const void *buff, size_t len)
{
return crc32(crc, buff, (unsigned int)len);
}
/* Used by "ignorecrc32" option to speed up tests. */
static unsigned long
fake_crc32(unsigned long crc, const void *buff, size_t len)
{
(void)crc; /* UNUSED */
(void)buff; /* UNUSED */
(void)len; /* UNUSED */
return 0;
}
static struct {
int id;
const char * name;
} compression_methods[] = {
{0, "uncompressed"}, /* The file is stored (no compression) */
{1, "shrinking"}, /* The file is Shrunk */
{2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
{3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
{4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
{5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
{6, "imploded"}, /* The file is Imploded */
{7, "reserved"}, /* Reserved for Tokenizing compression algorithm */
{8, "deflation"}, /* The file is Deflated */
{9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
{10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
* (old IBM TERSE) */
{11, "reserved"}, /* Reserved by PKWARE */
{12, "bzip"}, /* File is compressed using BZIP2 algorithm */
{13, "reserved"}, /* Reserved by PKWARE */
{14, "lzma"}, /* LZMA (EFS) */
{15, "reserved"}, /* Reserved by PKWARE */
{16, "reserved"}, /* Reserved by PKWARE */
{17, "reserved"}, /* Reserved by PKWARE */
{18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
{19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
{97, "wav-pack"}, /* WavPack compressed data */
{98, "ppmd-1"}, /* PPMd version I, Rev 1 */
{99, "aes"} /* WinZip AES encryption */
};
static const char *
compression_name(const int compression)
{
static const int num_compression_methods =
sizeof(compression_methods)/sizeof(compression_methods[0]);
int i=0;
while(compression >= 0 && i < num_compression_methods) {
if (compression_methods[i].id == compression)
return compression_methods[i].name;
i++;
}
return "??";
}
/* Convert an MSDOS-style date/time into Unix-style time. */
static time_t
zip_time(const char *p)
{
int msTime, msDate;
struct tm ts;
msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
memset(&ts, 0, sizeof(ts));
ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
ts.tm_mday = msDate & 0x1f; /* Day of month. */
ts.tm_hour = (msTime >> 11) & 0x1f;
ts.tm_min = (msTime >> 5) & 0x3f;
ts.tm_sec = (msTime << 1) & 0x3e;
ts.tm_isdst = -1;
return mktime(&ts);
}
/*
* The extra data is stored as a list of
* id1+size1+data1 + id2+size2+data2 ...
* triplets. id and size are 2 bytes each.
*/
static void
process_extra(const char *p, size_t extra_length, struct zip_entry* zip_entry)
{
unsigned offset = 0;
while (offset < extra_length - 4) {
unsigned short headerid = archive_le16dec(p + offset);
unsigned short datasize = archive_le16dec(p + offset + 2);
offset += 4;
if (offset + datasize > extra_length) {
break;
}
#ifdef DEBUG
fprintf(stderr, "Header id 0x%04x, length %d\n",
headerid, datasize);
#endif
switch (headerid) {
case 0x0001:
/* Zip64 extended information extra field. */
zip_entry->flags |= LA_USED_ZIP64;
if (zip_entry->uncompressed_size == 0xffffffff) {
if (datasize < 8)
break;
zip_entry->uncompressed_size =
archive_le64dec(p + offset);
offset += 8;
datasize -= 8;
}
if (zip_entry->compressed_size == 0xffffffff) {
if (datasize < 8)
break;
zip_entry->compressed_size =
archive_le64dec(p + offset);
offset += 8;
datasize -= 8;
}
if (zip_entry->local_header_offset == 0xffffffff) {
if (datasize < 8)
break;
zip_entry->local_header_offset =
archive_le64dec(p + offset);
offset += 8;
datasize -= 8;
}
/* archive_le32dec(p + offset) gives disk
* on which file starts, but we don't handle
* multi-volume Zip files. */
break;
#ifdef DEBUG
case 0x0017:
{
/* Strong encryption field. */
if (archive_le16dec(p + offset) == 2) {
unsigned algId =
archive_le16dec(p + offset + 2);
unsigned bitLen =
archive_le16dec(p + offset + 4);
int flags =
archive_le16dec(p + offset + 6);
fprintf(stderr, "algId=0x%04x, bitLen=%u, "
"flgas=%d\n", algId, bitLen,flags);
}
break;
}
#endif
case 0x5455:
{
/* Extended time field "UT". */
int flags = p[offset];
offset++;
datasize--;
/* Flag bits indicate which dates are present. */
if (flags & 0x01)
{
#ifdef DEBUG
fprintf(stderr, "mtime: %lld -> %d\n",
(long long)zip_entry->mtime,
archive_le32dec(p + offset));
#endif
if (datasize < 4)
break;
zip_entry->mtime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
if (flags & 0x02)
{
if (datasize < 4)
break;
zip_entry->atime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
if (flags & 0x04)
{
if (datasize < 4)
break;
zip_entry->ctime = archive_le32dec(p + offset);
offset += 4;
datasize -= 4;
}
break;
}
case 0x5855:
{
/* Info-ZIP Unix Extra Field (old version) "UX". */
if (datasize >= 8) {
zip_entry->atime = archive_le32dec(p + offset);
zip_entry->mtime =
archive_le32dec(p + offset + 4);
}
if (datasize >= 12) {
zip_entry->uid =
archive_le16dec(p + offset + 8);
zip_entry->gid =
archive_le16dec(p + offset + 10);
}
break;
}
case 0x6c78:
{
/* Experimental 'xl' field */
/*
* Introduced Dec 2013 to provide a way to
* include external file attributes (and other
* fields that ordinarily appear only in
* central directory) in local file header.
* This provides file type and permission
* information necessary to support full
* streaming extraction. Currently being
* discussed with other Zip developers
* ... subject to change.
*
* Format:
* The field starts with a bitmap that specifies
* which additional fields are included. The
* bitmap is variable length and can be extended in
* the future.
*
* n bytes - feature bitmap: first byte has low-order
* 7 bits. If high-order bit is set, a subsequent
* byte holds the next 7 bits, etc.
*
* if bitmap & 1, 2 byte "version made by"
* if bitmap & 2, 2 byte "internal file attributes"
* if bitmap & 4, 4 byte "external file attributes"
* if bitmap & 8, 2 byte comment length + n byte comment
*/
int bitmap, bitmap_last;
if (datasize < 1)
break;
bitmap_last = bitmap = 0xff & p[offset];
offset += 1;
datasize -= 1;
/* We only support first 7 bits of bitmap; skip rest. */
while ((bitmap_last & 0x80) != 0
&& datasize >= 1) {
bitmap_last = p[offset];
offset += 1;
datasize -= 1;
}
if (bitmap & 1) {
/* 2 byte "version made by" */
if (datasize < 2)
break;
zip_entry->system
= archive_le16dec(p + offset) >> 8;
offset += 2;
datasize -= 2;
}
if (bitmap & 2) {
/* 2 byte "internal file attributes" */
uint32_t internal_attributes;
if (datasize < 2)
break;
internal_attributes
= archive_le16dec(p + offset);
/* Not used by libarchive at present. */
(void)internal_attributes; /* UNUSED */
offset += 2;
datasize -= 2;
}
if (bitmap & 4) {
/* 4 byte "external file attributes" */
uint32_t external_attributes;
if (datasize < 4)
break;
external_attributes
= archive_le32dec(p + offset);
if (zip_entry->system == 3) {
zip_entry->mode
= external_attributes >> 16;
} else if (zip_entry->system == 0) {
// Interpret MSDOS directory bit
if (0x10 == (external_attributes & 0x10)) {
zip_entry->mode = AE_IFDIR | 0775;
} else {
zip_entry->mode = AE_IFREG | 0664;
}
if (0x01 == (external_attributes & 0x01)) {
// Read-only bit; strip write permissions
zip_entry->mode &= 0555;
}
} else {
zip_entry->mode = 0;
}
offset += 4;
datasize -= 4;
}
if (bitmap & 8) {
/* 2 byte comment length + comment */
uint32_t comment_length;
if (datasize < 2)
break;
comment_length
= archive_le16dec(p + offset);
offset += 2;
datasize -= 2;
if (datasize < comment_length)
break;
/* Comment is not supported by libarchive */
offset += comment_length;
datasize -= comment_length;
}
break;
}
case 0x7855:
/* Info-ZIP Unix Extra Field (type 2) "Ux". */
#ifdef DEBUG
fprintf(stderr, "uid %d gid %d\n",
archive_le16dec(p + offset),
archive_le16dec(p + offset + 2));
#endif
if (datasize >= 2)
zip_entry->uid = archive_le16dec(p + offset);
if (datasize >= 4)
zip_entry->gid =
archive_le16dec(p + offset + 2);
break;
case 0x7875:
{
/* Info-Zip Unix Extra Field (type 3) "ux". */
int uidsize = 0, gidsize = 0;
/* TODO: support arbitrary uidsize/gidsize. */
if (datasize >= 1 && p[offset] == 1) {/* version=1 */
if (datasize >= 4) {
/* get a uid size. */
uidsize = 0xff & (int)p[offset+1];
if (uidsize == 2)
zip_entry->uid =
archive_le16dec(
p + offset + 2);
else if (uidsize == 4 && datasize >= 6)
zip_entry->uid =
archive_le32dec(
p + offset + 2);
}
if (datasize >= (2 + uidsize + 3)) {
/* get a gid size. */
gidsize = 0xff & (int)p[offset+2+uidsize];
if (gidsize == 2)
zip_entry->gid =
archive_le16dec(
p+offset+2+uidsize+1);
else if (gidsize == 4 &&
datasize >= (2 + uidsize + 5))
zip_entry->gid =
archive_le32dec(
p+offset+2+uidsize+1);
}
}
break;
}
case 0x9901:
/* WinZIp AES extra data field. */
if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
/* Vendor version. */
zip_entry->aes_extra.vendor =
archive_le16dec(p + offset);
/* AES encryption strength. */
zip_entry->aes_extra.strength = p[offset + 4];
/* Actual compression method. */
zip_entry->aes_extra.compression =
p[offset + 5];
}
break;
default:
break;
}
offset += datasize;
}
#ifdef DEBUG
if (offset != extra_length)
{
fprintf(stderr,
"Extra data field contents do not match reported size!\n");
}
#endif
}
/*
* Assumes file pointer is at beginning of local file header.
*/
static int
zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
struct zip *zip)
{
const char *p;
const void *h;
const wchar_t *wp;
const char *cp;
size_t len, filename_length, extra_length;
struct archive_string_conv *sconv;
struct zip_entry *zip_entry = zip->entry;
struct zip_entry zip_entry_central_dir;
int ret = ARCHIVE_OK;
char version;
/* Save a copy of the original for consistency checks. */
zip_entry_central_dir = *zip_entry;
zip->decompress_init = 0;
zip->end_of_entry = 0;
zip->entry_uncompressed_bytes_read = 0;
zip->entry_compressed_bytes_read = 0;
zip->entry_crc32 = zip->crc32func(0, NULL, 0);
/* Setup default conversion. */
if (zip->sconv == NULL && !zip->init_default_conversion) {
zip->sconv_default =
archive_string_default_conversion_for_read(&(a->archive));
zip->init_default_conversion = 1;
}
if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_FATAL);
}
if (memcmp(p, "PK\003\004", 4) != 0) {
archive_set_error(&a->archive, -1, "Damaged Zip archive");
return ARCHIVE_FATAL;
}
version = p[4];
zip_entry->system = p[5];
zip_entry->zip_flags = archive_le16dec(p + 6);
if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
zip->has_encrypted_entries = 1;
archive_entry_set_is_data_encrypted(entry, 1);
if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
zip_entry->zip_flags & ZIP_ENCRYPTED &&
zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
archive_entry_set_is_metadata_encrypted(entry, 1);
return ARCHIVE_FATAL;
}
}
zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
zip_entry->compression = (char)archive_le16dec(p + 8);
zip_entry->mtime = zip_time(p + 10);
zip_entry->crc32 = archive_le32dec(p + 14);
if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
zip_entry->decdat = p[11];
else
zip_entry->decdat = p[17];
zip_entry->compressed_size = archive_le32dec(p + 18);
zip_entry->uncompressed_size = archive_le32dec(p + 22);
filename_length = archive_le16dec(p + 26);
extra_length = archive_le16dec(p + 28);
__archive_read_consume(a, 30);
/* Read the filename. */
if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_FATAL);
}
if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
/* The filename is stored to be UTF-8. */
if (zip->sconv_utf8 == NULL) {
zip->sconv_utf8 =
archive_string_conversion_from_charset(
&a->archive, "UTF-8", 1);
if (zip->sconv_utf8 == NULL)
return (ARCHIVE_FATAL);
}
sconv = zip->sconv_utf8;
} else if (zip->sconv != NULL)
sconv = zip->sconv;
else
sconv = zip->sconv_default;
if (archive_entry_copy_pathname_l(entry,
h, filename_length, sconv) != 0) {
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Pathname");
return (ARCHIVE_FATAL);
}
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Pathname cannot be converted "
"from %s to current locale.",
archive_string_conversion_charset_name(sconv));
ret = ARCHIVE_WARN;
}
__archive_read_consume(a, filename_length);
/* Read the extra data. */
if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_FATAL);
}
process_extra(h, extra_length, zip_entry);
__archive_read_consume(a, extra_length);
/* Work around a bug in Info-Zip: When reading from a pipe, it
* stats the pipe instead of synthesizing a file entry. */
if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
zip_entry->mode &= ~ AE_IFMT;
zip_entry->mode |= AE_IFREG;
}
if ((zip_entry->mode & AE_IFMT) == 0) {
/* Especially in streaming mode, we can end up
here without having seen proper mode information.
Guess from the filename. */
wp = archive_entry_pathname_w(entry);
if (wp != NULL) {
len = wcslen(wp);
if (len > 0 && wp[len - 1] == L'/')
zip_entry->mode |= AE_IFDIR;
else
zip_entry->mode |= AE_IFREG;
} else {
cp = archive_entry_pathname(entry);
len = (cp != NULL)?strlen(cp):0;
if (len > 0 && cp[len - 1] == '/')
zip_entry->mode |= AE_IFDIR;
else
zip_entry->mode |= AE_IFREG;
}
if (zip_entry->mode == AE_IFDIR) {
zip_entry->mode |= 0775;
} else if (zip_entry->mode == AE_IFREG) {
zip_entry->mode |= 0664;
}
}
/* Make sure directories end in '/' */
if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
wp = archive_entry_pathname_w(entry);
if (wp != NULL) {
len = wcslen(wp);
if (len > 0 && wp[len - 1] != L'/') {
struct archive_wstring s;
archive_string_init(&s);
archive_wstrcat(&s, wp);
archive_wstrappend_wchar(&s, L'/');
archive_entry_copy_pathname_w(entry, s.s);
}
} else {
cp = archive_entry_pathname(entry);
len = (cp != NULL)?strlen(cp):0;
if (len > 0 && cp[len - 1] != '/') {
struct archive_string s;
archive_string_init(&s);
archive_strcat(&s, cp);
archive_strappend_char(&s, '/');
archive_entry_set_pathname(entry, s.s);
}
}
}
if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
/* If this came from the central dir, it's size info
* is definitive, so ignore the length-at-end flag. */
zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
/* If local header is missing a value, use the one from
the central directory. If both have it, warn about
mismatches. */
if (zip_entry->crc32 == 0) {
zip_entry->crc32 = zip_entry_central_dir.crc32;
} else if (!zip->ignore_crc32
&& zip_entry->crc32 != zip_entry_central_dir.crc32) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Inconsistent CRC32 values");
ret = ARCHIVE_WARN;
}
if (zip_entry->compressed_size == 0) {
zip_entry->compressed_size
= zip_entry_central_dir.compressed_size;
} else if (zip_entry->compressed_size
!= zip_entry_central_dir.compressed_size) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Inconsistent compressed size: "
"%jd in central directory, %jd in local header",
(intmax_t)zip_entry_central_dir.compressed_size,
(intmax_t)zip_entry->compressed_size);
ret = ARCHIVE_WARN;
}
if (zip_entry->uncompressed_size == 0) {
zip_entry->uncompressed_size
= zip_entry_central_dir.uncompressed_size;
} else if (zip_entry->uncompressed_size
!= zip_entry_central_dir.uncompressed_size) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Inconsistent uncompressed size: "
"%jd in central directory, %jd in local header",
(intmax_t)zip_entry_central_dir.uncompressed_size,
(intmax_t)zip_entry->uncompressed_size);
ret = ARCHIVE_WARN;
}
}
/* Populate some additional entry fields: */
archive_entry_set_mode(entry, zip_entry->mode);
archive_entry_set_uid(entry, zip_entry->uid);
archive_entry_set_gid(entry, zip_entry->gid);
archive_entry_set_mtime(entry, zip_entry->mtime, 0);
archive_entry_set_ctime(entry, zip_entry->ctime, 0);
archive_entry_set_atime(entry, zip_entry->atime, 0);
if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
size_t linkname_length;
if (zip_entry->compressed_size > 64 * 1024) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Zip file with oversized link entry");
return ARCHIVE_FATAL;
}
linkname_length = (size_t)zip_entry->compressed_size;
archive_entry_set_size(entry, 0);
p = __archive_read_ahead(a, linkname_length, NULL);
if (p == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Truncated Zip file");
return ARCHIVE_FATAL;
}
sconv = zip->sconv;
if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
sconv = zip->sconv_utf8;
if (sconv == NULL)
sconv = zip->sconv_default;
if (archive_entry_copy_symlink_l(entry, p, linkname_length,
sconv) != 0) {
if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
(zip->entry->zip_flags & ZIP_UTF8_NAME))
archive_entry_copy_symlink_l(entry, p,
linkname_length, NULL);
if (errno == ENOMEM) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Symlink");
return (ARCHIVE_FATAL);
}
/*
* Since there is no character-set regulation for
* symlink name, do not report the conversion error
* in an automatic conversion.
*/
if (sconv != zip->sconv_utf8 ||
(zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Symlink cannot be converted "
"from %s to current locale.",
archive_string_conversion_charset_name(
sconv));
ret = ARCHIVE_WARN;
}
}
zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
if (__archive_read_consume(a, linkname_length) < 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Read error skipping symlink target name");
return ARCHIVE_FATAL;
}
} else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
|| zip_entry->uncompressed_size > 0) {
/* Set the size only if it's meaningful. */
archive_entry_set_size(entry, zip_entry->uncompressed_size);
}
zip->entry_bytes_remaining = zip_entry->compressed_size;
/* If there's no body, force read_data() to return EOF immediately. */
if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
&& zip->entry_bytes_remaining < 1)
zip->end_of_entry = 1;
/* Set up a more descriptive format name. */
archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
version / 10, version % 10,
compression_name(zip->entry->compression));
a->archive.archive_format_name = zip->format_name.s;
return (ret);
}
static int
check_authentication_code(struct archive_read *a, const void *_p)
{
struct zip *zip = (struct zip *)(a->format->data);
/* Check authentication code. */
if (zip->hctx_valid) {
const void *p;
uint8_t hmac[20];
size_t hmac_len = 20;
int cmp;
archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
if (_p == NULL) {
/* Read authentication code. */
p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
if (p == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
} else {
p = _p;
}
cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
__archive_read_consume(a, AUTH_CODE_SIZE);
if (cmp != 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"ZIP bad Authentication code");
return (ARCHIVE_WARN);
}
}
return (ARCHIVE_OK);
}
/*
* Read "uncompressed" data. There are three cases:
* 1) We know the size of the data. This is always true for the
* seeking reader (we've examined the Central Directory already).
* 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
* Info-ZIP seems to do this; we know the size but have to grab
* the CRC from the data descriptor afterwards.
* 3) We're streaming and ZIP_LENGTH_AT_END was specified and
* we have no size information. In this case, we can do pretty
* well by watching for the data descriptor record. The data
* descriptor is 16 bytes and includes a computed CRC that should
* provide a strong check.
*
* TODO: Technically, the PK\007\010 signature is optional.
* In the original spec, the data descriptor contained CRC
* and size fields but had no leading signature. In practice,
* newer writers seem to provide the signature pretty consistently.
*
* For uncompressed data, the PK\007\010 marker seems essential
* to be sure we've actually seen the end of the entry.
*
* Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
* zip->end_of_entry if it consumes all of the data.
*/
static int
zip_read_data_none(struct archive_read *a, const void **_buff,
size_t *size, int64_t *offset)
{
struct zip *zip;
const char *buff;
ssize_t bytes_avail;
int r;
(void)offset; /* UNUSED */
zip = (struct zip *)(a->format->data);
if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
const char *p;
ssize_t grabbing_bytes = 24;
if (zip->hctx_valid)
grabbing_bytes += AUTH_CODE_SIZE;
/* Grab at least 24 bytes. */
buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
if (bytes_avail < grabbing_bytes) {
/* Zip archives have end-of-archive markers
that are longer than this, so a failure to get at
least 24 bytes really does indicate a truncated
file. */
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
/* Check for a complete PK\007\010 signature, followed
* by the correct 4-byte CRC. */
p = buff;
if (zip->hctx_valid)
p += AUTH_CODE_SIZE;
if (p[0] == 'P' && p[1] == 'K'
&& p[2] == '\007' && p[3] == '\010'
&& (archive_le32dec(p + 4) == zip->entry_crc32
|| zip->ignore_crc32
|| (zip->hctx_valid
&& zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
if (zip->entry->flags & LA_USED_ZIP64) {
zip->entry->crc32 = archive_le32dec(p + 4);
zip->entry->compressed_size =
archive_le64dec(p + 8);
zip->entry->uncompressed_size =
archive_le64dec(p + 16);
zip->unconsumed = 24;
} else {
zip->entry->crc32 = archive_le32dec(p + 4);
zip->entry->compressed_size =
archive_le32dec(p + 8);
zip->entry->uncompressed_size =
archive_le32dec(p + 12);
zip->unconsumed = 16;
}
if (zip->hctx_valid) {
r = check_authentication_code(a, buff);
if (r != ARCHIVE_OK)
return (r);
}
zip->end_of_entry = 1;
return (ARCHIVE_OK);
}
/* If not at EOF, ensure we consume at least one byte. */
++p;
/* Scan forward until we see where a PK\007\010 signature
* might be. */
/* Return bytes up until that point. On the next call,
* the code above will verify the data descriptor. */
while (p < buff + bytes_avail - 4) {
if (p[3] == 'P') { p += 3; }
else if (p[3] == 'K') { p += 2; }
else if (p[3] == '\007') { p += 1; }
else if (p[3] == '\010' && p[2] == '\007'
&& p[1] == 'K' && p[0] == 'P') {
if (zip->hctx_valid)
p -= AUTH_CODE_SIZE;
break;
} else { p += 4; }
}
bytes_avail = p - buff;
} else {
if (zip->entry_bytes_remaining == 0) {
zip->end_of_entry = 1;
if (zip->hctx_valid) {
r = check_authentication_code(a, NULL);
if (r != ARCHIVE_OK)
return (r);
}
return (ARCHIVE_OK);
}
/* Grab a bunch of bytes. */
buff = __archive_read_ahead(a, 1, &bytes_avail);
if (bytes_avail <= 0) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
if (bytes_avail > zip->entry_bytes_remaining)
bytes_avail = (ssize_t)zip->entry_bytes_remaining;
}
if (zip->tctx_valid || zip->cctx_valid) {
size_t dec_size = bytes_avail;
if (dec_size > zip->decrypted_buffer_size)
dec_size = zip->decrypted_buffer_size;
if (zip->tctx_valid) {
trad_enc_decrypt_update(&zip->tctx,
(const uint8_t *)buff, dec_size,
zip->decrypted_buffer, dec_size);
} else {
size_t dsize = dec_size;
archive_hmac_sha1_update(&zip->hctx,
(const uint8_t *)buff, dec_size);
archive_decrypto_aes_ctr_update(&zip->cctx,
(const uint8_t *)buff, dec_size,
zip->decrypted_buffer, &dsize);
}
bytes_avail = dec_size;
buff = (const char *)zip->decrypted_buffer;
}
*size = bytes_avail;
zip->entry_bytes_remaining -= bytes_avail;
zip->entry_uncompressed_bytes_read += bytes_avail;
zip->entry_compressed_bytes_read += bytes_avail;
zip->unconsumed += bytes_avail;
*_buff = buff;
return (ARCHIVE_OK);
}
#ifdef HAVE_ZLIB_H
static int
zip_deflate_init(struct archive_read *a, struct zip *zip)
{
int r;
/* If we haven't yet read any data, initialize the decompressor. */
if (!zip->decompress_init) {
if (zip->stream_valid)
r = inflateReset(&zip->stream);
else
r = inflateInit2(&zip->stream,
-15 /* Don't check for zlib header */);
if (r != Z_OK) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Can't initialize ZIP decompression.");
return (ARCHIVE_FATAL);
}
/* Stream structure has been set up. */
zip->stream_valid = 1;
/* We've initialized decompression for this stream. */
zip->decompress_init = 1;
}
return (ARCHIVE_OK);
}
static int
zip_read_data_deflate(struct archive_read *a, const void **buff,
size_t *size, int64_t *offset)
{
struct zip *zip;
ssize_t bytes_avail;
const void *compressed_buff, *sp;
int r;
(void)offset; /* UNUSED */
zip = (struct zip *)(a->format->data);
/* If the buffer hasn't been allocated, allocate it now. */
if (zip->uncompressed_buffer == NULL) {
zip->uncompressed_buffer_size = 256 * 1024;
zip->uncompressed_buffer
= (unsigned char *)malloc(zip->uncompressed_buffer_size);
if (zip->uncompressed_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for ZIP decompression");
return (ARCHIVE_FATAL);
}
}
r = zip_deflate_init(a, zip);
if (r != ARCHIVE_OK)
return (r);
/*
* Note: '1' here is a performance optimization.
* Recall that the decompression layer returns a count of
* available bytes; asking for more than that forces the
* decompressor to combine reads by copying data.
*/
compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
&& bytes_avail > zip->entry_bytes_remaining) {
bytes_avail = (ssize_t)zip->entry_bytes_remaining;
}
if (bytes_avail <= 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file body");
return (ARCHIVE_FATAL);
}
if (zip->tctx_valid || zip->cctx_valid) {
if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
size_t buff_remaining = zip->decrypted_buffer_size
- (zip->decrypted_ptr - zip->decrypted_buffer);
if (buff_remaining > (size_t)bytes_avail)
buff_remaining = (size_t)bytes_avail;
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
zip->entry_bytes_remaining > 0) {
if ((int64_t)(zip->decrypted_bytes_remaining
+ buff_remaining)
> zip->entry_bytes_remaining) {
if (zip->entry_bytes_remaining <
(int64_t)zip->decrypted_bytes_remaining)
buff_remaining = 0;
else
buff_remaining =
(size_t)zip->entry_bytes_remaining
- zip->decrypted_bytes_remaining;
}
}
if (buff_remaining > 0) {
if (zip->tctx_valid) {
trad_enc_decrypt_update(&zip->tctx,
compressed_buff, buff_remaining,
zip->decrypted_ptr
+ zip->decrypted_bytes_remaining,
buff_remaining);
} else {
size_t dsize = buff_remaining;
archive_decrypto_aes_ctr_update(
&zip->cctx,
compressed_buff, buff_remaining,
zip->decrypted_ptr
+ zip->decrypted_bytes_remaining,
&dsize);
}
zip->decrypted_bytes_remaining += buff_remaining;
}
}
bytes_avail = zip->decrypted_bytes_remaining;
compressed_buff = (const char *)zip->decrypted_ptr;
}
/*
* A bug in zlib.h: stream.next_in should be marked 'const'
* but isn't (the library never alters data through the
* next_in pointer, only reads it). The result: this ugly
* cast to remove 'const'.
*/
zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
zip->stream.avail_in = (uInt)bytes_avail;
zip->stream.total_in = 0;
zip->stream.next_out = zip->uncompressed_buffer;
zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
zip->stream.total_out = 0;
r = inflate(&zip->stream, 0);
switch (r) {
case Z_OK:
break;
case Z_STREAM_END:
zip->end_of_entry = 1;
break;
case Z_MEM_ERROR:
archive_set_error(&a->archive, ENOMEM,
"Out of memory for ZIP decompression");
return (ARCHIVE_FATAL);
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP decompression failed (%d)", r);
return (ARCHIVE_FATAL);
}
/* Consume as much as the compressor actually used. */
bytes_avail = zip->stream.total_in;
if (zip->tctx_valid || zip->cctx_valid) {
zip->decrypted_bytes_remaining -= bytes_avail;
if (zip->decrypted_bytes_remaining == 0)
zip->decrypted_ptr = zip->decrypted_buffer;
else
zip->decrypted_ptr += bytes_avail;
}
/* Calculate compressed data as much as we used.*/
if (zip->hctx_valid)
archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
__archive_read_consume(a, bytes_avail);
zip->entry_bytes_remaining -= bytes_avail;
zip->entry_compressed_bytes_read += bytes_avail;
*size = zip->stream.total_out;
zip->entry_uncompressed_bytes_read += zip->stream.total_out;
*buff = zip->uncompressed_buffer;
if (zip->end_of_entry && zip->hctx_valid) {
r = check_authentication_code(a, NULL);
if (r != ARCHIVE_OK)
return (r);
}
if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
const char *p;
if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP end-of-file record");
return (ARCHIVE_FATAL);
}
/* Consume the optional PK\007\010 marker. */
if (p[0] == 'P' && p[1] == 'K' &&
p[2] == '\007' && p[3] == '\010') {
p += 4;
zip->unconsumed = 4;
}
if (zip->entry->flags & LA_USED_ZIP64) {
zip->entry->crc32 = archive_le32dec(p);
zip->entry->compressed_size = archive_le64dec(p + 4);
zip->entry->uncompressed_size = archive_le64dec(p + 12);
zip->unconsumed += 20;
} else {
zip->entry->crc32 = archive_le32dec(p);
zip->entry->compressed_size = archive_le32dec(p + 4);
zip->entry->uncompressed_size = archive_le32dec(p + 8);
zip->unconsumed += 12;
}
}
return (ARCHIVE_OK);
}
#endif
static int
read_decryption_header(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
const char *p;
unsigned int remaining_size;
unsigned int ts;
/*
* Read an initialization vector data field.
*/
p = __archive_read_ahead(a, 2, NULL);
if (p == NULL)
goto truncated;
ts = zip->iv_size;
zip->iv_size = archive_le16dec(p);
__archive_read_consume(a, 2);
if (ts < zip->iv_size) {
free(zip->iv);
zip->iv = NULL;
}
p = __archive_read_ahead(a, zip->iv_size, NULL);
if (p == NULL)
goto truncated;
if (zip->iv == NULL) {
zip->iv = malloc(zip->iv_size);
if (zip->iv == NULL)
goto nomem;
}
memcpy(zip->iv, p, zip->iv_size);
__archive_read_consume(a, zip->iv_size);
/*
* Read a size of remaining decryption header field.
*/
p = __archive_read_ahead(a, 14, NULL);
if (p == NULL)
goto truncated;
remaining_size = archive_le32dec(p);
if (remaining_size < 16 || remaining_size > (1 << 18))
goto corrupted;
/* Check if format version is supported. */
if (archive_le16dec(p+4) != 3) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported encryption format version: %u",
archive_le16dec(p+4));
return (ARCHIVE_FAILED);
}
/*
* Read an encryption algorithm field.
*/
zip->alg_id = archive_le16dec(p+6);
switch (zip->alg_id) {
case 0x6601:/* DES */
case 0x6602:/* RC2 */
case 0x6603:/* 3DES 168 */
case 0x6609:/* 3DES 112 */
case 0x660E:/* AES 128 */
case 0x660F:/* AES 192 */
case 0x6610:/* AES 256 */
case 0x6702:/* RC2 (version >= 5.2) */
case 0x6720:/* Blowfish */
case 0x6721:/* Twofish */
case 0x6801:/* RC4 */
/* Suuported encryption algorithm. */
break;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown encryption algorithm: %u", zip->alg_id);
return (ARCHIVE_FAILED);
}
/*
* Read a bit length field.
*/
zip->bit_len = archive_le16dec(p+8);
/*
* Read a flags field.
*/
zip->flags = archive_le16dec(p+10);
switch (zip->flags & 0xf000) {
case 0x0001: /* Password is required to decrypt. */
case 0x0002: /* Certificates only. */
case 0x0003: /* Password or certificate required to decrypt. */
break;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown encryption flag: %u", zip->flags);
return (ARCHIVE_FAILED);
}
if ((zip->flags & 0xf000) == 0 ||
(zip->flags & 0xf000) == 0x4000) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown encryption flag: %u", zip->flags);
return (ARCHIVE_FAILED);
}
/*
* Read an encrypted random data field.
*/
ts = zip->erd_size;
zip->erd_size = archive_le16dec(p+12);
__archive_read_consume(a, 14);
if ((zip->erd_size & 0xf) != 0 ||
(zip->erd_size + 16) > remaining_size ||
(zip->erd_size + 16) < zip->erd_size)
goto corrupted;
if (ts < zip->erd_size) {
free(zip->erd);
zip->erd = NULL;
}
p = __archive_read_ahead(a, zip->erd_size, NULL);
if (p == NULL)
goto truncated;
if (zip->erd == NULL) {
zip->erd = malloc(zip->erd_size);
if (zip->erd == NULL)
goto nomem;
}
memcpy(zip->erd, p, zip->erd_size);
__archive_read_consume(a, zip->erd_size);
/*
* Read a reserved data field.
*/
p = __archive_read_ahead(a, 4, NULL);
if (p == NULL)
goto truncated;
/* Reserved data size should be zero. */
if (archive_le32dec(p) != 0)
goto corrupted;
__archive_read_consume(a, 4);
/*
* Read a password validation data field.
*/
p = __archive_read_ahead(a, 2, NULL);
if (p == NULL)
goto truncated;
ts = zip->v_size;
zip->v_size = archive_le16dec(p);
__archive_read_consume(a, 2);
if ((zip->v_size & 0x0f) != 0 ||
(zip->erd_size + zip->v_size + 16) > remaining_size ||
(zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
goto corrupted;
if (ts < zip->v_size) {
free(zip->v_data);
zip->v_data = NULL;
}
p = __archive_read_ahead(a, zip->v_size, NULL);
if (p == NULL)
goto truncated;
if (zip->v_data == NULL) {
zip->v_data = malloc(zip->v_size);
if (zip->v_data == NULL)
goto nomem;
}
memcpy(zip->v_data, p, zip->v_size);
__archive_read_consume(a, zip->v_size);
p = __archive_read_ahead(a, 4, NULL);
if (p == NULL)
goto truncated;
zip->v_crc32 = archive_le32dec(p);
__archive_read_consume(a, 4);
/*return (ARCHIVE_OK);
* This is not fully implemnted yet.*/
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Encrypted file is unsupported");
return (ARCHIVE_FAILED);
truncated:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
corrupted:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Corrupted ZIP file data");
return (ARCHIVE_FATAL);
nomem:
archive_set_error(&a->archive, ENOMEM,
"No memory for ZIP decryption");
return (ARCHIVE_FATAL);
}
static int
zip_alloc_decryption_buffer(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
size_t bs = 256 * 1024;
if (zip->decrypted_buffer == NULL) {
zip->decrypted_buffer_size = bs;
zip->decrypted_buffer = malloc(bs);
if (zip->decrypted_buffer == NULL) {
archive_set_error(&a->archive, ENOMEM,
"No memory for ZIP decryption");
return (ARCHIVE_FATAL);
}
}
zip->decrypted_ptr = zip->decrypted_buffer;
return (ARCHIVE_OK);
}
static int
init_traditional_PKWARE_decryption(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
const void *p;
int retry;
int r;
if (zip->tctx_valid)
return (ARCHIVE_OK);
/*
Read the 12 bytes encryption header stored at
the start of the data area.
*/
#define ENC_HEADER_SIZE 12
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
&& zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated Zip encrypted body: only %jd bytes available",
(intmax_t)zip->entry_bytes_remaining);
return (ARCHIVE_FATAL);
}
p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
if (p == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
for (retry = 0;; retry++) {
const char *passphrase;
uint8_t crcchk;
passphrase = __archive_read_next_passphrase(a);
if (passphrase == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
(retry > 0)?
"Incorrect passphrase":
"Passphrase required for this entry");
return (ARCHIVE_FAILED);
}
/*
* Initialize ctx for Traditional PKWARE Decyption.
*/
r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
p, ENC_HEADER_SIZE, &crcchk);
if (r == 0 && crcchk == zip->entry->decdat)
break;/* The passphrase is OK. */
if (retry > 10000) {
/* Avoid infinity loop. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Too many incorrect passphrases");
return (ARCHIVE_FAILED);
}
}
__archive_read_consume(a, ENC_HEADER_SIZE);
zip->tctx_valid = 1;
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
}
/*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
zip->decrypted_bytes_remaining = 0;
return (zip_alloc_decryption_buffer(a));
#undef ENC_HEADER_SIZE
}
static int
init_WinZip_AES_decryption(struct archive_read *a)
{
struct zip *zip = (struct zip *)(a->format->data);
const void *p;
const uint8_t *pv;
size_t key_len, salt_len;
uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
int retry;
int r;
if (zip->cctx_valid || zip->hctx_valid)
return (ARCHIVE_OK);
switch (zip->entry->aes_extra.strength) {
case 1: salt_len = 8; key_len = 16; break;
case 2: salt_len = 12; key_len = 24; break;
case 3: salt_len = 16; key_len = 32; break;
default: goto corrupted;
}
p = __archive_read_ahead(a, salt_len + 2, NULL);
if (p == NULL)
goto truncated;
for (retry = 0;; retry++) {
const char *passphrase;
passphrase = __archive_read_next_passphrase(a);
if (passphrase == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
(retry > 0)?
"Incorrect passphrase":
"Passphrase required for this entry");
return (ARCHIVE_FAILED);
}
memset(derived_key, 0, sizeof(derived_key));
r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
p, salt_len, 1000, derived_key, key_len * 2 + 2);
if (r != 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Decryption is unsupported due to lack of "
"crypto library");
return (ARCHIVE_FAILED);
}
/* Check password verification value. */
pv = ((const uint8_t *)p) + salt_len;
if (derived_key[key_len * 2] == pv[0] &&
derived_key[key_len * 2 + 1] == pv[1])
break;/* The passphrase is OK. */
if (retry > 10000) {
/* Avoid infinity loop. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Too many incorrect passphrases");
return (ARCHIVE_FAILED);
}
}
r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
if (r != 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Decryption is unsupported due to lack of crypto library");
return (ARCHIVE_FAILED);
}
r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
if (r != 0) {
archive_decrypto_aes_ctr_release(&zip->cctx);
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to initialize HMAC-SHA1");
return (ARCHIVE_FAILED);
}
zip->cctx_valid = zip->hctx_valid = 1;
__archive_read_consume(a, salt_len + 2);
zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
&& zip->entry_bytes_remaining < 0)
goto corrupted;
zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
zip->decrypted_bytes_remaining = 0;
zip->entry->compression = zip->entry->aes_extra.compression;
return (zip_alloc_decryption_buffer(a));
truncated:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
corrupted:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Corrupted ZIP file data");
return (ARCHIVE_FATAL);
}
static int
archive_read_format_zip_read_data(struct archive_read *a,
const void **buff, size_t *size, int64_t *offset)
{
int r;
struct zip *zip = (struct zip *)(a->format->data);
if (zip->has_encrypted_entries ==
ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
zip->has_encrypted_entries = 0;
}
*offset = zip->entry_uncompressed_bytes_read;
*size = 0;
*buff = NULL;
/* If we hit end-of-entry last time, return ARCHIVE_EOF. */
if (zip->end_of_entry)
return (ARCHIVE_EOF);
/* Return EOF immediately if this is a non-regular file. */
if (AE_IFREG != (zip->entry->mode & AE_IFMT))
return (ARCHIVE_EOF);
__archive_read_consume(a, zip->unconsumed);
zip->unconsumed = 0;
if (zip->init_decryption) {
zip->has_encrypted_entries = 1;
if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
r = read_decryption_header(a);
else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
r = init_WinZip_AES_decryption(a);
else
r = init_traditional_PKWARE_decryption(a);
if (r != ARCHIVE_OK)
return (r);
zip->init_decryption = 0;
}
switch(zip->entry->compression) {
case 0: /* No compression. */
r = zip_read_data_none(a, buff, size, offset);
break;
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
r = zip_read_data_deflate(a, buff, size, offset);
break;
#endif
default: /* Unsupported compression. */
/* Return a warning. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported ZIP compression method (%s)",
compression_name(zip->entry->compression));
/* We can't decompress this entry, but we will
* be able to skip() it and try the next entry. */
return (ARCHIVE_FAILED);
break;
}
if (r != ARCHIVE_OK)
return (r);
/* Update checksum */
if (*size)
zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
(unsigned)*size);
/* If we hit the end, swallow any end-of-data marker. */
if (zip->end_of_entry) {
/* Check file size, CRC against these values. */
if (zip->entry->compressed_size !=
zip->entry_compressed_bytes_read) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP compressed data is wrong size "
"(read %jd, expected %jd)",
(intmax_t)zip->entry_compressed_bytes_read,
(intmax_t)zip->entry->compressed_size);
return (ARCHIVE_WARN);
}
/* Size field only stores the lower 32 bits of the actual
* size. */
if ((zip->entry->uncompressed_size & UINT32_MAX)
!= (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP uncompressed data is wrong size "
"(read %jd, expected %jd)\n",
(intmax_t)zip->entry_uncompressed_bytes_read,
(intmax_t)zip->entry->uncompressed_size);
return (ARCHIVE_WARN);
}
/* Check computed CRC against header */
if ((!zip->hctx_valid ||
zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
zip->entry->crc32 != zip->entry_crc32
&& !zip->ignore_crc32) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"ZIP bad CRC: 0x%lx should be 0x%lx",
(unsigned long)zip->entry_crc32,
(unsigned long)zip->entry->crc32);
return (ARCHIVE_WARN);
}
}
return (ARCHIVE_OK);
}
static int
archive_read_format_zip_cleanup(struct archive_read *a)
{
struct zip *zip;
struct zip_entry *zip_entry, *next_zip_entry;
zip = (struct zip *)(a->format->data);
#ifdef HAVE_ZLIB_H
if (zip->stream_valid)
inflateEnd(&zip->stream);
free(zip->uncompressed_buffer);
#endif
if (zip->zip_entries) {
zip_entry = zip->zip_entries;
while (zip_entry != NULL) {
next_zip_entry = zip_entry->next;
archive_string_free(&zip_entry->rsrcname);
free(zip_entry);
zip_entry = next_zip_entry;
}
}
free(zip->decrypted_buffer);
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
free(zip->iv);
free(zip->erd);
free(zip->v_data);
archive_string_free(&zip->format_name);
free(zip);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
static int
archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
{
if (_a && _a->format) {
struct zip * zip = (struct zip *)_a->format->data;
if (zip) {
return zip->has_encrypted_entries;
}
}
return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
}
static int
archive_read_format_zip_options(struct archive_read *a,
const char *key, const char *val)
{
struct zip *zip;
int ret = ARCHIVE_FAILED;
zip = (struct zip *)(a->format->data);
if (strcmp(key, "compat-2x") == 0) {
/* Handle filenames as libarchive 2.x */
zip->init_default_conversion = (val != NULL) ? 1 : 0;
return (ARCHIVE_OK);
} else if (strcmp(key, "hdrcharset") == 0) {
if (val == NULL || val[0] == 0)
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"zip: hdrcharset option needs a character-set name"
);
else {
zip->sconv = archive_string_conversion_from_charset(
&a->archive, val, 0);
if (zip->sconv != NULL) {
if (strcmp(val, "UTF-8") == 0)
zip->sconv_utf8 = zip->sconv;
ret = ARCHIVE_OK;
} else
ret = ARCHIVE_FATAL;
}
return (ret);
} else if (strcmp(key, "ignorecrc32") == 0) {
/* Mostly useful for testing. */
if (val == NULL || val[0] == 0) {
zip->crc32func = real_crc32;
zip->ignore_crc32 = 0;
} else {
zip->crc32func = fake_crc32;
zip->ignore_crc32 = 1;
}
return (ARCHIVE_OK);
} else if (strcmp(key, "mac-ext") == 0) {
zip->process_mac_extensions = (val != NULL && val[0] != 0);
return (ARCHIVE_OK);
}
/* Note: The "warn" return is just to inform the options
* supervisor that we didn't handle it. It will generate
* a suitable error if no one used this option. */
return (ARCHIVE_WARN);
}
int
archive_read_support_format_zip(struct archive *a)
{
int r;
r = archive_read_support_format_zip_streamable(a);
if (r != ARCHIVE_OK)
return r;
return (archive_read_support_format_zip_seekable(a));
}
/* ------------------------------------------------------------------------ */
/*
* Streaming-mode support
*/
static int
archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
{
(void)a; /* UNUSED */
return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
}
static int
archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
{
const char *p;
(void)best_bid; /* UNUSED */
if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
return (-1);
/*
* Bid of 29 here comes from:
* + 16 bits for "PK",
* + next 16-bit field has 6 options so contributes
* about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
*
* So we've effectively verified ~29 total bits of check data.
*/
if (p[0] == 'P' && p[1] == 'K') {
if ((p[2] == '\001' && p[3] == '\002')
|| (p[2] == '\003' && p[3] == '\004')
|| (p[2] == '\005' && p[3] == '\006')
|| (p[2] == '\006' && p[3] == '\006')
|| (p[2] == '\007' && p[3] == '\010')
|| (p[2] == '0' && p[3] == '0'))
return (29);
}
/* TODO: It's worth looking ahead a little bit for a valid
* PK signature. In particular, that would make it possible
* to read some UUEncoded SFX files or SFX files coming from
* a network socket. */
return (0);
}
static int
archive_read_format_zip_streamable_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct zip *zip;
a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
if (a->archive.archive_format_name == NULL)
a->archive.archive_format_name = "ZIP";
zip = (struct zip *)(a->format->data);
/*
* It should be sufficient to call archive_read_next_header() for
* a reader to determine if an entry is encrypted or not. If the
* encryption of an entry is only detectable when calling
* archive_read_data(), so be it. We'll do the same check there
* as well.
*/
if (zip->has_encrypted_entries ==
ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
zip->has_encrypted_entries = 0;
/* Make sure we have a zip_entry structure to use. */
if (zip->zip_entries == NULL) {
zip->zip_entries = malloc(sizeof(struct zip_entry));
if (zip->zip_entries == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Out of memory");
return ARCHIVE_FATAL;
}
}
zip->entry = zip->zip_entries;
memset(zip->entry, 0, sizeof(struct zip_entry));
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
__archive_read_reset_passphrase(a);
/* Search ahead for the next local file header. */
__archive_read_consume(a, zip->unconsumed);
zip->unconsumed = 0;
for (;;) {
int64_t skipped = 0;
const char *p, *end;
ssize_t bytes;
p = __archive_read_ahead(a, 4, &bytes);
if (p == NULL)
return (ARCHIVE_FATAL);
end = p + bytes;
while (p + 4 <= end) {
if (p[0] == 'P' && p[1] == 'K') {
if (p[2] == '\003' && p[3] == '\004') {
/* Regular file entry. */
__archive_read_consume(a, skipped);
return zip_read_local_file_header(a,
entry, zip);
}
/*
* TODO: We cannot restore permissions
* based only on the local file headers.
* Consider scanning the central
* directory and returning additional
* entries for at least directories.
* This would allow us to properly set
* directory permissions.
*
* This won't help us fix symlinks
* and may not help with regular file
* permissions, either. <sigh>
*/
if (p[2] == '\001' && p[3] == '\002') {
return (ARCHIVE_EOF);
}
/* End of central directory? Must be an
* empty archive. */
if ((p[2] == '\005' && p[3] == '\006')
|| (p[2] == '\006' && p[3] == '\006'))
return (ARCHIVE_EOF);
}
++p;
++skipped;
}
__archive_read_consume(a, skipped);
}
}
static int
archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
{
struct zip *zip;
int64_t bytes_skipped;
zip = (struct zip *)(a->format->data);
bytes_skipped = __archive_read_consume(a, zip->unconsumed);
zip->unconsumed = 0;
if (bytes_skipped < 0)
return (ARCHIVE_FATAL);
/* If we've already read to end of data, we're done. */
if (zip->end_of_entry)
return (ARCHIVE_OK);
/* So we know we're streaming... */
if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
|| zip->entry->compressed_size > 0) {
/* We know the compressed length, so we can just skip. */
bytes_skipped = __archive_read_consume(a,
zip->entry_bytes_remaining);
if (bytes_skipped < 0)
return (ARCHIVE_FATAL);
return (ARCHIVE_OK);
}
if (zip->init_decryption) {
int r;
zip->has_encrypted_entries = 1;
if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
r = read_decryption_header(a);
else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
r = init_WinZip_AES_decryption(a);
else
r = init_traditional_PKWARE_decryption(a);
if (r != ARCHIVE_OK)
return (r);
zip->init_decryption = 0;
}
/* We're streaming and we don't know the length. */
/* If the body is compressed and we know the format, we can
* find an exact end-of-entry by decompressing it. */
switch (zip->entry->compression) {
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
while (!zip->end_of_entry) {
int64_t offset = 0;
const void *buff = NULL;
size_t size = 0;
int r;
r = zip_read_data_deflate(a, &buff, &size, &offset);
if (r != ARCHIVE_OK)
return (r);
}
return ARCHIVE_OK;
#endif
default: /* Uncompressed or unknown. */
/* Scan for a PK\007\010 signature. */
for (;;) {
const char *p, *buff;
ssize_t bytes_avail;
buff = __archive_read_ahead(a, 16, &bytes_avail);
if (bytes_avail < 16) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file data");
return (ARCHIVE_FATAL);
}
p = buff;
while (p <= buff + bytes_avail - 16) {
if (p[3] == 'P') { p += 3; }
else if (p[3] == 'K') { p += 2; }
else if (p[3] == '\007') { p += 1; }
else if (p[3] == '\010' && p[2] == '\007'
&& p[1] == 'K' && p[0] == 'P') {
if (zip->entry->flags & LA_USED_ZIP64)
__archive_read_consume(a,
p - buff + 24);
else
__archive_read_consume(a,
p - buff + 16);
return ARCHIVE_OK;
} else { p += 4; }
}
__archive_read_consume(a, p - buff);
}
}
}
int
archive_read_support_format_zip_streamable(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
struct zip *zip;
int r;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
zip = (struct zip *)calloc(1, sizeof(*zip));
if (zip == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate zip data");
return (ARCHIVE_FATAL);
}
/* Streamable reader doesn't support mac extensions. */
zip->process_mac_extensions = 0;
/*
* Until enough data has been read, we cannot tell about
* any encrypted entries yet.
*/
zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
zip->crc32func = real_crc32;
r = __archive_read_register_format(a,
zip,
"zip",
archive_read_format_zip_streamable_bid,
archive_read_format_zip_options,
archive_read_format_zip_streamable_read_header,
archive_read_format_zip_read_data,
archive_read_format_zip_read_data_skip_streamable,
NULL,
archive_read_format_zip_cleanup,
archive_read_support_format_zip_capabilities_streamable,
archive_read_format_zip_has_encrypted_entries);
if (r != ARCHIVE_OK)
free(zip);
return (ARCHIVE_OK);
}
/* ------------------------------------------------------------------------ */
/*
* Seeking-mode support
*/
static int
archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
{
(void)a; /* UNUSED */
return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
}
/*
* TODO: This is a performance sink because it forces the read core to
* drop buffered data from the start of file, which will then have to
* be re-read again if this bidder loses.
*
* We workaround this a little by passing in the best bid so far so
* that later bidders can do nothing if they know they'll never
* outbid. But we can certainly do better...
*/
static int
read_eocd(struct zip *zip, const char *p, int64_t current_offset)
{
/* Sanity-check the EOCD we've found. */
/* This must be the first volume. */
if (archive_le16dec(p + 4) != 0)
return 0;
/* Central directory must be on this volume. */
if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
return 0;
/* All central directory entries must be on this volume. */
if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
return 0;
/* Central directory can't extend beyond start of EOCD record. */
if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
> current_offset)
return 0;
/* Save the central directory location for later use. */
zip->central_directory_offset = archive_le32dec(p + 16);
/* This is just a tiny bit higher than the maximum
returned by the streaming Zip bidder. This ensures
that the more accurate seeking Zip parser wins
whenever seek is available. */
return 32;
}
/*
* Examine Zip64 EOCD locator: If it's valid, store the information
* from it.
*/
static void
read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
{
int64_t eocd64_offset;
int64_t eocd64_size;
/* Sanity-check the locator record. */
/* Central dir must be on first volume. */
if (archive_le32dec(p + 4) != 0)
return;
/* Must be only a single volume. */
if (archive_le32dec(p + 16) != 1)
return;
/* Find the Zip64 EOCD record. */
eocd64_offset = archive_le64dec(p + 8);
if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
return;
if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
return;
/* Make sure we can read all of it. */
eocd64_size = archive_le64dec(p + 4) + 12;
if (eocd64_size < 56 || eocd64_size > 16384)
return;
if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
return;
/* Sanity-check the EOCD64 */
if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
return;
if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
return;
/* CD can't be split. */
if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
return;
/* Save the central directory offset for later use. */
zip->central_directory_offset = archive_le64dec(p + 48);
}
static int
archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
{
struct zip *zip = (struct zip *)a->format->data;
int64_t file_size, current_offset;
const char *p;
int i, tail;
/* If someone has already bid more than 32, then avoid
trashing the look-ahead buffers with a seek. */
if (best_bid > 32)
return (-1);
file_size = __archive_read_seek(a, 0, SEEK_END);
if (file_size <= 0)
return 0;
/* Search last 16k of file for end-of-central-directory
* record (which starts with PK\005\006) */
tail = (int)zipmin(1024 * 16, file_size);
current_offset = __archive_read_seek(a, -tail, SEEK_END);
if (current_offset < 0)
return 0;
if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
return 0;
/* Boyer-Moore search backwards from the end, since we want
* to match the last EOCD in the file (there can be more than
* one if there is an uncompressed Zip archive as a member
* within this Zip archive). */
for (i = tail - 22; i > 0;) {
switch (p[i]) {
case 'P':
if (memcmp(p + i, "PK\005\006", 4) == 0) {
int ret = read_eocd(zip, p + i,
current_offset + i);
if (ret > 0) {
/* Zip64 EOCD locator precedes
* regular EOCD if present. */
if (i >= 20
&& memcmp(p + i - 20, "PK\006\007", 4) == 0) {
read_zip64_eocd(a, zip, p + i - 20);
}
return (ret);
}
}
i -= 4;
break;
case 'K': i -= 1; break;
case 005: i -= 2; break;
case 006: i -= 3; break;
default: i -= 4; break;
}
}
return 0;
}
/* The red-black trees are only used in seeking mode to manage
* the in-memory copy of the central directory. */
static int
cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
{
const struct zip_entry *e1 = (const struct zip_entry *)n1;
const struct zip_entry *e2 = (const struct zip_entry *)n2;
if (e1->local_header_offset > e2->local_header_offset)
return -1;
if (e1->local_header_offset < e2->local_header_offset)
return 1;
return 0;
}
static int
cmp_key(const struct archive_rb_node *n, const void *key)
{
/* This function won't be called */
(void)n; /* UNUSED */
(void)key; /* UNUSED */
return 1;
}
static const struct archive_rb_tree_ops rb_ops = {
&cmp_node, &cmp_key
};
static int
rsrc_cmp_node(const struct archive_rb_node *n1,
const struct archive_rb_node *n2)
{
const struct zip_entry *e1 = (const struct zip_entry *)n1;
const struct zip_entry *e2 = (const struct zip_entry *)n2;
return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
}
static int
rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
{
const struct zip_entry *e = (const struct zip_entry *)n;
return (strcmp((const char *)key, e->rsrcname.s));
}
static const struct archive_rb_tree_ops rb_rsrc_ops = {
&rsrc_cmp_node, &rsrc_cmp_key
};
static const char *
rsrc_basename(const char *name, size_t name_length)
{
const char *s, *r;
r = s = name;
for (;;) {
s = memchr(s, '/', name_length - (s - name));
if (s == NULL)
break;
r = ++s;
}
return (r);
}
static void
expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
{
struct archive_string str;
struct zip_entry *dir;
char *s;
archive_string_init(&str);
archive_strncpy(&str, name, name_length);
for (;;) {
s = strrchr(str.s, '/');
if (s == NULL)
break;
*s = '\0';
/* Transfer the parent directory from zip->tree_rsrc RB
* tree to zip->tree RB tree to expose. */
dir = (struct zip_entry *)
__archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
if (dir == NULL)
break;
__archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
archive_string_free(&dir->rsrcname);
__archive_rb_tree_insert_node(&zip->tree, &dir->node);
}
archive_string_free(&str);
}
static int
slurp_central_directory(struct archive_read *a, struct zip *zip)
{
ssize_t i;
unsigned found;
int64_t correction;
ssize_t bytes_avail;
const char *p;
/*
* Find the start of the central directory. The end-of-CD
* record has our starting point, but there are lots of
* Zip archives which have had other data prepended to the
* file, which makes the recorded offsets all too small.
* So we search forward from the specified offset until we
* find the real start of the central directory. Then we
* know the correction we need to apply to account for leading
* padding.
*/
if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
return ARCHIVE_FATAL;
found = 0;
while (!found) {
if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
return ARCHIVE_FATAL;
for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
switch (p[i + 3]) {
case 'P': i += 3; break;
case 'K': i += 2; break;
case 001: i += 1; break;
case 002:
if (memcmp(p + i, "PK\001\002", 4) == 0) {
p += i;
found = 1;
} else
i += 4;
break;
case 005: i += 1; break;
case 006:
if (memcmp(p + i, "PK\005\006", 4) == 0) {
p += i;
found = 1;
} else if (memcmp(p + i, "PK\006\006", 4) == 0) {
p += i;
found = 1;
} else
i += 1;
break;
default: i += 4; break;
}
}
__archive_read_consume(a, i);
}
correction = archive_filter_bytes(&a->archive, 0)
- zip->central_directory_offset;
__archive_rb_tree_init(&zip->tree, &rb_ops);
__archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
zip->central_directory_entries_total = 0;
while (1) {
struct zip_entry *zip_entry;
size_t filename_length, extra_length, comment_length;
uint32_t external_attributes;
const char *name, *r;
if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
return ARCHIVE_FATAL;
if (memcmp(p, "PK\006\006", 4) == 0
|| memcmp(p, "PK\005\006", 4) == 0) {
break;
} else if (memcmp(p, "PK\001\002", 4) != 0) {
archive_set_error(&a->archive,
-1, "Invalid central directory signature");
return ARCHIVE_FATAL;
}
if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
return ARCHIVE_FATAL;
zip_entry = calloc(1, sizeof(struct zip_entry));
zip_entry->next = zip->zip_entries;
zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
zip->zip_entries = zip_entry;
zip->central_directory_entries_total++;
/* version = p[4]; */
zip_entry->system = p[5];
/* version_required = archive_le16dec(p + 6); */
zip_entry->zip_flags = archive_le16dec(p + 8);
if (zip_entry->zip_flags
& (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
zip->has_encrypted_entries = 1;
}
zip_entry->compression = (char)archive_le16dec(p + 10);
zip_entry->mtime = zip_time(p + 12);
zip_entry->crc32 = archive_le32dec(p + 16);
if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
zip_entry->decdat = p[13];
else
zip_entry->decdat = p[19];
zip_entry->compressed_size = archive_le32dec(p + 20);
zip_entry->uncompressed_size = archive_le32dec(p + 24);
filename_length = archive_le16dec(p + 28);
extra_length = archive_le16dec(p + 30);
comment_length = archive_le16dec(p + 32);
/* disk_start = archive_le16dec(p + 34); */ /* Better be zero. */
/* internal_attributes = archive_le16dec(p + 36); */ /* text bit */
external_attributes = archive_le32dec(p + 38);
zip_entry->local_header_offset =
archive_le32dec(p + 42) + correction;
/* If we can't guess the mode, leave it zero here;
when we read the local file header we might get
more information. */
if (zip_entry->system == 3) {
zip_entry->mode = external_attributes >> 16;
} else if (zip_entry->system == 0) {
// Interpret MSDOS directory bit
if (0x10 == (external_attributes & 0x10)) {
zip_entry->mode = AE_IFDIR | 0775;
} else {
zip_entry->mode = AE_IFREG | 0664;
}
if (0x01 == (external_attributes & 0x01)) {
// Read-only bit; strip write permissions
zip_entry->mode &= 0555;
}
} else {
zip_entry->mode = 0;
}
/* We're done with the regular data; get the filename and
* extra data. */
__archive_read_consume(a, 46);
p = __archive_read_ahead(a, filename_length + extra_length,
NULL);
if (p == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return ARCHIVE_FATAL;
}
process_extra(p + filename_length, extra_length, zip_entry);
/*
* Mac resource fork files are stored under the
* "__MACOSX/" directory, so we should check if
* it is.
*/
if (!zip->process_mac_extensions) {
/* Treat every entry as a regular entry. */
__archive_rb_tree_insert_node(&zip->tree,
&zip_entry->node);
} else {
name = p;
r = rsrc_basename(name, filename_length);
if (filename_length >= 9 &&
strncmp("__MACOSX/", name, 9) == 0) {
/* If this file is not a resource fork nor
* a directory. We should treat it as a non
* resource fork file to expose it. */
if (name[filename_length-1] != '/' &&
(r - name < 3 || r[0] != '.' || r[1] != '_')) {
__archive_rb_tree_insert_node(
&zip->tree, &zip_entry->node);
/* Expose its parent directories. */
expose_parent_dirs(zip, name,
filename_length);
} else {
/* This file is a resource fork file or
* a directory. */
archive_strncpy(&(zip_entry->rsrcname),
name, filename_length);
__archive_rb_tree_insert_node(
&zip->tree_rsrc, &zip_entry->node);
}
} else {
/* Generate resource fork name to find its
* resource file at zip->tree_rsrc. */
archive_strcpy(&(zip_entry->rsrcname),
"__MACOSX/");
archive_strncat(&(zip_entry->rsrcname),
name, r - name);
archive_strcat(&(zip_entry->rsrcname), "._");
archive_strncat(&(zip_entry->rsrcname),
name + (r - name),
filename_length - (r - name));
/* Register an entry to RB tree to sort it by
* file offset. */
__archive_rb_tree_insert_node(&zip->tree,
&zip_entry->node);
}
}
/* Skip the comment too ... */
__archive_read_consume(a,
filename_length + extra_length + comment_length);
}
return ARCHIVE_OK;
}
static ssize_t
zip_get_local_file_header_size(struct archive_read *a, size_t extra)
{
const char *p;
ssize_t filename_length, extra_length;
if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
return (ARCHIVE_WARN);
}
p += extra;
if (memcmp(p, "PK\003\004", 4) != 0) {
archive_set_error(&a->archive, -1, "Damaged Zip archive");
return ARCHIVE_WARN;
}
filename_length = archive_le16dec(p + 26);
extra_length = archive_le16dec(p + 28);
return (30 + filename_length + extra_length);
}
static int
zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
struct zip_entry *rsrc)
{
struct zip *zip = (struct zip *)a->format->data;
unsigned char *metadata, *mp;
int64_t offset = archive_filter_bytes(&a->archive, 0);
size_t remaining_bytes, metadata_bytes;
ssize_t hsize;
int ret = ARCHIVE_OK, eof;
switch(rsrc->compression) {
case 0: /* No compression. */
if (rsrc->uncompressed_size != rsrc->compressed_size) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Malformed OS X metadata entry: inconsistent size");
return (ARCHIVE_FATAL);
}
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
#endif
break;
default: /* Unsupported compression. */
/* Return a warning. */
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unsupported ZIP compression method (%s)",
compression_name(rsrc->compression));
/* We can't decompress this entry, but we will
* be able to skip() it and try the next entry. */
return (ARCHIVE_WARN);
}
if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Mac metadata is too large: %jd > 4M bytes",
(intmax_t)rsrc->uncompressed_size);
return (ARCHIVE_WARN);
}
if (rsrc->compressed_size > (4 * 1024 * 1024)) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Mac metadata is too large: %jd > 4M bytes",
(intmax_t)rsrc->compressed_size);
return (ARCHIVE_WARN);
}
metadata = malloc((size_t)rsrc->uncompressed_size);
if (metadata == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory for Mac metadata");
return (ARCHIVE_FATAL);
}
if (offset < rsrc->local_header_offset)
__archive_read_consume(a, rsrc->local_header_offset - offset);
else if (offset != rsrc->local_header_offset) {
__archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
}
hsize = zip_get_local_file_header_size(a, 0);
__archive_read_consume(a, hsize);
remaining_bytes = (size_t)rsrc->compressed_size;
metadata_bytes = (size_t)rsrc->uncompressed_size;
mp = metadata;
eof = 0;
while (!eof && remaining_bytes) {
const unsigned char *p;
ssize_t bytes_avail;
size_t bytes_used;
p = __archive_read_ahead(a, 1, &bytes_avail);
if (p == NULL) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Truncated ZIP file header");
ret = ARCHIVE_WARN;
goto exit_mac_metadata;
}
if ((size_t)bytes_avail > remaining_bytes)
bytes_avail = remaining_bytes;
switch(rsrc->compression) {
case 0: /* No compression. */
if ((size_t)bytes_avail > metadata_bytes)
bytes_avail = metadata_bytes;
memcpy(mp, p, bytes_avail);
bytes_used = (size_t)bytes_avail;
metadata_bytes -= bytes_used;
mp += bytes_used;
if (metadata_bytes == 0)
eof = 1;
break;
#ifdef HAVE_ZLIB_H
case 8: /* Deflate compression. */
{
int r;
ret = zip_deflate_init(a, zip);
if (ret != ARCHIVE_OK)
goto exit_mac_metadata;
zip->stream.next_in =
(Bytef *)(uintptr_t)(const void *)p;
zip->stream.avail_in = (uInt)bytes_avail;
zip->stream.total_in = 0;
zip->stream.next_out = mp;
zip->stream.avail_out = (uInt)metadata_bytes;
zip->stream.total_out = 0;
r = inflate(&zip->stream, 0);
switch (r) {
case Z_OK:
break;
case Z_STREAM_END:
eof = 1;
break;
case Z_MEM_ERROR:
archive_set_error(&a->archive, ENOMEM,
"Out of memory for ZIP decompression");
ret = ARCHIVE_FATAL;
goto exit_mac_metadata;
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"ZIP decompression failed (%d)", r);
ret = ARCHIVE_FATAL;
goto exit_mac_metadata;
}
bytes_used = zip->stream.total_in;
metadata_bytes -= zip->stream.total_out;
mp += zip->stream.total_out;
break;
}
#endif
default:
bytes_used = 0;
break;
}
__archive_read_consume(a, bytes_used);
remaining_bytes -= bytes_used;
}
archive_entry_copy_mac_metadata(entry, metadata,
(size_t)rsrc->uncompressed_size - metadata_bytes);
exit_mac_metadata:
__archive_read_seek(a, offset, SEEK_SET);
zip->decompress_init = 0;
free(metadata);
return (ret);
}
static int
archive_read_format_zip_seekable_read_header(struct archive_read *a,
struct archive_entry *entry)
{
struct zip *zip = (struct zip *)a->format->data;
struct zip_entry *rsrc;
int64_t offset;
int r, ret = ARCHIVE_OK;
/*
* It should be sufficient to call archive_read_next_header() for
* a reader to determine if an entry is encrypted or not. If the
* encryption of an entry is only detectable when calling
* archive_read_data(), so be it. We'll do the same check there
* as well.
*/
if (zip->has_encrypted_entries ==
ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
zip->has_encrypted_entries = 0;
a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
if (a->archive.archive_format_name == NULL)
a->archive.archive_format_name = "ZIP";
if (zip->zip_entries == NULL) {
r = slurp_central_directory(a, zip);
if (r != ARCHIVE_OK)
return r;
/* Get first entry whose local header offset is lower than
* other entries in the archive file. */
zip->entry =
(struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
} else if (zip->entry != NULL) {
/* Get next entry in local header offset order. */
zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
&zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
}
if (zip->entry == NULL)
return ARCHIVE_EOF;
if (zip->entry->rsrcname.s)
rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
&zip->tree_rsrc, zip->entry->rsrcname.s);
else
rsrc = NULL;
if (zip->cctx_valid)
archive_decrypto_aes_ctr_release(&zip->cctx);
if (zip->hctx_valid)
archive_hmac_sha1_cleanup(&zip->hctx);
zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
__archive_read_reset_passphrase(a);
/* File entries are sorted by the header offset, we should mostly
* use __archive_read_consume to advance a read point to avoid redundant
* data reading. */
offset = archive_filter_bytes(&a->archive, 0);
if (offset < zip->entry->local_header_offset)
__archive_read_consume(a,
zip->entry->local_header_offset - offset);
else if (offset != zip->entry->local_header_offset) {
__archive_read_seek(a, zip->entry->local_header_offset,
SEEK_SET);
}
zip->unconsumed = 0;
r = zip_read_local_file_header(a, entry, zip);
if (r != ARCHIVE_OK)
return r;
if (rsrc) {
int ret2 = zip_read_mac_metadata(a, entry, rsrc);
if (ret2 < ret)
ret = ret2;
}
return (ret);
}
/*
* We're going to seek for the next header anyway, so we don't
* need to bother doing anything here.
*/
static int
archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
{
struct zip *zip;
zip = (struct zip *)(a->format->data);
zip->unconsumed = 0;
return (ARCHIVE_OK);
}
int
archive_read_support_format_zip_seekable(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
struct zip *zip;
int r;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
zip = (struct zip *)calloc(1, sizeof(*zip));
if (zip == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate zip data");
return (ARCHIVE_FATAL);
}
#ifdef HAVE_COPYFILE_H
/* Set this by default on Mac OS. */
zip->process_mac_extensions = 1;
#endif
/*
* Until enough data has been read, we cannot tell about
* any encrypted entries yet.
*/
zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
zip->crc32func = real_crc32;
r = __archive_read_register_format(a,
zip,
"zip",
archive_read_format_zip_seekable_bid,
archive_read_format_zip_options,
archive_read_format_zip_seekable_read_header,
archive_read_format_zip_read_data,
archive_read_format_zip_read_data_skip_seekable,
NULL,
archive_read_format_zip_cleanup,
archive_read_support_format_zip_capabilities_seekable,
archive_read_format_zip_has_encrypted_entries);
if (r != ARCHIVE_OK)
free(zip);
return (ARCHIVE_OK);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_4904_0 |
crossvul-cpp_data_bad_721_0 | /* Copyright (C) 2007-2013 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \ingroup decode
*
* @{
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
*
* Decode IPv6
*/
#include "suricata-common.h"
#include "packet-queue.h"
#include "decode.h"
#include "decode-ipv6.h"
#include "decode-icmpv6.h"
#include "decode-events.h"
#include "defrag.h"
#include "pkt-var.h"
#include "util-debug.h"
#include "util-print.h"
#include "util-unittest.h"
#include "util-profiling.h"
#include "host.h"
#define IPV6_EXTHDRS ip6eh.ip6_exthdrs
#define IPV6_EH_CNT ip6eh.ip6_exthdrs_cnt
/**
* \brief Function to decode IPv4 in IPv6 packets
*
*/
static void DecodeIPv4inIPv6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t plen, PacketQueue *pq)
{
if (unlikely(plen < IPV4_HEADER_LEN)) {
ENGINE_SET_INVALID_EVENT(p, IPV4_IN_IPV6_PKT_TOO_SMALL);
return;
}
if (IP_GET_RAW_VER(pkt) == 4) {
if (pq != NULL) {
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt, plen, DECODE_TUNNEL_IPV4, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV6);
/* add the tp to the packet queue. */
PacketEnqueue(pq,tp);
StatsIncr(tv, dtv->counter_ipv4inipv6);
return;
}
}
} else {
ENGINE_SET_EVENT(p, IPV4_IN_IPV6_WRONG_IP_VER);
}
return;
}
/**
* \brief Function to decode IPv6 in IPv6 packets
*
*/
static int DecodeIP6inIP6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t plen, PacketQueue *pq)
{
if (unlikely(plen < IPV6_HEADER_LEN)) {
ENGINE_SET_INVALID_EVENT(p, IPV6_IN_IPV6_PKT_TOO_SMALL);
return TM_ECODE_FAILED;
}
if (IP_GET_RAW_VER(pkt) == 6) {
if (unlikely(pq != NULL)) {
Packet *tp = PacketTunnelPktSetup(tv, dtv, p, pkt, plen, DECODE_TUNNEL_IPV6, pq);
if (tp != NULL) {
PKT_SET_SRC(tp, PKT_SRC_DECODER_IPV6);
PacketEnqueue(pq,tp);
StatsIncr(tv, dtv->counter_ipv6inipv6);
}
}
} else {
ENGINE_SET_EVENT(p, IPV6_IN_IPV6_WRONG_IP_VER);
}
return TM_ECODE_OK;
}
#ifndef UNITTESTS // ugly, but we need this in defrag tests
static inline
#endif
void DecodeIPV6FragHeader(Packet *p, uint8_t *pkt,
uint16_t hdrextlen, uint16_t plen,
uint16_t prev_hdrextlen)
{
uint16_t frag_offset = (*(pkt + 2) << 8 | *(pkt + 3)) & 0xFFF8;
int frag_morefrags = (*(pkt + 2) << 8 | *(pkt + 3)) & 0x0001;
p->ip6eh.fh_offset = frag_offset;
p->ip6eh.fh_more_frags_set = frag_morefrags ? TRUE : FALSE;
p->ip6eh.fh_nh = *pkt;
uint32_t fh_id;
memcpy(&fh_id, pkt+4, 4);
p->ip6eh.fh_id = SCNtohl(fh_id);
SCLogDebug("IPV6 FH: offset %u, mf %s, nh %u, id %u/%x",
p->ip6eh.fh_offset,
p->ip6eh.fh_more_frags_set ? "true" : "false",
p->ip6eh.fh_nh,
p->ip6eh.fh_id, p->ip6eh.fh_id);
// store header offset, data offset
uint16_t frag_hdr_offset = (uint16_t)(pkt - GET_PKT_DATA(p));
uint16_t data_offset = (uint16_t)(frag_hdr_offset + hdrextlen);
uint16_t data_len = plen - hdrextlen;
p->ip6eh.fh_header_offset = frag_hdr_offset;
p->ip6eh.fh_data_offset = data_offset;
p->ip6eh.fh_data_len = data_len;
/* if we have a prev hdr, store the type and offset of it */
if (prev_hdrextlen) {
p->ip6eh.fh_prev_hdr_offset = frag_hdr_offset - prev_hdrextlen;
}
SCLogDebug("IPV6 FH: frag_hdr_offset %u, data_offset %u, data_len %u",
p->ip6eh.fh_header_offset, p->ip6eh.fh_data_offset,
p->ip6eh.fh_data_len);
}
static void
DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
SCEnter();
uint8_t *orig_pkt = pkt;
uint8_t nh = 0; /* careful, 0 is actually a real type */
uint16_t hdrextlen = 0;
uint16_t plen;
char dstopts = 0;
char exthdr_fh_done = 0;
int hh = 0;
int rh = 0;
int eh = 0;
int ah = 0;
nh = IPV6_GET_NH(p);
plen = len;
while(1)
{
/* No upper layer, but we do have data. Suspicious. */
if (nh == IPPROTO_NONE && plen > 0) {
ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER);
SCReturn;
}
if (plen < 2) { /* minimal needed in a hdr */
SCReturn;
}
switch(nh)
{
case IPPROTO_TCP:
IPV6_SET_L4PROTO(p,nh);
DecodeTCP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_UDP:
IPV6_SET_L4PROTO(p,nh);
DecodeUDP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ICMPV6:
IPV6_SET_L4PROTO(p,nh);
DecodeICMPV6(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_SCTP:
IPV6_SET_L4PROTO(p,nh);
DecodeSCTP(tv, dtv, p, pkt, plen, pq);
SCReturn;
case IPPROTO_ROUTING:
IPV6_SET_L4PROTO(p,nh);
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (rh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
rh = 1;
IPV6_EXTHDR_SET_RH(p);
uint8_t ip6rh_type = *(pkt + 2);
if (ip6rh_type == 0) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0);
}
p->ip6eh.rh_type = ip6rh_type;
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
{
IPV6OptHAO hao_s, *hao = &hao_s;
IPV6OptRA ra_s, *ra = &ra_s;
IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s;
uint16_t optslen = 0;
IPV6_SET_L4PROTO(p,nh);
hdrextlen = (*(pkt+1) + 1) << 3;
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */
/* point the pointers to right structures
* in Packet. */
if (nh == IPPROTO_HOPOPTS) {
if (hh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
hh = 1;
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
}
else if (nh == IPPROTO_DSTOPTS)
{
if (dstopts == 0) {
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
dstopts = 1;
} else if (dstopts == 1) {
optslen = ((*(pkt + 1) + 1 ) << 3) - 2;
dstopts = 2;
} else {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
}
if (optslen > plen) {
/* since the packet is long enough (we checked
* plen against hdrlen, the optlen must be malformed. */
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
/* skip past this extension so we can continue parsing the rest
* of the packet */
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/** \todo move into own function to loaded on demand */
uint16_t padn_cnt = 0;
uint16_t other_cnt = 0;
uint16_t offset = 0;
while(offset < optslen)
{
if (*ptr == IPV6OPT_PAD1)
{
padn_cnt++;
offset++;
ptr++;
continue;
}
if (offset + 1 >= optslen) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
/* length field for each opt */
uint8_t ip6_optlen = *(ptr + 1);
/* see if the optlen from the packet fits the total optslen */
if ((offset + 1 + ip6_optlen) > optslen) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
if (*ptr == IPV6OPT_PADN) /* PadN */
{
//printf("PadN option\n");
padn_cnt++;
/* a zero padN len would be weird */
if (ip6_optlen == 0)
ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN);
}
else if (*ptr == IPV6OPT_RA) /* RA */
{
ra->ip6ra_type = *(ptr);
ra->ip6ra_len = ip6_optlen;
if (ip6_optlen < sizeof(ra->ip6ra_value)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value));
ra->ip6ra_value = SCNtohs(ra->ip6ra_value);
//printf("RA option: type %" PRIu32 " len %" PRIu32 " value %" PRIu32 "\n",
// ra->ip6ra_type, ra->ip6ra_len, ra->ip6ra_value);
other_cnt++;
}
else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */
{
jumbo->ip6j_type = *(ptr);
jumbo->ip6j_len = ip6_optlen;
if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len));
jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len);
//printf("Jumbo option: type %" PRIu32 " len %" PRIu32 " payload len %" PRIu32 "\n",
// jumbo->ip6j_type, jumbo->ip6j_len, jumbo->ip6j_payload_len);
}
else if (*ptr == IPV6OPT_HAO) /* HAO */
{
hao->ip6hao_type = *(ptr);
hao->ip6hao_len = ip6_optlen;
if (ip6_optlen < sizeof(hao->ip6hao_hoa)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN);
break;
}
memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa));
//printf("HAO option: type %" PRIu32 " len %" PRIu32 " ",
// hao->ip6hao_type, hao->ip6hao_len);
//char addr_buf[46];
//PrintInet(AF_INET6, (char *)&(hao->ip6hao_hoa),
// addr_buf,sizeof(addr_buf));
//printf("home addr %s\n", addr_buf);
other_cnt++;
} else {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT);
other_cnt++;
}
uint16_t optlen = (*(ptr + 1) + 2);
ptr += optlen; /* +2 for opt type and opt len fields */
offset += optlen;
}
/* flag packets that have only padding */
if (padn_cnt > 0 && other_cnt == 0) {
if (nh == IPPROTO_HOPOPTS)
ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING);
else
ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING);
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_FRAGMENT:
{
IPV6_SET_L4PROTO(p,nh);
/* store the offset of this extension into the packet
* past the ipv6 header. We use it in defrag for creating
* a defragmented packet without the frag header */
if (exthdr_fh_done == 0) {
p->ip6eh.fh_offset = pkt - orig_pkt;
exthdr_fh_done = 1;
}
uint16_t prev_hdrextlen = hdrextlen;
hdrextlen = sizeof(IPV6FragHdr);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
/* for the frag header, the length field is reserved */
if (*(pkt + 1) != 0) {
ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD);
/* non fatal, lets try to continue */
}
if (IPV6_EXTHDR_ISSET_FH(p)) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* set the header flag first */
IPV6_EXTHDR_SET_FH(p);
/* parse the header and setup the vars */
DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen);
/* if FH has offset 0 and no more fragments are coming, we
* parse this packet further right away, no defrag will be
* needed. It is a useless FH then though, so we do set an
* decoder event. */
if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
/* the rest is parsed upon reassembly */
p->flags |= PKT_IS_FRAGMENT;
SCReturn;
}
case IPPROTO_ESP:
{
IPV6_SET_L4PROTO(p,nh);
hdrextlen = sizeof(IPV6EspHdr);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
if (eh) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH);
SCReturn;
}
eh = 1;
nh = IPPROTO_NONE;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_AH:
{
IPV6_SET_L4PROTO(p,nh);
/* we need the header as a minimum */
hdrextlen = sizeof(IPV6AuthHdr);
/* the payload len field is the number of extra 4 byte fields,
* IPV6AuthHdr already contains the first */
if (*(pkt+1) > 0)
hdrextlen += ((*(pkt+1) - 1) * 4);
SCLogDebug("hdrextlen %"PRIu8, hdrextlen);
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt;
if (ahhdr->ip6ah_reserved != 0x0000) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL);
}
if (ah) {
ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH);
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
ah = 1;
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
}
case IPPROTO_IPIP:
IPV6_SET_L4PROTO(p,nh);
DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq);
SCReturn;
/* none, last header */
case IPPROTO_NONE:
IPV6_SET_L4PROTO(p,nh);
SCReturn;
case IPPROTO_ICMP:
ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4);
SCReturn;
/* no parsing yet, just skip it */
case IPPROTO_MH:
case IPPROTO_HIP:
case IPPROTO_SHIM6:
hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */
if (hdrextlen > plen) {
ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR);
SCReturn;
}
nh = *pkt;
pkt += hdrextlen;
plen -= hdrextlen;
break;
default:
ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER);
IPV6_SET_L4PROTO(p,nh);
SCReturn;
}
}
SCReturn;
}
static int DecodeIPV6Packet (ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len)
{
if (unlikely(len < IPV6_HEADER_LEN)) {
return -1;
}
if (unlikely(IP_GET_RAW_VER(pkt) != 6)) {
SCLogDebug("wrong ip version %" PRIu8 "",IP_GET_RAW_VER(pkt));
ENGINE_SET_INVALID_EVENT(p, IPV6_WRONG_IP_VER);
return -1;
}
p->ip6h = (IPV6Hdr *)pkt;
if (unlikely(len < (IPV6_HEADER_LEN + IPV6_GET_PLEN(p))))
{
ENGINE_SET_INVALID_EVENT(p, IPV6_TRUNC_PKT);
return -1;
}
SET_IPV6_SRC_ADDR(p,&p->src);
SET_IPV6_DST_ADDR(p,&p->dst);
return 0;
}
int DecodeIPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq)
{
int ret;
StatsIncr(tv, dtv->counter_ipv6);
/* do the actual decoding */
ret = DecodeIPV6Packet (tv, dtv, p, pkt, len);
if (unlikely(ret < 0)) {
p->ip6h = NULL;
return TM_ECODE_FAILED;
}
#ifdef DEBUG
if (SCLogDebugEnabled()) { /* only convert the addresses if debug is really enabled */
/* debug print */
char s[46], d[46];
PrintInet(AF_INET6, (const void *)GET_IPV6_SRC_ADDR(p), s, sizeof(s));
PrintInet(AF_INET6, (const void *)GET_IPV6_DST_ADDR(p), d, sizeof(d));
SCLogDebug("IPV6 %s->%s - CLASS: %" PRIu32 " FLOW: %" PRIu32 " NH: %" PRIu32 " PLEN: %" PRIu32 " HLIM: %" PRIu32 "", s,d,
IPV6_GET_CLASS(p), IPV6_GET_FLOW(p), IPV6_GET_NH(p), IPV6_GET_PLEN(p),
IPV6_GET_HLIM(p));
}
#endif /* DEBUG */
/* now process the Ext headers and/or the L4 Layer */
switch(IPV6_GET_NH(p)) {
case IPPROTO_TCP:
IPV6_SET_L4PROTO (p, IPPROTO_TCP);
DecodeTCP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_UDP:
IPV6_SET_L4PROTO (p, IPPROTO_UDP);
DecodeUDP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_ICMPV6:
IPV6_SET_L4PROTO (p, IPPROTO_ICMPV6);
DecodeICMPV6(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_SCTP:
IPV6_SET_L4PROTO (p, IPPROTO_SCTP);
DecodeSCTP(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_IPIP:
IPV6_SET_L4PROTO(p, IPPROTO_IPIP);
DecodeIPv4inIPv6(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_IPV6:
DecodeIP6inIP6(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
return TM_ECODE_OK;
case IPPROTO_FRAGMENT:
case IPPROTO_HOPOPTS:
case IPPROTO_ROUTING:
case IPPROTO_NONE:
case IPPROTO_DSTOPTS:
case IPPROTO_AH:
case IPPROTO_ESP:
case IPPROTO_MH:
case IPPROTO_HIP:
case IPPROTO_SHIM6:
DecodeIPV6ExtHdrs(tv, dtv, p, pkt + IPV6_HEADER_LEN, IPV6_GET_PLEN(p), pq);
break;
case IPPROTO_ICMP:
ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4);
break;
default:
ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER);
IPV6_SET_L4PROTO (p, IPV6_GET_NH(p));
break;
}
p->proto = IPV6_GET_L4PROTO (p);
/* Pass to defragger if a fragment. */
if (IPV6_EXTHDR_ISSET_FH(p)) {
Packet *rp = Defrag(tv, dtv, p, pq);
if (rp != NULL) {
PacketEnqueue(pq,rp);
}
}
return TM_ECODE_OK;
}
#ifdef UNITTESTS
/**
* \test fragment decoding
*/
static int DecodeIPV6FragTest01 (void)
{
uint8_t raw_frag1[] = {
0x60, 0x0f, 0x1a, 0xcf, 0x05, 0xa8, 0x2c, 0x36, 0x20, 0x01, 0x04, 0x70, 0x00, 0x01, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x20, 0x01, 0x09, 0x80, 0x32, 0xb2, 0x00, 0x01,
0x2e, 0x41, 0x38, 0xff, 0xfe, 0xa7, 0xea, 0xeb, 0x06, 0x00, 0x00, 0x01, 0xdf, 0xf8, 0x11, 0xd7,
0x00, 0x50, 0xa6, 0x5c, 0xcc, 0xd7, 0x28, 0x9f, 0xc3, 0x34, 0xc6, 0x58, 0x80, 0x10, 0x20, 0x13,
0x18, 0x1f, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0xcd, 0xf9, 0x3a, 0x41, 0x00, 0x1a, 0x91, 0x8a,
0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x20, 0x32, 0x30, 0x30, 0x20, 0x4f, 0x4b, 0x0d,
0x0a, 0x44, 0x61, 0x74, 0x65, 0x3a, 0x20, 0x46, 0x72, 0x69, 0x2c, 0x20, 0x30, 0x32, 0x20, 0x44,
0x65, 0x63, 0x20, 0x32, 0x30, 0x31, 0x31, 0x20, 0x30, 0x38, 0x3a, 0x33, 0x32, 0x3a, 0x35, 0x37,
0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3a, 0x20, 0x41, 0x70,
0x61, 0x63, 0x68, 0x65, 0x0d, 0x0a, 0x43, 0x61, 0x63, 0x68, 0x65, 0x2d, 0x43, 0x6f, 0x6e, 0x74,
0x72, 0x6f, 0x6c, 0x3a, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x0d, 0x0a, 0x50,
0x72, 0x61, 0x67, 0x6d, 0x61, 0x3a, 0x20, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65, 0x0d,
0x0a, 0x45, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, 0x3a, 0x20, 0x54, 0x68, 0x75, 0x2c, 0x20, 0x30,
0x31, 0x20, 0x4a, 0x61, 0x6e, 0x20, 0x31, 0x39, 0x37, 0x31, 0x20, 0x30, 0x30, 0x3a, 0x30, 0x30,
0x3a, 0x30, 0x30, 0x20, 0x47, 0x4d, 0x54, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
0x2d, 0x4c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x3a, 0x20, 0x31, 0x35, 0x39, 0x39, 0x0d, 0x0a, 0x4b,
0x65, 0x65, 0x70, 0x2d, 0x41, 0x6c, 0x69, 0x76, 0x65, 0x3a, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x6f,
0x75, 0x74, 0x3d, 0x35, 0x2c, 0x20, 0x6d, 0x61, 0x78, 0x3d, 0x39, 0x39, 0x0d, 0x0a, 0x43, 0x6f,
0x6e, 0x6e, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x3a, 0x20, 0x4b, 0x65, 0x65, 0x70, 0x2d, 0x41,
0x6c, 0x69, 0x76, 0x65, 0x0d, 0x0a, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2d, 0x54, 0x79,
0x70, 0x65, 0x3a, 0x20, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f,
0x6a, 0x61, 0x76, 0x61, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x3b, 0x63, 0x68, 0x61, 0x72, 0x73,
0x65, 0x74, 0x3d, 0x61, 0x73, 0x63, 0x69, 0x69, 0x0d, 0x0a, 0x0d, 0x0a, 0x5f, 0x6a, 0x71, 0x6a,
0x73, 0x70, 0x28, 0x7b, 0x22, 0x69, 0x70, 0x22, 0x3a, 0x22, 0x32, 0x30, 0x30, 0x31, 0x3a, 0x39,
0x38, 0x30, 0x3a, 0x33, 0x32, 0x62, 0x32, 0x3a, 0x31, 0x3a, 0x32, 0x65, 0x34, 0x31, 0x3a, 0x33,
0x38, 0x66, 0x66, 0x3a, 0x66, 0x65, 0x61, 0x37, 0x3a, 0x65, 0x61, 0x65, 0x62, 0x22, 0x2c, 0x22,
0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x22, 0x69, 0x70, 0x76, 0x36, 0x22, 0x2c, 0x22, 0x73, 0x75,
0x62, 0x74, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x22, 0x22, 0x2c, 0x22, 0x76, 0x69, 0x61, 0x22, 0x3a,
0x22, 0x22, 0x2c, 0x22, 0x70, 0x61, 0x64, 0x64, 0x69, 0x6e, 0x67, 0x22, 0x3a, 0x22, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
};
uint8_t raw_frag2[] = {
0x60, 0x0f, 0x1a, 0xcf, 0x00, 0x1c, 0x2c, 0x36, 0x20, 0x01, 0x04, 0x70, 0x00, 0x01, 0x00, 0x18,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x20, 0x01, 0x09, 0x80, 0x32, 0xb2, 0x00, 0x01,
0x2e, 0x41, 0x38, 0xff, 0xfe, 0xa7, 0xea, 0xeb, 0x06, 0x00, 0x05, 0xa0, 0xdf, 0xf8, 0x11, 0xd7,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20,
};
Packet *pkt;
Packet *p1 = PacketGetFromAlloc();
if (unlikely(p1 == NULL))
return 0;
Packet *p2 = PacketGetFromAlloc();
if (unlikely(p2 == NULL)) {
SCFree(p1);
return 0;
}
ThreadVars tv;
DecodeThreadVars dtv;
int result = 0;
PacketQueue pq;
FlowInitConfig(FLOW_QUIET);
DefragInit();
memset(&pq, 0, sizeof(PacketQueue));
memset(&tv, 0, sizeof(ThreadVars));
memset(&dtv, 0, sizeof(DecodeThreadVars));
PacketCopyData(p1, raw_frag1, sizeof(raw_frag1));
PacketCopyData(p2, raw_frag2, sizeof(raw_frag2));
DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq);
if (!(IPV6_EXTHDR_ISSET_FH(p1))) {
printf("ipv6 frag header not detected: ");
goto end;
}
DecodeIPV6(&tv, &dtv, p2, GET_PKT_DATA(p2), GET_PKT_LEN(p2), &pq);
if (!(IPV6_EXTHDR_ISSET_FH(p2))) {
printf("ipv6 frag header not detected: ");
goto end;
}
if (pq.len != 1) {
printf("no reassembled packet: ");
goto end;
}
result = 1;
end:
PACKET_RECYCLE(p1);
PACKET_RECYCLE(p2);
SCFree(p1);
SCFree(p2);
pkt = PacketDequeue(&pq);
while (pkt != NULL) {
PACKET_RECYCLE(pkt);
SCFree(pkt);
pkt = PacketDequeue(&pq);
}
DefragDestroy();
FlowShutdown();
return result;
}
/**
* \test routing header decode
*/
static int DecodeIPV6RouteTest01 (void)
{
uint8_t raw_pkt1[] = {
0x60, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x2b, 0x40,
0x20, 0x01, 0xaa, 0xaa, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
0x20, 0x01, 0xaa, 0xaa, 0x00, 0x01, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xb2, 0xed, 0x00, 0x50, 0x1b, 0xc7, 0x6a, 0xdf,
0x00, 0x00, 0x00, 0x00, 0x50, 0x02, 0x20, 0x00,
0xfa, 0x87, 0x00, 0x00,
};
Packet *p1 = PacketGetFromAlloc();
FAIL_IF(unlikely(p1 == NULL));
ThreadVars tv;
DecodeThreadVars dtv;
PacketQueue pq;
FlowInitConfig(FLOW_QUIET);
memset(&pq, 0, sizeof(PacketQueue));
memset(&tv, 0, sizeof(ThreadVars));
memset(&dtv, 0, sizeof(DecodeThreadVars));
PacketCopyData(p1, raw_pkt1, sizeof(raw_pkt1));
DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq);
FAIL_IF (!(IPV6_EXTHDR_ISSET_RH(p1)));
FAIL_IF (p1->ip6eh.rh_type != 0);
PACKET_RECYCLE(p1);
SCFree(p1);
FlowShutdown();
PASS;
}
/**
* \test HOP header decode
*/
static int DecodeIPV6HopTest01 (void)
{
uint8_t raw_pkt1[] = {
0x60,0x00,0x00,0x00,0x00,0x20,0x00,0x01,0xfe,0x80,0x00,0x00,0x00,0x00,0x00,0x00,
0x02,0x0f,0xfe,0xff,0xfe,0x98,0x3d,0x01,0xff,0x02,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x3a,0x00,0xff, /* 0xff is a nonsene opt */
0x02,0x00,0x00,0x00,0x00,
0x82,0x00,0x1c,0x6f,0x27,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
Packet *p1 = PacketGetFromAlloc();
FAIL_IF(unlikely(p1 == NULL));
ThreadVars tv;
DecodeThreadVars dtv;
PacketQueue pq;
FlowInitConfig(FLOW_QUIET);
memset(&pq, 0, sizeof(PacketQueue));
memset(&tv, 0, sizeof(ThreadVars));
memset(&dtv, 0, sizeof(DecodeThreadVars));
PacketCopyData(p1, raw_pkt1, sizeof(raw_pkt1));
DecodeIPV6(&tv, &dtv, p1, GET_PKT_DATA(p1), GET_PKT_LEN(p1), &pq);
FAIL_IF (!(ENGINE_ISSET_EVENT(p1, IPV6_HOPOPTS_UNKNOWN_OPT)));
PACKET_RECYCLE(p1);
SCFree(p1);
FlowShutdown();
PASS;
}
#endif /* UNITTESTS */
/**
* \brief this function registers unit tests for IPV6 decoder
*/
void DecodeIPV6RegisterTests(void)
{
#ifdef UNITTESTS
UtRegisterTest("DecodeIPV6FragTest01", DecodeIPV6FragTest01);
UtRegisterTest("DecodeIPV6RouteTest01", DecodeIPV6RouteTest01);
UtRegisterTest("DecodeIPV6HopTest01", DecodeIPV6HopTest01);
#endif /* UNITTESTS */
}
/**
* @}
*/
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_721_0 |
crossvul-cpp_data_good_1389_0 | /*
* This file is part of Cockpit.
*
* Copyright (C) 2013 Red Hat, Inc.
*
* Cockpit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Cockpit is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "cockpitauth.h"
#include "cockpitws.h"
#include "websocket/websocket.h"
#include "common/cockpitauthorize.h"
#include "common/cockpitconf.h"
#include "common/cockpiterror.h"
#include "common/cockpithex.h"
#include "common/cockpitlog.h"
#include "common/cockpitjson.h"
#include "common/cockpitmemory.h"
#include "common/cockpitpipe.h"
#include "common/cockpitpipetransport.h"
#include "common/cockpitsystem.h"
#include "common/cockpitunixfd.h"
#include "common/cockpitwebserver.h"
#include <security/pam_appl.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define ACTION_SSH "remote-login-ssh"
#define ACTION_NONE "none"
#define LOCAL_SESSION "local-session"
/* Some tunables that can be set from tests */
const gchar *cockpit_ws_session_program =
PACKAGE_LIBEXEC_DIR "/cockpit-session";
const gchar *cockpit_ws_ssh_program =
PACKAGE_LIBEXEC_DIR "/cockpit-ssh";
/* Timeout of authenticated session when no connections */
guint cockpit_ws_service_idle = 15;
/* Timeout of everything when noone is connected */
guint cockpit_ws_process_idle = 90;
/* The amount of time a spawned process has to complete authentication */
guint cockpit_ws_auth_process_timeout = 30;
guint cockpit_ws_auth_response_timeout = 60;
/* Maximum number of pending authentication requests */
const gchar *cockpit_ws_max_startups = NULL;
static guint max_startups = 10;
static guint sig__idling = 0;
/* Tristate tracking whether gssapi works properly */
static gint gssapi_available = -1;
G_DEFINE_TYPE (CockpitAuth, cockpit_auth, G_TYPE_OBJECT)
typedef struct {
gint refs;
gchar *name;
gchar *cookie;
CockpitAuth *auth;
CockpitWebService *service;
gboolean initialized;
guint timeout_tag;
gulong idling_sig;
gulong destroy_sig;
/* Used during authentication */
CockpitTransport *transport;
gulong control_sig;
gulong close_sig;
guint client_timeout;
guint authorize_timeout;
/* An open /login request from client */
GSimpleAsyncResult *result;
/* An authorization header from client */
gchar *authorization;
/* An authorize challenge from session */
JsonObject *authorize;
/* The conversation in progress */
gchar *conversation;
} CockpitSession;
static void
cockpit_session_reset (gpointer data)
{
CockpitSession *session = data;
GSimpleAsyncResult *result;
char *conversation;
CockpitAuth *self;
char *cookie;
if (session->result)
{
result = session->result;
session->result = NULL;
g_simple_async_result_complete (result);
g_object_unref (result);
}
if (session->authorization)
{
cockpit_memory_clear (session->authorization, -1);
g_free (session->authorization);
session->authorization = NULL;
}
conversation = session->conversation;
session->conversation = NULL;
cookie = session->cookie;
session->cookie = NULL;
self = session->auth;
/* No accessing session after this point */
if (cookie)
{
g_hash_table_remove (self->sessions, cookie);
g_free (cookie);
}
if (conversation)
{
g_hash_table_remove (self->conversations, conversation);
g_free (conversation);
}
}
static CockpitSession *
cockpit_session_ref (CockpitSession *session)
{
session->refs++;
return session;
}
static void
on_web_service_gone (gpointer data,
GObject *where_the_object_was)
{
CockpitSession *session = data;
session->service = NULL;
cockpit_session_reset (session);
}
static void
cockpit_session_unref (gpointer data)
{
CockpitSession *session = data;
CockpitCreds *creds;
GObject *object;
session->refs--;
if (session->refs > 0)
return;
cockpit_session_reset (data);
g_free (session->name);
g_free (session->cookie);
if (session->authorize)
json_object_unref (session->authorize);
if (session->transport)
{
if (session->control_sig)
g_signal_handler_disconnect (session->transport, session->control_sig);
if (session->close_sig)
g_signal_handler_disconnect (session->transport, session->close_sig);
g_object_unref (session->transport);
}
if (session->service)
{
creds = cockpit_web_service_get_creds (session->service);
object = G_OBJECT (session->service);
session->service = NULL;
if (creds)
cockpit_creds_poison (creds);
if (session->idling_sig)
g_signal_handler_disconnect (object, session->idling_sig);
if (session->destroy_sig)
g_signal_handler_disconnect (object, session->destroy_sig);
g_object_weak_unref (object, on_web_service_gone, session);
g_object_run_dispose (object);
g_object_unref (object);
}
if (session->timeout_tag)
g_source_remove (session->timeout_tag);
g_free (session);
}
static void
byte_array_clear_and_free (gpointer data)
{
GByteArray *buffer = data;
cockpit_memory_clear (buffer->data, buffer->len);
g_byte_array_free (buffer, TRUE);
}
static void
cockpit_auth_finalize (GObject *object)
{
CockpitAuth *self = COCKPIT_AUTH (object);
if (self->timeout_tag)
g_source_remove (self->timeout_tag);
g_bytes_unref (self->key);
g_hash_table_remove_all (self->sessions);
g_hash_table_remove_all (self->conversations);
g_hash_table_destroy (self->sessions);
g_hash_table_destroy (self->conversations);
G_OBJECT_CLASS (cockpit_auth_parent_class)->finalize (object);
}
static gboolean
on_process_timeout (gpointer data)
{
CockpitAuth *self = COCKPIT_AUTH (data);
self->timeout_tag = 0;
if (g_hash_table_size (self->sessions) == 0)
{
g_debug ("auth is idle");
g_signal_emit (self, sig__idling, 0);
}
return FALSE;
}
static void
cockpit_auth_init (CockpitAuth *self)
{
static const gsize key_len = 128;
gpointer key;
key = cockpit_authorize_nonce (key_len);
if (!key)
g_error ("couldn't read random key, startup aborted");
self->key = g_bytes_new_take (key, key_len);
self->sessions = g_hash_table_new_full (g_str_hash, g_str_equal,
NULL, cockpit_session_unref);
self->conversations = g_hash_table_new_full (g_str_hash, g_str_equal,
NULL, cockpit_session_unref);
self->timeout_tag = g_timeout_add_seconds (cockpit_ws_process_idle,
on_process_timeout, self);
self->startups = 0;
self->max_startups = max_startups;
self->max_startups_begin = max_startups;
self->max_startups_rate = 100;
}
gchar *
cockpit_auth_nonce (CockpitAuth *self)
{
const guchar *key;
gsize len;
guint64 seed;
seed = self->nonce_seed++;
key = g_bytes_get_data (self->key, &len);
return g_compute_hmac_for_data (G_CHECKSUM_SHA256, key, len,
(guchar *)&seed, sizeof (seed));
}
static gchar *
get_remote_address (GIOStream *io)
{
GSocketAddress *remote = NULL;
GSocketConnection *connection = NULL;
GIOStream *base;
gchar *result = NULL;
if (G_IS_TLS_CONNECTION (io))
{
g_object_get (io, "base-io-stream", &base, NULL);
if (G_IS_SOCKET_CONNECTION (base))
connection = g_object_ref (base);
g_object_unref (base);
}
else if (G_IS_SOCKET_CONNECTION (io))
{
connection = g_object_ref (io);
}
if (connection)
remote = g_socket_connection_get_remote_address (connection, NULL);
if (remote && G_IS_INET_SOCKET_ADDRESS (remote))
result = g_inet_address_to_string (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (remote)));
if (remote)
g_object_unref (remote);
if (connection)
g_object_unref (connection);
return result;
}
gchar *
cockpit_auth_steal_authorization (GHashTable *headers,
GIOStream *connection,
gchar **ret_type,
gchar **ret_conversation)
{
char *type = NULL;
gchar *ret = NULL;
gchar *line;
gpointer key;
g_assert (headers != NULL);
g_assert (ret_conversation != NULL);
g_assert (ret_type != NULL);
/* Avoid copying as it can contain passwords */
if (g_hash_table_lookup_extended (headers, "Authorization", &key, (gpointer *)&line))
{
g_hash_table_steal (headers, "Authorization");
g_free (key);
}
else
{
/*
* If we don't yet know that Negotiate authentication is possible
* or not, then we ask our session to try to do Negotiate auth
* but without any input data.
*/
if (gssapi_available != 0)
line = g_strdup ("Negotiate");
else
return NULL;
}
/* Dig out the authorization type */
if (!cockpit_authorize_type (line, &type))
goto out;
/* If this is a conversation, get that part out too */
if (g_str_equal (type, "x-conversation"))
{
if (!cockpit_authorize_subject (line, ret_conversation))
goto out;
}
/*
* So for negotiate authentication, conversation happens on a
* single connection. Yes that's right, GSSAPI, NTLM, and all
* those nice mechanisms are keep-alive based, not HTTP request based.
*/
else if (g_str_equal (type, "negotiate"))
{
/* Resume an already running conversation? */
if (ret_conversation && connection)
*ret_conversation = g_strdup (g_object_get_data (G_OBJECT (connection), type));
}
if (ret_type)
{
*ret_type = type;
type = NULL;
}
ret = line;
line = NULL;
out:
g_free (line);
g_free (type);
return ret;
}
static const gchar *
type_option (const gchar *type,
const gchar *option,
const gchar *default_str)
{
if (type && cockpit_conf_string (type, option))
return cockpit_conf_string (type, option);
return default_str;
}
static guint
timeout_option (const gchar *name,
const gchar *type,
guint default_value)
{
return cockpit_conf_guint (type, name, default_value,
MAX_AUTH_TIMEOUT, MIN_AUTH_TIMEOUT);
}
static const gchar *
application_parse_host (const gchar *application)
{
const gchar *prefix = "cockpit+=";
gint len = strlen (prefix);
g_return_val_if_fail (application != NULL, NULL);
if (g_str_has_prefix (application, prefix) && application[len] != '\0')
return application + len;
else
return NULL;
}
static gchar *
application_cookie_name (const gchar *application)
{
const gchar *host = application_parse_host (application);
gchar *cookie_name = NULL;
if (host)
cookie_name = g_strdup_printf ("machine-cockpit+%s", host);
else
cookie_name = g_strdup (application);
return cookie_name;
}
/* Struct for adding tty later */
typedef struct {
int io;
} ChildData;
static void
session_child_setup (gpointer data)
{
ChildData *child = data;
if (dup2 (child->io, 0) < 0 || dup2 (child->io, 1) < 0)
{
g_printerr ("couldn't set child stdin/stout file descriptors\n");
_exit (127);
}
close (child->io);
if (cockpit_unix_fd_close_all (3, -1) < 0)
{
g_printerr ("couldn't close file descriptors: %m\n");
_exit (127);
}
}
static CockpitTransport *
session_start_process (const gchar **argv,
const gchar **env)
{
CockpitTransport *transport = NULL;
CockpitPipe *pipe = NULL;
GError *error = NULL;
ChildData child;
gboolean ret;
GPid pid = 0;
int fds[2];
g_debug ("spawning %s", argv[0]);
/* The main stdin/stdout for the socket ... both are read/writable */
if (socketpair (PF_LOCAL, SOCK_STREAM, 0, fds) < 0)
{
g_warning ("couldn't create loopback socket: %s", g_strerror (errno));
return NULL;
}
child.io = fds[0];
ret = g_spawn_async_with_pipes (NULL, (gchar **)argv, (gchar **)env,
G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
session_child_setup, &child,
&pid, NULL, NULL, NULL, &error);
close (fds[0]);
if (!ret)
{
g_message ("couldn't launch cockpit session: %s: %s", argv[0], error->message);
g_error_free (error);
close (fds[1]);
return NULL;
}
pipe = g_object_new (COCKPIT_TYPE_PIPE,
"in-fd", fds[1],
"out-fd", fds[1],
"pid", pid,
"name", argv[0],
NULL);
transport = cockpit_pipe_transport_new (pipe);
g_object_unref (pipe);
return transport;
}
static void
send_authorize_reply (CockpitTransport *transport,
const gchar *cookie,
const gchar *authorization)
{
const gchar *fields[] = {
"command", "authorize",
"cookie", cookie,
"response", authorization,
NULL
};
GBytes *payload;
const gchar *delim;
GByteArray *buffer;
JsonNode *node;
gchar *encoded;
gsize length;
guint i;
buffer = g_byte_array_new ();
for (i = 0; fields[i] != NULL; i++)
{
if (i % 2 == 0)
delim = buffer->len == 0 ? "{" : ",";
else
delim = ":";
g_byte_array_append (buffer, (guchar *)delim, 1);
node = json_node_init_string (json_node_new (JSON_NODE_VALUE), fields[i]);
encoded = cockpit_json_write (node, &length);
g_byte_array_append (buffer, (guchar *)encoded, length);
cockpit_memory_clear ((guchar *)json_node_get_string (node), -1);
json_node_free (node);
g_free (encoded);
}
g_byte_array_append (buffer, (guchar *)"}", 1);
payload = g_bytes_new_with_free_func (buffer->data, buffer->len,
byte_array_clear_and_free, buffer);
cockpit_transport_send (transport, NULL, payload);
g_bytes_unref (payload);
}
static gboolean
reply_authorize_challenge (CockpitSession *session)
{
const gchar *challenge = NULL;
char *authorize_type = NULL;
char *authorization_type = NULL;
const gchar *cookie = NULL;
const gchar *response = NULL;
JsonObject *login_data = NULL;
gboolean ret = FALSE;
if (!session->authorize)
goto out;
if (!cockpit_json_get_string (session->authorize, "cookie", NULL, &cookie) ||
!cockpit_json_get_string (session->authorize, "challenge", NULL, &challenge) ||
!cockpit_json_get_string (session->authorize, "response", NULL, &response))
goto out;
if (response && !cookie)
{
cockpit_memory_clear (session->authorization, -1);
g_free (session->authorization);
session->authorization = g_strdup (response);
ret = TRUE;
goto out;
}
if (!challenge || !cookie)
goto out;
if (!cockpit_authorize_type (challenge, &authorize_type))
goto out;
/* Handle prompting for login data */
if (g_str_equal (authorize_type, "x-login-data"))
{
if (cockpit_json_get_object (session->authorize, "login-data", NULL, &login_data) && login_data)
cockpit_creds_set_login_data (cockpit_web_service_get_creds (session->service), login_data);
ret = TRUE;
goto out;
}
if (!session->authorization)
goto out;
if (cockpit_authorize_type (session->authorization, &authorization_type) &&
(g_str_equal (authorize_type, "*") || g_str_equal (authorize_type, authorization_type)))
{
send_authorize_reply (session->transport, cookie, session->authorization);
cockpit_memory_clear (session->authorization, -1);
g_free (session->authorization);
session->authorization = NULL;
ret = TRUE;
}
out:
free (authorize_type);
free (authorization_type);
return ret;
}
static gboolean
on_authorize_timeout (gpointer data)
{
CockpitSession *session = data;
CockpitTransport *transport = cockpit_web_service_get_transport (session->service);
session->timeout_tag = 0;
g_message ("%s: session timed out during authentication", session->name);
cockpit_transport_close (transport, "timeout");
return FALSE;
}
static void
reset_authorize_timeout (CockpitSession *session,
gboolean waiting_for_client)
{
guint seconds = waiting_for_client ? session->client_timeout : session->authorize_timeout;
if (session->timeout_tag)
g_source_remove (session->timeout_tag);
session->timeout_tag = g_timeout_add_seconds (seconds, on_authorize_timeout, session);
}
static void
propagate_problem_to_error (CockpitSession *session,
JsonObject *options,
const gchar *problem,
const gchar *message,
GError **error)
{
char *type = NULL;
const char *pw_result = NULL;
JsonObject *auth_results = NULL;
g_return_if_fail (error != NULL);
if (g_str_equal (problem, "authentication-unavailable") &&
cockpit_authorize_type (session->authorization, &type) &&
g_str_equal (type, "negotiate"))
{
g_debug ("%s: negotiate authentication not available", session->name);
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Negotiate authentication not available");
gssapi_available = 0;
}
else if (g_str_equal (problem, "authentication-failed") ||
g_str_equal (problem, "authentication-unavailable"))
{
cockpit_json_get_object (options, "auth-method-results", NULL, &auth_results);
if (auth_results)
{
cockpit_json_get_string (auth_results, "password", NULL, &pw_result);
if (!pw_result || g_strcmp0 (pw_result, "no-server-support") == 0)
{
g_clear_error (error);
g_set_error (error, COCKPIT_ERROR,
COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Authentication failed: authentication-not-supported");
}
}
if (*error == NULL)
{
g_debug ("%s: %s %s", session->name, problem, message);
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Authentication failed");
}
}
else if (g_str_equal (problem, "no-host") ||
g_str_equal (problem, "invalid-hostkey") ||
g_str_equal (problem, "unknown-hostkey") ||
g_str_equal (problem, "unknown-host") ||
g_str_equal (problem, "terminated"))
{
g_debug ("%s: %s", session->name, problem);
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Authentication failed: %s", problem);
}
else if (g_str_equal (problem, "access-denied"))
{
g_debug ("permission denied %s", message);
g_set_error_literal (error, COCKPIT_ERROR, COCKPIT_ERROR_PERMISSION_DENIED,
message ? message : "Permission denied");
}
else
{
g_debug ("%s: errored %s: %s", session->name, problem, message);
if (message)
{
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
"Authentication failed: %s: %s", problem, message);
}
else
{
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
"Authentication failed: %s", problem);
}
}
free (type);
}
static gboolean
on_transport_control (CockpitTransport *transport,
const char *command,
const gchar *channel,
JsonObject *options,
GBytes *payload,
gpointer user_data)
{
CockpitSession *session = user_data;
const gchar *problem = NULL;
const gchar *message = NULL;
GSimpleAsyncResult *result;
GError *error = NULL;
gboolean ret = TRUE;
if (g_str_equal (command, "init"))
{
g_debug ("session initialized");
g_signal_handler_disconnect (session->transport, session->control_sig);
g_signal_handler_disconnect (session->transport, session->close_sig);
session->control_sig = session->close_sig = 0;
session->initialized = TRUE;
if (cockpit_json_get_string (options, "problem", NULL, &problem) && problem)
{
if (!cockpit_json_get_string (options, "message", NULL, &message))
message = NULL;
propagate_problem_to_error (session, options, problem, message, &error);
if (session->result)
{
g_simple_async_result_take_error (session->result, error);
}
else
{
g_message ("ignoring failure from session process: %s", error->message);
g_error_free (error);
}
}
ret = FALSE; /* Let this message be handled elsewhere */
}
else if (g_str_equal (command, "authorize"))
{
const gchar *challenge;
/* handle x-host-key challenge */
if (cockpit_json_get_string (options, "challenge", NULL, &challenge) && g_strcmp0 (challenge, "x-host-key") == 0)
{
const gchar *cookie;
g_return_val_if_fail (cockpit_json_get_string (options, "cookie", NULL, &cookie), FALSE);
/* return a negative answer; we handle unknown hosts interactively, or want to fail on them */
g_debug ("received x-host-key authorize challenge");
send_authorize_reply (session->transport, cookie, "");
return TRUE;
}
/* handle login ("*") challenge */
g_debug ("received authorize challenge");
if (session->authorize)
json_object_unref (session->authorize);
session->authorize = json_object_ref (options);
if (reply_authorize_challenge (session))
return TRUE;
}
else
{
g_message ("unexpected \"%s\" control message from session before \"init\"", command);
cockpit_transport_close (transport, "protocol-error");
}
if (session->result)
{
result = session->result;
session->result = NULL;
g_simple_async_result_complete (result);
g_object_unref (result);
}
return ret;
}
static void
on_transport_closed (CockpitTransport *transport,
const gchar *problem,
gpointer user_data)
{
CockpitSession *session = user_data;
GSimpleAsyncResult *result;
CockpitPipe *pipe;
GError *error = NULL;
gint status = 0;
if (g_strcmp0 (problem, "timeout") == 0)
{
g_message ("%s: authentication timed out", session->name);
g_set_error (&error, COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
"Authentication failed: Timeout");
}
else if (!session->initialized)
{
pipe = cockpit_pipe_transport_get_pipe (COCKPIT_PIPE_TRANSPORT (transport));
if (cockpit_pipe_get_pid (pipe, NULL))
status = cockpit_pipe_exit_status (pipe);
g_debug ("%s: authentication process exited: %d; problem %s", session->name, status, problem);
if (problem)
{
g_set_error (&error, COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
g_strcmp0 (problem, "no-cockpit") == 0
? "The cockpit package is not installed"
: "Internal error in login process");
}
else
{
g_set_error (&error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Authentication failed");
}
}
if (!error)
{
g_message ("%s: authentication process failed", session->name);
g_set_error (&error, COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
"Authentication internal error");
}
if (session->result)
{
result = session->result;
session->result = NULL;
g_simple_async_result_take_error (result, error);
g_simple_async_result_complete (result);
g_object_unref (result);
}
else
{
g_message ("ignoring failure from session process: %s", error->message);
cockpit_session_reset (session);
g_error_free (error);
}
}
static CockpitCreds *
build_session_credentials (CockpitAuth *self,
GIOStream *connection,
GHashTable *headers,
const char *application,
const char *type,
const char *authorization)
{
CockpitCreds *creds;
const gchar *authorized;
char *user = NULL;
char *raw = NULL;
GBytes *password = NULL;
gchar *remote_peer = NULL;
gchar *csrf_token = NULL;
/* Prepare various credentials */
if (g_strcmp0 (type, "basic") == 0)
{
raw = cockpit_authorize_parse_basic (authorization, &user);
/* If "password" is in the X-Authorize header, we can keep the password for use */
authorized = g_hash_table_lookup (headers, "X-Authorize");
if (!authorized)
authorized = "";
if (strstr (authorized, "password") && raw)
{
password = g_bytes_new_take (raw, strlen (raw));
raw = NULL;
}
}
remote_peer = get_remote_address (connection);
csrf_token = cockpit_auth_nonce (self);
creds = cockpit_creds_new (application,
COCKPIT_CRED_USER, user,
COCKPIT_CRED_PASSWORD, password,
COCKPIT_CRED_RHOST, remote_peer,
COCKPIT_CRED_CSRF_TOKEN, csrf_token,
NULL);
g_free (remote_peer);
if (raw)
{
cockpit_memory_clear (raw, strlen (raw));
free (raw);
}
g_free (csrf_token);
if (password)
g_bytes_unref (password);
free (user);
return creds;
}
static gboolean
on_session_timeout (gpointer data)
{
CockpitSession *session = data;
session->timeout_tag = 0;
if (!session->service || cockpit_web_service_get_idling (session->service))
{
g_info ("session timed out");
cockpit_session_reset (session);
}
return FALSE;
}
static void
on_web_service_idling (CockpitWebService *service,
gpointer data)
{
CockpitSession *session = data;
if (session->timeout_tag)
g_source_remove (session->timeout_tag);
g_debug ("session is idle");
/*
* The minimum amount of time before a request uses this new web service,
* otherwise it will just go away.
*/
session->timeout_tag = g_timeout_add_seconds (cockpit_ws_service_idle,
on_session_timeout,
session);
/*
* Also reset the timer which checks whether anything is going on in the
* entire process or not.
*/
if (session->auth->timeout_tag)
g_source_remove (session->auth->timeout_tag);
session->auth->timeout_tag = g_timeout_add_seconds (cockpit_ws_process_idle,
on_process_timeout, session->auth);
}
static void
on_web_service_destroy (CockpitWebService *service,
gpointer data)
{
on_web_service_idling (service, data);
cockpit_session_reset (data);
}
static CockpitSession *
cockpit_session_create (CockpitAuth *self,
const gchar *name,
CockpitCreds *creds,
CockpitTransport *transport)
{
CockpitSession *session;
session = g_new0 (CockpitSession, 1);
session->refs = 1;
session->name = g_path_get_basename (name);
session->auth = self;
session->service = cockpit_web_service_new (creds, transport);
session->idling_sig = g_signal_connect (session->service, "idling",
G_CALLBACK (on_web_service_idling), session);
session->destroy_sig = g_signal_connect (session->service, "destroy",
G_CALLBACK (on_web_service_destroy), session);
g_object_weak_ref (G_OBJECT (session->service), on_web_service_gone, session);
session->transport = g_object_ref (transport);
session->control_sig = g_signal_connect (transport, "control", G_CALLBACK (on_transport_control), session);
session->close_sig = g_signal_connect (transport, "closed", G_CALLBACK (on_transport_closed), session);
return session;
}
static CockpitSession *
cockpit_session_launch (CockpitAuth *self,
GIOStream *connection,
GHashTable *headers,
const gchar *type,
const gchar *authorization,
const gchar *application,
GError **error)
{
CockpitTransport *transport = NULL;
CockpitSession *session = NULL;
CockpitCreds *creds = NULL;
const gchar *host;
const gchar *action;
const gchar *command;
const gchar *section;
const gchar *program_default;
gchar **env = g_get_environ ();
const gchar *argv[] = {
"command",
"host",
NULL,
};
host = application_parse_host (application);
action = type_option (type, "action", "localhost");
if (g_strcmp0 (action, ACTION_NONE) == 0)
{
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Authentication disabled");
goto out;
}
/* These are the credentials we'll carry around for this session */
creds = build_session_credentials (self, connection, headers,
application, type, authorization);
if (host)
section = COCKPIT_CONF_SSH_SECTION;
else if (self->login_loopback && g_strcmp0 (type, "basic") == 0)
section = COCKPIT_CONF_SSH_SECTION;
else if (g_strcmp0 (action, ACTION_SSH) == 0)
section = COCKPIT_CONF_SSH_SECTION;
else
section = type;
if (g_strcmp0 (section, COCKPIT_CONF_SSH_SECTION) == 0)
{
if (!host)
host = type_option (COCKPIT_CONF_SSH_SECTION, "host", "127.0.0.1");
program_default = cockpit_ws_ssh_program;
}
else
{
program_default = cockpit_ws_session_program;
}
command = type_option (section, "command", program_default);
if (cockpit_creds_get_rhost (creds))
{
env = g_environ_setenv (env, "COCKPIT_REMOTE_PEER",
cockpit_creds_get_rhost (creds),
TRUE);
}
argv[0] = command;
argv[1] = host ? host : "localhost";
transport = session_start_process (argv, (const gchar **)env);
if (!transport)
{
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
"Authentication failed to start");
goto out;
}
session = cockpit_session_create (self, argv[0], creds, transport);
/* How long to wait for the auth process to send some data */
session->authorize_timeout = timeout_option ("timeout", section, cockpit_ws_auth_process_timeout);
/* How long to wait for a response from the client to a auth prompt */
session->client_timeout = timeout_option ("response-timeout", section, cockpit_ws_auth_response_timeout);
out:
g_strfreev (env);
if (creds)
cockpit_creds_unref (creds);
if (transport)
g_object_unref (transport);
return session;
}
static gboolean
build_authorize_challenge (CockpitAuth *self,
JsonObject *authorize,
GIOStream *connection,
GHashTable *headers,
JsonObject **body,
gchar **conversation)
{
const gchar *challenge = NULL;
gchar *type = NULL;
JsonObject *object;
GList *l, *names;
if (!cockpit_json_get_string (authorize, "challenge", NULL, &challenge) ||
!cockpit_authorize_type (challenge, &type))
{
g_message ("invalid \"challenge\" field in \"authorize\" message");
return FALSE;
}
g_hash_table_replace (headers, g_strdup ("WWW-Authenticate"), g_strdup (challenge));
*conversation = NULL;
if (g_str_equal (type, "negotiate"))
{
gssapi_available = 1;
*conversation = cockpit_auth_nonce (self);
if (connection)
g_object_set_data_full (G_OBJECT (connection), "negotiate", g_strdup (*conversation), g_free);
}
else if (g_str_equal (type, "x-conversation"))
{
cockpit_authorize_subject (challenge, conversation);
}
object = json_object_new ();
names = json_object_get_members (authorize);
for (l = names; l != NULL; l = g_list_next (l))
{
if (!g_str_equal (l->data, "challenge") && !g_str_equal (l->data, "cookie"))
json_object_set_member (object, l->data, json_object_dup_member (authorize, l->data));
}
if (body)
*body = object;
g_list_free (names);
g_free (type);
return TRUE;
}
static void
authorize_logger (const char *data)
{
g_message ("%s", data);
}
static void
cockpit_auth_class_init (CockpitAuthClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = cockpit_auth_finalize;
sig__idling = g_signal_new ("idling", COCKPIT_TYPE_AUTH, G_SIGNAL_RUN_FIRST,
0, NULL, NULL, NULL, G_TYPE_NONE, 0);
cockpit_authorize_logger (authorize_logger, 0);
}
static gchar *
base64_decode_string (const char *enc)
{
gchar *dec;
gsize len;
if (enc == NULL)
return NULL;
dec = (gchar *)g_base64_decode (enc, &len);
if (dec)
dec[len] = '\0';
return dec;
}
static CockpitSession *
session_for_headers (CockpitAuth *self,
const gchar *path,
GHashTable *in_headers)
{
gchar *cookie = NULL;
gchar *raw = NULL;
const char *prefix = "v=2;k=";
CockpitSession *ret = NULL;
gchar *application;
gchar *cookie_name = NULL;
g_return_val_if_fail (self != NULL, FALSE);
g_return_val_if_fail (in_headers != NULL, FALSE);
application = cockpit_auth_parse_application (path, NULL);
if (!application)
return NULL;
cookie_name = application_cookie_name (application);
raw = cockpit_web_server_parse_cookie (in_headers, cookie_name);
if (raw)
{
cookie = base64_decode_string (raw);
if (cookie != NULL)
{
if (g_str_has_prefix (cookie, prefix))
ret = g_hash_table_lookup (self->sessions, cookie);
else
g_debug ("invalid or unsupported cookie: %s", cookie);
/* We must never find the default session based on a cookie */
g_assert (!ret || !g_str_equal (ret->cookie, LOCAL_SESSION));
g_assert (!ret || !g_str_equal (ret->name, LOCAL_SESSION));
g_free (cookie);
}
g_free (raw);
}
/* Check for a default session for auto-login */
if (!ret)
ret = g_hash_table_lookup (self->sessions, LOCAL_SESSION);
g_free (application);
g_free (cookie_name);
return ret;
}
CockpitWebService *
cockpit_auth_check_cookie (CockpitAuth *self,
const gchar *path,
GHashTable *in_headers)
{
CockpitSession *session;
CockpitCreds *creds;
session = session_for_headers (self, path, in_headers);
if (session)
{
creds = cockpit_web_service_get_creds (session->service);
g_debug ("received %s credential cookie for session",
cockpit_creds_get_application (creds));
return g_object_ref (session->service);
}
else
{
g_debug ("received unknown/invalid credential cookie");
return NULL;
}
}
void
cockpit_auth_local_async (CockpitAuth *self,
const gchar *user,
CockpitPipe *pipe,
GAsyncReadyCallback callback,
gpointer user_data)
{
CockpitTransport *transport;
CockpitSession *session;
CockpitCreds *creds;
gchar *csrf_token;
g_return_if_fail (COCKPIT_IS_AUTH (self));
g_return_if_fail (COCKPIT_IS_PIPE (pipe));
g_return_if_fail (user != NULL);
transport = cockpit_pipe_transport_new (pipe);
csrf_token = cockpit_auth_nonce (self);
creds = cockpit_creds_new ("cockpit",
COCKPIT_CRED_USER, user,
COCKPIT_CRED_RHOST, "localhost",
COCKPIT_CRED_CSRF_TOKEN, csrf_token,
NULL);
session = cockpit_session_create (self, cockpit_pipe_get_name (pipe), creds, transport);
session->cookie = g_strdup (LOCAL_SESSION);
g_hash_table_insert (self->sessions, session->cookie, session);
session->result = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
cockpit_auth_local_async);
g_free (csrf_token);
g_object_unref (transport);
cockpit_creds_unref (creds);
}
gboolean
cockpit_auth_local_finish (CockpitAuth *self,
GAsyncResult *result,
GError **error)
{
g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self),
cockpit_auth_local_async), FALSE);
return g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result), error);
}
/*
* returns TRUE if auth can proceed, FALSE otherwise.
* dropping starts at connection max_startups_begin with a probability
* of (max_startups_rate/100). the probability increases linearly until
* all connections are dropped for startups > max_startups
*/
static gboolean
can_start_auth (CockpitAuth *self)
{
int p, r;
/* 0 means unlimited */
if (self->max_startups == 0)
return TRUE;
/* Under soft limit */
if (self->startups <= self->max_startups_begin)
return TRUE;
/* Over hard limit */
if (self->startups > self->max_startups)
return FALSE;
/* If rate is 100, soft limit is hard limit */
if (self->max_startups_rate == 100)
return FALSE;
p = 100 - self->max_startups_rate;
p *= self->startups - self->max_startups_begin;
p /= self->max_startups - self->max_startups_begin;
p += self->max_startups_rate;
r = g_random_int_range (0, 100);
g_debug ("calculating if auth can start: (%u:%u:%u): p %d, r %d",
self->max_startups_begin, self->max_startups_rate,
self->max_startups, p, r);
return (r < p) ? FALSE : TRUE;
}
void
cockpit_auth_login_async (CockpitAuth *self,
const gchar *path,
GIOStream *connection,
GHashTable *headers,
GAsyncReadyCallback callback,
gpointer user_data)
{
GSimpleAsyncResult *result = NULL;
CockpitSession *session;
GError *error = NULL;
gchar *type = NULL;
gchar *conversation = NULL;
gchar *authorization = NULL;
gchar *application = NULL;
g_return_if_fail (path != NULL);
g_return_if_fail (headers != NULL);
self->startups++;
result = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
cockpit_auth_login_async);
if (!can_start_auth (self))
{
g_message ("Request dropped; too many startup connections: %u", self->startups);
g_simple_async_result_set_error (result, COCKPIT_ERROR, COCKPIT_ERROR_FAILED,
"Connection closed by host");
g_simple_async_result_complete_in_idle (result);
goto out;
}
application = cockpit_auth_parse_application (path, NULL);
authorization = cockpit_auth_steal_authorization (headers, connection, &type, &conversation);
if (!application || !authorization)
{
g_simple_async_result_set_error (result, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Authentication required");
g_simple_async_result_complete_in_idle (result);
goto out;
}
if (conversation)
{
session = g_hash_table_lookup (self->conversations, conversation);
if (!session)
{
g_simple_async_result_set_error (result, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Invalid conversation token");
g_simple_async_result_complete_in_idle (result);
goto out;
}
g_simple_async_result_set_op_res_gpointer (result, cockpit_session_ref (session), cockpit_session_unref);
}
else
{
session = cockpit_session_launch (self, connection, headers, type, authorization, application, &error);
if (!session)
{
g_simple_async_result_take_error (result, error);
g_simple_async_result_complete_in_idle (result);
goto out;
}
g_simple_async_result_set_op_res_gpointer (result, session, cockpit_session_unref);
}
cockpit_session_reset (session);
session->result = g_object_ref (result);
session->authorization = authorization;
authorization = NULL;
if (conversation && !reply_authorize_challenge (session))
{
g_simple_async_result_set_error (result, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Invalid conversation reply");
g_simple_async_result_complete_in_idle (result);
goto out;
}
reset_authorize_timeout (session, FALSE);
out:
g_free (type);
g_free (application);
g_free (conversation);
if (authorization)
{
cockpit_memory_clear (authorization, -1);
g_free (authorization);
}
g_object_unref (result);
}
JsonObject *
cockpit_auth_login_finish (CockpitAuth *self,
GAsyncResult *result,
GIOStream *connection,
GHashTable *headers,
GError **error)
{
JsonObject *body = NULL;
CockpitCreds *creds = NULL;
CockpitSession *session = NULL;
gboolean force_secure;
gchar *cookie_name;
gchar *cookie_b64;
gchar *header;
gchar *id;
g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self),
cockpit_auth_login_async), NULL);
g_object_ref (result);
session = g_simple_async_result_get_op_res_gpointer (G_SIMPLE_ASYNC_RESULT (result));
if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result), error))
goto out;
g_return_val_if_fail (session != NULL, NULL);
g_return_val_if_fail (session->result == NULL, NULL);
cockpit_session_reset (session);
if (session->authorize)
{
if (build_authorize_challenge (self, session->authorize, connection,
headers, &body, &session->conversation))
{
if (session->conversation)
{
reset_authorize_timeout (session, TRUE);
g_hash_table_replace (self->conversations, session->conversation, cockpit_session_ref (session));
}
}
}
if (session->initialized)
{
/* Start off in the idling state, and begin a timeout during which caller must do something else */
on_web_service_idling (session->service, session);
creds = cockpit_web_service_get_creds (session->service);
id = cockpit_auth_nonce (self);
session->cookie = g_strdup_printf ("v=2;k=%s", id);
g_hash_table_insert (self->sessions, session->cookie, cockpit_session_ref (session));
g_free (id);
if (headers)
{
force_secure = connection ? !G_IS_SOCKET_CONNECTION (connection) : TRUE;
cookie_name = application_cookie_name (cockpit_creds_get_application (creds));
cookie_b64 = g_base64_encode ((guint8 *)session->cookie, strlen (session->cookie));
header = g_strdup_printf ("%s=%s; Path=/; %s HttpOnly",
cookie_name, cookie_b64,
force_secure ? " Secure;" : "");
g_free (cookie_b64);
g_free (cookie_name);
g_hash_table_insert (headers, g_strdup ("Set-Cookie"), header);
}
if (body)
json_object_unref (body);
body = cockpit_creds_to_json (creds);
}
else
{
g_set_error (error, COCKPIT_ERROR, COCKPIT_ERROR_AUTHENTICATION_FAILED,
"Authentication failed");
}
out:
self->startups--;
g_object_unref (result);
/* Successful login */
if (creds)
g_info ("logged in user session");
return body;
}
CockpitAuth *
cockpit_auth_new (gboolean login_loopback)
{
CockpitAuth *self = g_object_new (COCKPIT_TYPE_AUTH, NULL);
const gchar *max_startups_conf;
gint count = 0;
self->login_loopback = login_loopback;
if (cockpit_ws_max_startups == NULL)
max_startups_conf = cockpit_conf_string ("WebService", "MaxStartups");
else
max_startups_conf = cockpit_ws_max_startups;
self->max_startups = max_startups;
self->max_startups_begin = max_startups;
self->max_startups_rate = 100;
if (max_startups_conf)
{
count = sscanf (max_startups_conf, "%u:%u:%u",
&self->max_startups_begin,
&self->max_startups_rate,
&self->max_startups);
/* If all three numbers are not given use the
* first as a hard limit */
if (count == 1 || count == 2)
{
self->max_startups = self->max_startups_begin;
self->max_startups_rate = 100;
}
if (count < 1 || count > 3 ||
self->max_startups_begin > self->max_startups ||
self->max_startups_rate > 100 || self->max_startups_rate < 1)
{
g_warning ("Illegal MaxStartups spec: %s. Reverting to defaults", max_startups_conf);
self->max_startups = max_startups;
self->max_startups_begin = max_startups;
self->max_startups_rate = 100;
}
}
return self;
}
gchar *
cockpit_auth_parse_application (const gchar *path,
gboolean *is_host)
{
const gchar *pos;
gchar *tmp = NULL;
gchar *val = NULL;
g_return_val_if_fail (path != NULL, NULL);
g_return_val_if_fail (path[0] == '/', NULL);
path += 1;
/* We are being embedded as a specific application */
if (g_str_has_prefix (path, "cockpit+") && path[8] != '\0')
{
pos = strchr (path, '/');
if (pos)
val = g_strndup (path, pos - path);
else
val = g_strdup (path);
}
else if (path[0] == '=' && path[1] != '\0')
{
pos = strchr (path, '/');
if (pos)
{
tmp = g_strndup (path, pos - path);
val = g_strdup_printf ("cockpit+%s", tmp);
}
else
{
val = g_strdup_printf ("cockpit+%s", path);
}
}
else
{
val = g_strdup ("cockpit");
}
if (is_host)
*is_host = application_parse_host (val) != NULL;
g_free (tmp);
return val;
}
gchar *
cockpit_auth_empty_cookie_value (const gchar *path)
{
gchar *application = cockpit_auth_parse_application (path, NULL);
gchar *cookie = application_cookie_name (application);
gchar *cookie_line = g_strdup_printf ("%s=deleted; PATH=/; HttpOnly", cookie);
g_free (application);
g_free (cookie);
return cookie_line;
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_1389_0 |
crossvul-cpp_data_bad_907_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% CCC U U TTTTT %
% C U U T %
% C U U T %
% C U U T %
% CCC UUU T %
% %
% %
% Read DR Halo Image Format %
% %
% Software Design %
% Jaroslav Fojtik %
% June 2000 %
% %
% %
% Permission is hereby granted, free of charge, to any person obtaining a %
% copy of this software and associated documentation files ("ImageMagick"), %
% to deal in ImageMagick without restriction, including without limitation %
% the rights to use, copy, modify, merge, publish, distribute, sublicense, %
% and/or sell copies of ImageMagick, and to permit persons to whom the %
% ImageMagick is furnished to do so, subject to the following conditions: %
% %
% The above copyright notice and this permission notice shall be included in %
% all copies or substantial portions of ImageMagick. %
% %
% The software is provided "as is", without warranty of any kind, express or %
% implied, including but not limited to the warranties of merchantability, %
% fitness for a particular purpose and noninfringement. In no event shall %
% ImageMagick Studio be liable for any claim, damages or other liability, %
% whether in an action of contract, tort or otherwise, arising from, out of %
% or in connection with ImageMagick or the use or other dealings in %
% ImageMagick. %
% %
% Except as contained in this notice, the name of the ImageMagick Studio %
% shall not be used in advertising or otherwise to promote the sale, use or %
% other dealings in ImageMagick without prior written authorization from the %
% ImageMagick Studio. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colormap.h"
#include "magick/colormap-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/pixel-accessor.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
#include "magick/utility.h"
#include "magick/utility-private.h"
typedef struct
{
unsigned Width;
unsigned Height;
unsigned Reserved;
} CUTHeader;
typedef struct
{
char FileId[2];
unsigned Version;
unsigned Size;
char FileType;
char SubType;
unsigned BoardID;
unsigned GraphicsMode;
unsigned MaxIndex;
unsigned MaxRed;
unsigned MaxGreen;
unsigned MaxBlue;
char PaletteId[20];
} CUTPalHeader;
static MagickBooleanType InsertRow(int bpp,unsigned char *p,ssize_t y,
Image *image)
{
ExceptionInfo
*exception;
int
bit;
ssize_t
x;
register PixelPacket
*q;
IndexPacket
index;
register IndexPacket
*indexes;
exception=(&image->exception);
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
return(MagickFalse);
indexes=GetAuthenticIndexQueue(image);
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=0; bit < 8; bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=0; bit < (ssize_t) (image->columns % 8); bit++)
{
index=((*p) & (0x80 >> bit) ? 0x01 : 0x00);
SetPixelIndex(indexes+x+bit,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
p++;
}
break;
}
case 2: /* Convert PseudoColor scanline. */
{
if ((image->storage_class != PseudoClass) ||
(indexes == (IndexPacket *) NULL))
break;
for (x=0; x < ((ssize_t) image->columns-3); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x3);
SetPixelIndex(indexes+x+1,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
p++;
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) > 1)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
if ((image->columns % 4) > 2)
{
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
}
}
p++;
}
break;
}
case 4: /* Convert PseudoColor scanline. */
{
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
q++;
index=ConstrainColormapIndex(image,(*p) & 0x0f);
SetPixelIndex(indexes+x+1,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
if ((image->columns % 2) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
break;
}
case 8: /* Convert PseudoColor scanline. */
{
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p);
SetPixelIndex(indexes+x,index);
if (index < image->colors)
SetPixelRGBO(q,image->colormap+(ssize_t) index);
p++;
q++;
}
}
break;
case 24: /* Convert DirectColor scanline. */
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ScaleCharToQuantum(*p++));
SetPixelGreen(q,ScaleCharToQuantum(*p++));
SetPixelBlue(q,ScaleCharToQuantum(*p++));
q++;
}
break;
}
if (!SyncAuthenticPixels(image,exception))
return(MagickFalse);
return(MagickTrue);
}
/*
Compute the number of colors in Grayed R[i]=G[i]=B[i] image
*/
static int GetCutColors(Image *image)
{
ExceptionInfo
*exception;
Quantum
intensity,
scale_intensity;
register PixelPacket
*q;
ssize_t
x,
y;
exception=(&image->exception);
intensity=0;
scale_intensity=ScaleCharToQuantum(16);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (intensity < GetPixelRed(q))
intensity=GetPixelRed(q);
if (intensity >= scale_intensity)
return(255);
q++;
}
}
if (intensity < ScaleCharToQuantum(2))
return(2);
if (intensity < ScaleCharToQuantum(16))
return(16);
return((int) intensity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d C U T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadCUTImage() reads an CUT X image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadCUTImage method is:
%
% Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadCUTImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define ThrowCUTReaderException(severity,tag) \
{ \
if (palette != NULL) \
palette=DestroyImage(palette); \
if (clone_info != NULL) \
clone_info=DestroyImageInfo(clone_info); \
ThrowReaderException(severity,tag); \
}
Image *image,*palette;
ImageInfo *clone_info;
MagickBooleanType status;
MagickOffsetType
offset;
size_t EncodedByte;
unsigned char RunCount,RunValue,RunCountMasked;
CUTHeader Header;
CUTPalHeader PalHeader;
ssize_t depth;
ssize_t i,j;
ssize_t ldblk;
unsigned char *BImgBuff=NULL,*ptrB;
PixelPacket *q;
/*
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);
}
/*
Read CUT image.
*/
palette=NULL;
clone_info=NULL;
Header.Width=ReadBlobLSBShort(image);
Header.Height=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.Width==0 || Header.Height==0 || Header.Reserved!=0)
CUT_KO: ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
/*---This code checks first line of image---*/
EncodedByte=ReadBlobLSBShort(image);
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
ldblk=0;
while((int) RunCountMasked!=0) /*end of line?*/
{
i=1;
if((int) RunCount<0x80) i=(ssize_t) RunCountMasked;
offset=SeekBlob(image,TellBlob(image)+i,SEEK_SET);
if (offset < 0)
ThrowCUTReaderException(CorruptImageError,"ImproperImageHeader");
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data*/
EncodedByte-=i+1;
ldblk+=(ssize_t) RunCountMasked;
RunCount=(unsigned char) ReadBlobByte(image);
if(EOFBlob(image) != MagickFalse) goto CUT_KO; /*wrong data: unexpected eof in line*/
RunCountMasked=RunCount & 0x7F;
}
if(EncodedByte!=1) goto CUT_KO; /*wrong data: size incorrect*/
i=0; /*guess a number of bit planes*/
if(ldblk==(int) Header.Width) i=8;
if(2*ldblk==(int) Header.Width) i=4;
if(8*ldblk==(int) Header.Width) i=1;
if(i==0) goto CUT_KO; /*wrong data: incorrect bit planes*/
depth=i;
image->columns=Header.Width;
image->rows=Header.Height;
image->depth=8;
image->colors=(size_t) (GetQuantumRange(1UL*i)+1);
if (image_info->ping != MagickFalse) goto Finish;
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/* ----- Do something with palette ----- */
if ((clone_info=CloneImageInfo(image_info)) == NULL) goto NoPalette;
i=(ssize_t) strlen(clone_info->filename);
j=i;
while(--i>0)
{
if(clone_info->filename[i]=='.')
{
break;
}
if(clone_info->filename[i]=='/' || clone_info->filename[i]=='\\' ||
clone_info->filename[i]==':' )
{
i=j;
break;
}
}
(void) CopyMagickString(clone_info->filename+i,".PAL",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
(void) CopyMagickString(clone_info->filename+i,".pal",(size_t)
(MaxTextExtent-i));
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info->filename[i]='\0';
if((clone_info->file=fopen_utf8(clone_info->filename,"rb"))==NULL)
{
clone_info=DestroyImageInfo(clone_info);
clone_info=NULL;
goto NoPalette;
}
}
}
if( (palette=AcquireImage(clone_info))==NULL ) goto NoPalette;
status=OpenBlob(clone_info,palette,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
ErasePalette:
palette=DestroyImage(palette);
palette=NULL;
goto NoPalette;
}
if(palette!=NULL)
{
(void) ReadBlob(palette,2,(unsigned char *) PalHeader.FileId);
if(strncmp(PalHeader.FileId,"AH",2) != 0) goto ErasePalette;
PalHeader.Version=ReadBlobLSBShort(palette);
PalHeader.Size=ReadBlobLSBShort(palette);
PalHeader.FileType=(char) ReadBlobByte(palette);
PalHeader.SubType=(char) ReadBlobByte(palette);
PalHeader.BoardID=ReadBlobLSBShort(palette);
PalHeader.GraphicsMode=ReadBlobLSBShort(palette);
PalHeader.MaxIndex=ReadBlobLSBShort(palette);
PalHeader.MaxRed=ReadBlobLSBShort(palette);
PalHeader.MaxGreen=ReadBlobLSBShort(palette);
PalHeader.MaxBlue=ReadBlobLSBShort(palette);
(void) ReadBlob(palette,20,(unsigned char *) PalHeader.PaletteId);
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
if(PalHeader.MaxIndex<1) goto ErasePalette;
image->colors=PalHeader.MaxIndex+1;
if (AcquireImageColormap(image,image->colors) == MagickFalse) goto NoMemory;
if(PalHeader.MaxRed==0) PalHeader.MaxRed=(unsigned int) QuantumRange; /*avoid division by 0*/
if(PalHeader.MaxGreen==0) PalHeader.MaxGreen=(unsigned int) QuantumRange;
if(PalHeader.MaxBlue==0) PalHeader.MaxBlue=(unsigned int) QuantumRange;
for(i=0;i<=(int) PalHeader.MaxIndex;i++)
{ /*this may be wrong- I don't know why is palette such strange*/
j=(ssize_t) TellBlob(palette);
if((j % 512)>512-6)
{
j=((j / 512)+1)*512;
offset=SeekBlob(palette,j,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
image->colormap[i].red=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxRed)
{
image->colormap[i].red=ClampToQuantum(((double)
image->colormap[i].red*QuantumRange+(PalHeader.MaxRed>>1))/
PalHeader.MaxRed);
}
image->colormap[i].green=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxGreen)
{
image->colormap[i].green=ClampToQuantum
(((double) image->colormap[i].green*QuantumRange+(PalHeader.MaxGreen>>1))/PalHeader.MaxGreen);
}
image->colormap[i].blue=(Quantum) ReadBlobLSBShort(palette);
if (QuantumRange != (Quantum) PalHeader.MaxBlue)
{
image->colormap[i].blue=ClampToQuantum
(((double)image->colormap[i].blue*QuantumRange+(PalHeader.MaxBlue>>1))/PalHeader.MaxBlue);
}
}
if (EOFBlob(image))
ThrowCUTReaderException(CorruptImageError,"UnexpectedEndOfFile");
}
NoPalette:
if(palette==NULL)
{
image->colors=256;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
{
NoMemory:
ThrowCUTReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
for (i=0; i < (ssize_t)image->colors; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].green=ScaleCharToQuantum((unsigned char) i);
image->colormap[i].blue=ScaleCharToQuantum((unsigned char) i);
}
}
/* ----- Load RLE compressed raster ----- */
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk,
sizeof(*BImgBuff)); /*Ldblk was set in the check phase*/
if(BImgBuff==NULL) goto NoMemory;
offset=SeekBlob(image,6 /*sizeof(Header)*/,SEEK_SET);
if (offset < 0)
{
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
for (i=0; i < (int) Header.Height; i++)
{
EncodedByte=ReadBlobLSBShort(image);
ptrB=BImgBuff;
j=ldblk;
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
while ((int) RunCountMasked != 0)
{
if((ssize_t) RunCountMasked>j)
{ /*Wrong Data*/
RunCountMasked=(unsigned char) j;
if(j==0)
{
break;
}
}
if((int) RunCount>0x80)
{
RunValue=(unsigned char) ReadBlobByte(image);
(void) memset(ptrB,(int) RunValue,(size_t) RunCountMasked);
}
else {
(void) ReadBlob(image,(size_t) RunCountMasked,ptrB);
}
ptrB+=(int) RunCountMasked;
j-=(int) RunCountMasked;
if (EOFBlob(image) != MagickFalse) goto Finish; /* wrong data: unexpected eof in line */
RunCount=(unsigned char) ReadBlobByte(image);
RunCountMasked=RunCount & 0x7F;
}
InsertRow(depth,BImgBuff,i,image);
}
(void) SyncImage(image);
/*detect monochrome image*/
if(palette==NULL)
{ /*attempt to detect binary (black&white) images*/
if ((image->storage_class == PseudoClass) &&
(SetImageGray(image,&image->exception) != MagickFalse))
{
if(GetCutColors(image)==2)
{
for (i=0; i < (ssize_t)image->colors; i++)
{
register Quantum
sample;
sample=ScaleCharToQuantum((unsigned char) i);
if(image->colormap[i].red!=sample) goto Finish;
if(image->colormap[i].green!=sample) goto Finish;
if(image->colormap[i].blue!=sample) goto Finish;
}
image->colormap[1].red=image->colormap[1].green=
image->colormap[1].blue=QuantumRange;
for (i=0; i < (ssize_t)image->rows; i++)
{
q=QueueAuthenticPixels(image,0,i,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (j=0; j < (ssize_t)image->columns; j++)
{
if (GetPixelRed(q) == ScaleCharToQuantum(1))
{
SetPixelRed(q,QuantumRange);
SetPixelGreen(q,QuantumRange);
SetPixelBlue(q,QuantumRange);
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse) goto Finish;
}
}
}
}
Finish:
if (BImgBuff != NULL)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
if (palette != NULL)
palette=DestroyImage(palette);
if (clone_info != NULL)
clone_info=DestroyImageInfo(clone_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r C U T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterCUTImage() adds attributes for the CUT image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterCUTImage method is:
%
% size_t RegisterCUTImage(void)
%
*/
ModuleExport size_t RegisterCUTImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("CUT");
entry->decoder=(DecodeImageHandler *) ReadCUTImage;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("DR Halo");
entry->module=ConstantString("CUT");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r C U T I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterCUTImage() removes format registrations made by the
% CUT module from the list of supported formats.
%
% The format of the UnregisterCUTImage method is:
%
% UnregisterCUTImage(void)
%
*/
ModuleExport void UnregisterCUTImage(void)
{
(void) UnregisterMagickInfo("CUT");
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_907_0 |
crossvul-cpp_data_good_5844_2 | /*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* RAW - implementation of IP "raw" sockets.
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
*
* Fixes:
* Alan Cox : verify_area() fixed up
* Alan Cox : ICMP error handling
* Alan Cox : EMSGSIZE if you send too big a packet
* Alan Cox : Now uses generic datagrams and shared
* skbuff library. No more peek crashes,
* no more backlogs
* Alan Cox : Checks sk->broadcast.
* Alan Cox : Uses skb_free_datagram/skb_copy_datagram
* Alan Cox : Raw passes ip options too
* Alan Cox : Setsocketopt added
* Alan Cox : Fixed error return for broadcasts
* Alan Cox : Removed wake_up calls
* Alan Cox : Use ttl/tos
* Alan Cox : Cleaned up old debugging
* Alan Cox : Use new kernel side addresses
* Arnt Gulbrandsen : Fixed MSG_DONTROUTE in raw sockets.
* Alan Cox : BSD style RAW socket demultiplexing.
* Alan Cox : Beginnings of mrouted support.
* Alan Cox : Added IP_HDRINCL option.
* Alan Cox : Skip broadcast check if BSDism set.
* David S. Miller : New socket lookup architecture.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/types.h>
#include <linux/atomic.h>
#include <asm/byteorder.h>
#include <asm/current.h>
#include <asm/uaccess.h>
#include <asm/ioctls.h>
#include <linux/stddef.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/aio.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/spinlock.h>
#include <linux/sockios.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/mroute.h>
#include <linux/netdevice.h>
#include <linux/in_route.h>
#include <linux/route.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/dst.h>
#include <net/sock.h>
#include <linux/ip.h>
#include <linux/net.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/raw.h>
#include <net/snmp.h>
#include <net/tcp_states.h>
#include <net/inet_common.h>
#include <net/checksum.h>
#include <net/xfrm.h>
#include <linux/rtnetlink.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/compat.h>
static struct raw_hashinfo raw_v4_hashinfo = {
.lock = __RW_LOCK_UNLOCKED(raw_v4_hashinfo.lock),
};
void raw_hash_sk(struct sock *sk)
{
struct raw_hashinfo *h = sk->sk_prot->h.raw_hash;
struct hlist_head *head;
head = &h->ht[inet_sk(sk)->inet_num & (RAW_HTABLE_SIZE - 1)];
write_lock_bh(&h->lock);
sk_add_node(sk, head);
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
write_unlock_bh(&h->lock);
}
EXPORT_SYMBOL_GPL(raw_hash_sk);
void raw_unhash_sk(struct sock *sk)
{
struct raw_hashinfo *h = sk->sk_prot->h.raw_hash;
write_lock_bh(&h->lock);
if (sk_del_node_init(sk))
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
write_unlock_bh(&h->lock);
}
EXPORT_SYMBOL_GPL(raw_unhash_sk);
static struct sock *__raw_v4_lookup(struct net *net, struct sock *sk,
unsigned short num, __be32 raddr, __be32 laddr, int dif)
{
sk_for_each_from(sk) {
struct inet_sock *inet = inet_sk(sk);
if (net_eq(sock_net(sk), net) && inet->inet_num == num &&
!(inet->inet_daddr && inet->inet_daddr != raddr) &&
!(inet->inet_rcv_saddr && inet->inet_rcv_saddr != laddr) &&
!(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif))
goto found; /* gotcha */
}
sk = NULL;
found:
return sk;
}
/*
* 0 - deliver
* 1 - block
*/
static int icmp_filter(const struct sock *sk, const struct sk_buff *skb)
{
struct icmphdr _hdr;
const struct icmphdr *hdr;
hdr = skb_header_pointer(skb, skb_transport_offset(skb),
sizeof(_hdr), &_hdr);
if (!hdr)
return 1;
if (hdr->type < 32) {
__u32 data = raw_sk(sk)->filter.data;
return ((1U << hdr->type) & data) != 0;
}
/* Do not block unknown ICMP types */
return 0;
}
/* IP input processing comes here for RAW socket delivery.
* Caller owns SKB, so we must make clones.
*
* RFC 1122: SHOULD pass TOS value up to the transport layer.
* -> It does. And not only TOS, but all IP header.
*/
static int raw_v4_input(struct sk_buff *skb, const struct iphdr *iph, int hash)
{
struct sock *sk;
struct hlist_head *head;
int delivered = 0;
struct net *net;
read_lock(&raw_v4_hashinfo.lock);
head = &raw_v4_hashinfo.ht[hash];
if (hlist_empty(head))
goto out;
net = dev_net(skb->dev);
sk = __raw_v4_lookup(net, __sk_head(head), iph->protocol,
iph->saddr, iph->daddr,
skb->dev->ifindex);
while (sk) {
delivered = 1;
if (iph->protocol != IPPROTO_ICMP || !icmp_filter(sk, skb)) {
struct sk_buff *clone = skb_clone(skb, GFP_ATOMIC);
/* Not releasing hash table! */
if (clone)
raw_rcv(sk, clone);
}
sk = __raw_v4_lookup(net, sk_next(sk), iph->protocol,
iph->saddr, iph->daddr,
skb->dev->ifindex);
}
out:
read_unlock(&raw_v4_hashinfo.lock);
return delivered;
}
int raw_local_deliver(struct sk_buff *skb, int protocol)
{
int hash;
struct sock *raw_sk;
hash = protocol & (RAW_HTABLE_SIZE - 1);
raw_sk = sk_head(&raw_v4_hashinfo.ht[hash]);
/* If there maybe a raw socket we must check - if not we
* don't care less
*/
if (raw_sk && !raw_v4_input(skb, ip_hdr(skb), hash))
raw_sk = NULL;
return raw_sk != NULL;
}
static void raw_err(struct sock *sk, struct sk_buff *skb, u32 info)
{
struct inet_sock *inet = inet_sk(sk);
const int type = icmp_hdr(skb)->type;
const int code = icmp_hdr(skb)->code;
int err = 0;
int harderr = 0;
if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
ipv4_sk_update_pmtu(skb, sk, info);
else if (type == ICMP_REDIRECT) {
ipv4_sk_redirect(skb, sk);
return;
}
/* Report error on raw socket, if:
1. User requested ip_recverr.
2. Socket is connected (otherwise the error indication
is useless without ip_recverr and error is hard.
*/
if (!inet->recverr && sk->sk_state != TCP_ESTABLISHED)
return;
switch (type) {
default:
case ICMP_TIME_EXCEEDED:
err = EHOSTUNREACH;
break;
case ICMP_SOURCE_QUENCH:
return;
case ICMP_PARAMETERPROB:
err = EPROTO;
harderr = 1;
break;
case ICMP_DEST_UNREACH:
err = EHOSTUNREACH;
if (code > NR_ICMP_UNREACH)
break;
err = icmp_err_convert[code].errno;
harderr = icmp_err_convert[code].fatal;
if (code == ICMP_FRAG_NEEDED) {
harderr = inet->pmtudisc != IP_PMTUDISC_DONT;
err = EMSGSIZE;
}
}
if (inet->recverr) {
const struct iphdr *iph = (const struct iphdr *)skb->data;
u8 *payload = skb->data + (iph->ihl << 2);
if (inet->hdrincl)
payload = skb->data;
ip_icmp_error(sk, skb, err, 0, info, payload);
}
if (inet->recverr || harderr) {
sk->sk_err = err;
sk->sk_error_report(sk);
}
}
void raw_icmp_error(struct sk_buff *skb, int protocol, u32 info)
{
int hash;
struct sock *raw_sk;
const struct iphdr *iph;
struct net *net;
hash = protocol & (RAW_HTABLE_SIZE - 1);
read_lock(&raw_v4_hashinfo.lock);
raw_sk = sk_head(&raw_v4_hashinfo.ht[hash]);
if (raw_sk != NULL) {
iph = (const struct iphdr *)skb->data;
net = dev_net(skb->dev);
while ((raw_sk = __raw_v4_lookup(net, raw_sk, protocol,
iph->daddr, iph->saddr,
skb->dev->ifindex)) != NULL) {
raw_err(raw_sk, skb, info);
raw_sk = sk_next(raw_sk);
iph = (const struct iphdr *)skb->data;
}
}
read_unlock(&raw_v4_hashinfo.lock);
}
static int raw_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
/* Charge it to the socket. */
ipv4_pktinfo_prepare(sk, skb);
if (sock_queue_rcv_skb(sk, skb) < 0) {
kfree_skb(skb);
return NET_RX_DROP;
}
return NET_RX_SUCCESS;
}
int raw_rcv(struct sock *sk, struct sk_buff *skb)
{
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
atomic_inc(&sk->sk_drops);
kfree_skb(skb);
return NET_RX_DROP;
}
nf_reset(skb);
skb_push(skb, skb->data - skb_network_header(skb));
raw_rcv_skb(sk, skb);
return 0;
}
static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4,
void *from, size_t length,
struct rtable **rtp,
unsigned int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct net *net = sock_net(sk);
struct iphdr *iph;
struct sk_buff *skb;
unsigned int iphlen;
int err;
struct rtable *rt = *rtp;
int hlen, tlen;
if (length > rt->dst.dev->mtu) {
ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
rt->dst.dev->mtu);
return -EMSGSIZE;
}
if (flags&MSG_PROBE)
goto out;
hlen = LL_RESERVED_SPACE(rt->dst.dev);
tlen = rt->dst.dev->needed_tailroom;
skb = sock_alloc_send_skb(sk,
length + hlen + tlen + 15,
flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto error;
skb_reserve(skb, hlen);
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
skb_dst_set(skb, &rt->dst);
*rtp = NULL;
skb_reset_network_header(skb);
iph = ip_hdr(skb);
skb_put(skb, length);
skb->ip_summed = CHECKSUM_NONE;
skb->transport_header = skb->network_header;
err = -EFAULT;
if (memcpy_fromiovecend((void *)iph, from, 0, length))
goto error_free;
iphlen = iph->ihl * 4;
/*
* We don't want to modify the ip header, but we do need to
* be sure that it won't cause problems later along the network
* stack. Specifically we want to make sure that iph->ihl is a
* sane value. If ihl points beyond the length of the buffer passed
* in, reject the frame as invalid
*/
err = -EINVAL;
if (iphlen > length)
goto error_free;
if (iphlen >= sizeof(*iph)) {
if (!iph->saddr)
iph->saddr = fl4->saddr;
iph->check = 0;
iph->tot_len = htons(length);
if (!iph->id)
ip_select_ident(skb, &rt->dst, NULL);
iph->check = ip_fast_csum((unsigned char *)iph, iph->ihl);
}
if (iph->protocol == IPPROTO_ICMP)
icmp_out_count(net, ((struct icmphdr *)
skb_transport_header(skb))->type);
err = NF_HOOK(NFPROTO_IPV4, NF_INET_LOCAL_OUT, skb, NULL,
rt->dst.dev, dst_output);
if (err > 0)
err = net_xmit_errno(err);
if (err)
goto error;
out:
return 0;
error_free:
kfree_skb(skb);
error:
IP_INC_STATS(net, IPSTATS_MIB_OUTDISCARDS);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
return err;
}
static int raw_probe_proto_opt(struct flowi4 *fl4, struct msghdr *msg)
{
struct iovec *iov;
u8 __user *type = NULL;
u8 __user *code = NULL;
int probed = 0;
unsigned int i;
if (!msg->msg_iov)
return 0;
for (i = 0; i < msg->msg_iovlen; i++) {
iov = &msg->msg_iov[i];
if (!iov)
continue;
switch (fl4->flowi4_proto) {
case IPPROTO_ICMP:
/* check if one-byte field is readable or not. */
if (iov->iov_base && iov->iov_len < 1)
break;
if (!type) {
type = iov->iov_base;
/* check if code field is readable or not. */
if (iov->iov_len > 1)
code = type + 1;
} else if (!code)
code = iov->iov_base;
if (type && code) {
if (get_user(fl4->fl4_icmp_type, type) ||
get_user(fl4->fl4_icmp_code, code))
return -EFAULT;
probed = 1;
}
break;
default:
probed = 1;
break;
}
if (probed)
break;
}
return 0;
}
static int raw_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len)
{
struct inet_sock *inet = inet_sk(sk);
struct ipcm_cookie ipc;
struct rtable *rt = NULL;
struct flowi4 fl4;
int free = 0;
__be32 daddr;
__be32 saddr;
u8 tos;
int err;
struct ip_options_data opt_copy;
err = -EMSGSIZE;
if (len > 0xFFFF)
goto out;
/*
* Check the flags.
*/
err = -EOPNOTSUPP;
if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message */
goto out; /* compatibility */
/*
* Get and verify the address.
*/
if (msg->msg_namelen) {
struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
err = -EINVAL;
if (msg->msg_namelen < sizeof(*usin))
goto out;
if (usin->sin_family != AF_INET) {
pr_info_once("%s: %s forgot to set AF_INET. Fix it!\n",
__func__, current->comm);
err = -EAFNOSUPPORT;
if (usin->sin_family)
goto out;
}
daddr = usin->sin_addr.s_addr;
/* ANK: I did not forget to get protocol from port field.
* I just do not know, who uses this weirdness.
* IP_HDRINCL is much more convenient.
*/
} else {
err = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
}
ipc.addr = inet->inet_saddr;
ipc.opt = NULL;
ipc.tx_flags = 0;
ipc.ttl = 0;
ipc.tos = -1;
ipc.oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
err = ip_cmsg_send(sock_net(sk), msg, &ipc);
if (err)
goto out;
if (ipc.opt)
free = 1;
}
saddr = ipc.addr;
ipc.addr = daddr;
if (!ipc.opt) {
struct ip_options_rcu *inet_opt;
rcu_read_lock();
inet_opt = rcu_dereference(inet->inet_opt);
if (inet_opt) {
memcpy(&opt_copy, inet_opt,
sizeof(*inet_opt) + inet_opt->opt.optlen);
ipc.opt = &opt_copy.opt;
}
rcu_read_unlock();
}
if (ipc.opt) {
err = -EINVAL;
/* Linux does not mangle headers on raw sockets,
* so that IP options + IP_HDRINCL is non-sense.
*/
if (inet->hdrincl)
goto done;
if (ipc.opt->opt.srr) {
if (!daddr)
goto done;
daddr = ipc.opt->opt.faddr;
}
}
tos = get_rtconn_flags(&ipc, sk);
if (msg->msg_flags & MSG_DONTROUTE)
tos |= RTO_ONLINK;
if (ipv4_is_multicast(daddr)) {
if (!ipc.oif)
ipc.oif = inet->mc_index;
if (!saddr)
saddr = inet->mc_addr;
} else if (!ipc.oif)
ipc.oif = inet->uc_index;
flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
RT_SCOPE_UNIVERSE,
inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol,
inet_sk_flowi_flags(sk) | FLOWI_FLAG_CAN_SLEEP |
(inet->hdrincl ? FLOWI_FLAG_KNOWN_NH : 0),
daddr, saddr, 0, 0);
if (!inet->hdrincl) {
err = raw_probe_proto_opt(&fl4, msg);
if (err)
goto done;
}
security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
rt = ip_route_output_flow(sock_net(sk), &fl4, sk);
if (IS_ERR(rt)) {
err = PTR_ERR(rt);
rt = NULL;
goto done;
}
err = -EACCES;
if (rt->rt_flags & RTCF_BROADCAST && !sock_flag(sk, SOCK_BROADCAST))
goto done;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = raw_send_hdrinc(sk, &fl4, msg->msg_iov, len,
&rt, msg->msg_flags);
else {
if (!ipc.addr)
ipc.addr = fl4.daddr;
lock_sock(sk);
err = ip_append_data(sk, &fl4, ip_generic_getfrag,
msg->msg_iov, len, 0,
&ipc, &rt, msg->msg_flags);
if (err)
ip_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE)) {
err = ip_push_pending_frames(sk, &fl4);
if (err == -ENOBUFS && !inet->recverr)
err = 0;
}
release_sock(sk);
}
done:
if (free)
kfree(ipc.opt);
ip_rt_put(rt);
out:
if (err < 0)
return err;
return len;
do_confirm:
dst_confirm(&rt->dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
static void raw_close(struct sock *sk, long timeout)
{
/*
* Raw sockets may have direct kernel references. Kill them.
*/
ip_ra_control(sk, 0, NULL);
sk_common_release(sk);
}
static void raw_destroy(struct sock *sk)
{
lock_sock(sk);
ip_flush_pending_frames(sk);
release_sock(sk);
}
/* This gets rid of all the nasties in af_inet. -DaveM */
static int raw_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_in *addr = (struct sockaddr_in *) uaddr;
int ret = -EINVAL;
int chk_addr_ret;
if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_in))
goto out;
chk_addr_ret = inet_addr_type(sock_net(sk), addr->sin_addr.s_addr);
ret = -EADDRNOTAVAIL;
if (addr->sin_addr.s_addr && chk_addr_ret != RTN_LOCAL &&
chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST)
goto out;
inet->inet_rcv_saddr = inet->inet_saddr = addr->sin_addr.s_addr;
if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
inet->inet_saddr = 0; /* Use device */
sk_dst_reset(sk);
ret = 0;
out: return ret;
}
/*
* This should be easy, if there is something there
* we return it, otherwise we block.
*/
static int raw_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
size_t copied = 0;
int err = -EOPNOTSUPP;
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
struct sk_buff *skb;
if (flags & MSG_OOB)
goto out;
if (flags & MSG_ERRQUEUE) {
err = ip_recv_error(sk, msg, len);
goto out;
}
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_ts_and_drops(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
sin->sin_port = 0;
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
if (err)
return err;
return copied;
}
static int raw_init(struct sock *sk)
{
struct raw_sock *rp = raw_sk(sk);
if (inet_sk(sk)->inet_num == IPPROTO_ICMP)
memset(&rp->filter, 0, sizeof(rp->filter));
return 0;
}
static int raw_seticmpfilter(struct sock *sk, char __user *optval, int optlen)
{
if (optlen > sizeof(struct icmp_filter))
optlen = sizeof(struct icmp_filter);
if (copy_from_user(&raw_sk(sk)->filter, optval, optlen))
return -EFAULT;
return 0;
}
static int raw_geticmpfilter(struct sock *sk, char __user *optval, int __user *optlen)
{
int len, ret = -EFAULT;
if (get_user(len, optlen))
goto out;
ret = -EINVAL;
if (len < 0)
goto out;
if (len > sizeof(struct icmp_filter))
len = sizeof(struct icmp_filter);
ret = -EFAULT;
if (put_user(len, optlen) ||
copy_to_user(optval, &raw_sk(sk)->filter, len))
goto out;
ret = 0;
out: return ret;
}
static int do_raw_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (optname == ICMP_FILTER) {
if (inet_sk(sk)->inet_num != IPPROTO_ICMP)
return -EOPNOTSUPP;
else
return raw_seticmpfilter(sk, optval, optlen);
}
return -ENOPROTOOPT;
}
static int raw_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level != SOL_RAW)
return ip_setsockopt(sk, level, optname, optval, optlen);
return do_raw_setsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
static int compat_raw_setsockopt(struct sock *sk, int level, int optname,
char __user *optval, unsigned int optlen)
{
if (level != SOL_RAW)
return compat_ip_setsockopt(sk, level, optname, optval, optlen);
return do_raw_setsockopt(sk, level, optname, optval, optlen);
}
#endif
static int do_raw_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (optname == ICMP_FILTER) {
if (inet_sk(sk)->inet_num != IPPROTO_ICMP)
return -EOPNOTSUPP;
else
return raw_geticmpfilter(sk, optval, optlen);
}
return -ENOPROTOOPT;
}
static int raw_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level != SOL_RAW)
return ip_getsockopt(sk, level, optname, optval, optlen);
return do_raw_getsockopt(sk, level, optname, optval, optlen);
}
#ifdef CONFIG_COMPAT
static int compat_raw_getsockopt(struct sock *sk, int level, int optname,
char __user *optval, int __user *optlen)
{
if (level != SOL_RAW)
return compat_ip_getsockopt(sk, level, optname, optval, optlen);
return do_raw_getsockopt(sk, level, optname, optval, optlen);
}
#endif
static int raw_ioctl(struct sock *sk, int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ: {
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ: {
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb != NULL)
amount = skb->len;
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
default:
#ifdef CONFIG_IP_MROUTE
return ipmr_ioctl(sk, cmd, (void __user *)arg);
#else
return -ENOIOCTLCMD;
#endif
}
}
#ifdef CONFIG_COMPAT
static int compat_raw_ioctl(struct sock *sk, unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case SIOCOUTQ:
case SIOCINQ:
return -ENOIOCTLCMD;
default:
#ifdef CONFIG_IP_MROUTE
return ipmr_compat_ioctl(sk, cmd, compat_ptr(arg));
#else
return -ENOIOCTLCMD;
#endif
}
}
#endif
struct proto raw_prot = {
.name = "RAW",
.owner = THIS_MODULE,
.close = raw_close,
.destroy = raw_destroy,
.connect = ip4_datagram_connect,
.disconnect = udp_disconnect,
.ioctl = raw_ioctl,
.init = raw_init,
.setsockopt = raw_setsockopt,
.getsockopt = raw_getsockopt,
.sendmsg = raw_sendmsg,
.recvmsg = raw_recvmsg,
.bind = raw_bind,
.backlog_rcv = raw_rcv_skb,
.release_cb = ip4_datagram_release_cb,
.hash = raw_hash_sk,
.unhash = raw_unhash_sk,
.obj_size = sizeof(struct raw_sock),
.h.raw_hash = &raw_v4_hashinfo,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_raw_setsockopt,
.compat_getsockopt = compat_raw_getsockopt,
.compat_ioctl = compat_raw_ioctl,
#endif
};
#ifdef CONFIG_PROC_FS
static struct sock *raw_get_first(struct seq_file *seq)
{
struct sock *sk;
struct raw_iter_state *state = raw_seq_private(seq);
for (state->bucket = 0; state->bucket < RAW_HTABLE_SIZE;
++state->bucket) {
sk_for_each(sk, &state->h->ht[state->bucket])
if (sock_net(sk) == seq_file_net(seq))
goto found;
}
sk = NULL;
found:
return sk;
}
static struct sock *raw_get_next(struct seq_file *seq, struct sock *sk)
{
struct raw_iter_state *state = raw_seq_private(seq);
do {
sk = sk_next(sk);
try_again:
;
} while (sk && sock_net(sk) != seq_file_net(seq));
if (!sk && ++state->bucket < RAW_HTABLE_SIZE) {
sk = sk_head(&state->h->ht[state->bucket]);
goto try_again;
}
return sk;
}
static struct sock *raw_get_idx(struct seq_file *seq, loff_t pos)
{
struct sock *sk = raw_get_first(seq);
if (sk)
while (pos && (sk = raw_get_next(seq, sk)) != NULL)
--pos;
return pos ? NULL : sk;
}
void *raw_seq_start(struct seq_file *seq, loff_t *pos)
{
struct raw_iter_state *state = raw_seq_private(seq);
read_lock(&state->h->lock);
return *pos ? raw_get_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
EXPORT_SYMBOL_GPL(raw_seq_start);
void *raw_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *sk;
if (v == SEQ_START_TOKEN)
sk = raw_get_first(seq);
else
sk = raw_get_next(seq, v);
++*pos;
return sk;
}
EXPORT_SYMBOL_GPL(raw_seq_next);
void raw_seq_stop(struct seq_file *seq, void *v)
{
struct raw_iter_state *state = raw_seq_private(seq);
read_unlock(&state->h->lock);
}
EXPORT_SYMBOL_GPL(raw_seq_stop);
static void raw_sock_seq_show(struct seq_file *seq, struct sock *sp, int i)
{
struct inet_sock *inet = inet_sk(sp);
__be32 dest = inet->inet_daddr,
src = inet->inet_rcv_saddr;
__u16 destp = 0,
srcp = inet->inet_num;
seq_printf(seq, "%4d: %08X:%04X %08X:%04X"
" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d\n",
i, src, srcp, dest, destp, sp->sk_state,
sk_wmem_alloc_get(sp),
sk_rmem_alloc_get(sp),
0, 0L, 0,
from_kuid_munged(seq_user_ns(seq), sock_i_uid(sp)),
0, sock_i_ino(sp),
atomic_read(&sp->sk_refcnt), sp, atomic_read(&sp->sk_drops));
}
static int raw_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_printf(seq, " sl local_address rem_address st tx_queue "
"rx_queue tr tm->when retrnsmt uid timeout "
"inode ref pointer drops\n");
else
raw_sock_seq_show(seq, v, raw_seq_private(seq)->bucket);
return 0;
}
static const struct seq_operations raw_seq_ops = {
.start = raw_seq_start,
.next = raw_seq_next,
.stop = raw_seq_stop,
.show = raw_seq_show,
};
int raw_seq_open(struct inode *ino, struct file *file,
struct raw_hashinfo *h, const struct seq_operations *ops)
{
int err;
struct raw_iter_state *i;
err = seq_open_net(ino, file, ops, sizeof(struct raw_iter_state));
if (err < 0)
return err;
i = raw_seq_private((struct seq_file *)file->private_data);
i->h = h;
return 0;
}
EXPORT_SYMBOL_GPL(raw_seq_open);
static int raw_v4_seq_open(struct inode *inode, struct file *file)
{
return raw_seq_open(inode, file, &raw_v4_hashinfo, &raw_seq_ops);
}
static const struct file_operations raw_seq_fops = {
.owner = THIS_MODULE,
.open = raw_v4_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static __net_init int raw_init_net(struct net *net)
{
if (!proc_create("raw", S_IRUGO, net->proc_net, &raw_seq_fops))
return -ENOMEM;
return 0;
}
static __net_exit void raw_exit_net(struct net *net)
{
remove_proc_entry("raw", net->proc_net);
}
static __net_initdata struct pernet_operations raw_net_ops = {
.init = raw_init_net,
.exit = raw_exit_net,
};
int __init raw_proc_init(void)
{
return register_pernet_subsys(&raw_net_ops);
}
void __init raw_proc_exit(void)
{
unregister_pernet_subsys(&raw_net_ops);
}
#endif /* CONFIG_PROC_FS */
| ./CrossVul/dataset_final_sorted/CWE-20/c/good_5844_2 |
crossvul-cpp_data_bad_5845_2 | /*
*
* Author Karsten Keil <kkeil@novell.com>
*
* Copyright 2008 by Karsten Keil <kkeil@novell.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/mISDNif.h>
#include <linux/slab.h>
#include <linux/export.h>
#include "core.h"
static u_int *debug;
static struct proto mISDN_proto = {
.name = "misdn",
.owner = THIS_MODULE,
.obj_size = sizeof(struct mISDN_sock)
};
#define _pms(sk) ((struct mISDN_sock *)sk)
static struct mISDN_sock_list data_sockets = {
.lock = __RW_LOCK_UNLOCKED(data_sockets.lock)
};
static struct mISDN_sock_list base_sockets = {
.lock = __RW_LOCK_UNLOCKED(base_sockets.lock)
};
#define L2_HEADER_LEN 4
static inline struct sk_buff *
_l2_alloc_skb(unsigned int len, gfp_t gfp_mask)
{
struct sk_buff *skb;
skb = alloc_skb(len + L2_HEADER_LEN, gfp_mask);
if (likely(skb))
skb_reserve(skb, L2_HEADER_LEN);
return skb;
}
static void
mISDN_sock_link(struct mISDN_sock_list *l, struct sock *sk)
{
write_lock_bh(&l->lock);
sk_add_node(sk, &l->head);
write_unlock_bh(&l->lock);
}
static void mISDN_sock_unlink(struct mISDN_sock_list *l, struct sock *sk)
{
write_lock_bh(&l->lock);
sk_del_node_init(sk);
write_unlock_bh(&l->lock);
}
static int
mISDN_send(struct mISDNchannel *ch, struct sk_buff *skb)
{
struct mISDN_sock *msk;
int err;
msk = container_of(ch, struct mISDN_sock, ch);
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s len %d %p\n", __func__, skb->len, skb);
if (msk->sk.sk_state == MISDN_CLOSED)
return -EUNATCH;
__net_timestamp(skb);
err = sock_queue_rcv_skb(&msk->sk, skb);
if (err)
printk(KERN_WARNING "%s: error %d\n", __func__, err);
return err;
}
static int
mISDN_ctrl(struct mISDNchannel *ch, u_int cmd, void *arg)
{
struct mISDN_sock *msk;
msk = container_of(ch, struct mISDN_sock, ch);
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s(%p, %x, %p)\n", __func__, ch, cmd, arg);
switch (cmd) {
case CLOSE_CHANNEL:
msk->sk.sk_state = MISDN_CLOSED;
break;
}
return 0;
}
static inline void
mISDN_sock_cmsg(struct sock *sk, struct msghdr *msg, struct sk_buff *skb)
{
struct timeval tv;
if (_pms(sk)->cmask & MISDN_TIME_STAMP) {
skb_get_timestamp(skb, &tv);
put_cmsg(msg, SOL_MISDN, MISDN_TIME_STAMP, sizeof(tv), &tv);
}
}
static int
mISDN_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sk_buff *skb;
struct sock *sk = sock->sk;
struct sockaddr_mISDN *maddr;
int copied, err;
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s: len %d, flags %x ch.nr %d, proto %x\n",
__func__, (int)len, flags, _pms(sk)->ch.nr,
sk->sk_protocol);
if (flags & (MSG_OOB))
return -EOPNOTSUPP;
if (sk->sk_state == MISDN_CLOSED)
return 0;
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
if (!skb)
return err;
if (msg->msg_namelen >= sizeof(struct sockaddr_mISDN)) {
msg->msg_namelen = sizeof(struct sockaddr_mISDN);
maddr = (struct sockaddr_mISDN *)msg->msg_name;
maddr->family = AF_ISDN;
maddr->dev = _pms(sk)->dev->id;
if ((sk->sk_protocol == ISDN_P_LAPD_TE) ||
(sk->sk_protocol == ISDN_P_LAPD_NT)) {
maddr->channel = (mISDN_HEAD_ID(skb) >> 16) & 0xff;
maddr->tei = (mISDN_HEAD_ID(skb) >> 8) & 0xff;
maddr->sapi = mISDN_HEAD_ID(skb) & 0xff;
} else {
maddr->channel = _pms(sk)->ch.nr;
maddr->sapi = _pms(sk)->ch.addr & 0xFF;
maddr->tei = (_pms(sk)->ch.addr >> 8) & 0xFF;
}
} else {
if (msg->msg_namelen)
printk(KERN_WARNING "%s: too small namelen %d\n",
__func__, msg->msg_namelen);
msg->msg_namelen = 0;
}
copied = skb->len + MISDN_HEADER_LEN;
if (len < copied) {
if (flags & MSG_PEEK)
atomic_dec(&skb->users);
else
skb_queue_head(&sk->sk_receive_queue, skb);
return -ENOSPC;
}
memcpy(skb_push(skb, MISDN_HEADER_LEN), mISDN_HEAD_P(skb),
MISDN_HEADER_LEN);
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
mISDN_sock_cmsg(sk, msg, skb);
skb_free_datagram(sk, skb);
return err ? : copied;
}
static int
mISDN_sock_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int err = -ENOMEM;
struct sockaddr_mISDN *maddr;
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s: len %d flags %x ch %d proto %x\n",
__func__, (int)len, msg->msg_flags, _pms(sk)->ch.nr,
sk->sk_protocol);
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
if (msg->msg_flags & ~(MSG_DONTWAIT | MSG_NOSIGNAL | MSG_ERRQUEUE))
return -EINVAL;
if (len < MISDN_HEADER_LEN)
return -EINVAL;
if (sk->sk_state != MISDN_BOUND)
return -EBADFD;
lock_sock(sk);
skb = _l2_alloc_skb(len, GFP_KERNEL);
if (!skb)
goto done;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
err = -EFAULT;
goto done;
}
memcpy(mISDN_HEAD_P(skb), skb->data, MISDN_HEADER_LEN);
skb_pull(skb, MISDN_HEADER_LEN);
if (msg->msg_namelen >= sizeof(struct sockaddr_mISDN)) {
/* if we have a address, we use it */
maddr = (struct sockaddr_mISDN *)msg->msg_name;
mISDN_HEAD_ID(skb) = maddr->channel;
} else { /* use default for L2 messages */
if ((sk->sk_protocol == ISDN_P_LAPD_TE) ||
(sk->sk_protocol == ISDN_P_LAPD_NT))
mISDN_HEAD_ID(skb) = _pms(sk)->ch.nr;
}
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s: ID:%x\n",
__func__, mISDN_HEAD_ID(skb));
err = -ENODEV;
if (!_pms(sk)->ch.peer)
goto done;
err = _pms(sk)->ch.recv(_pms(sk)->ch.peer, skb);
if (err)
goto done;
else {
skb = NULL;
err = len;
}
done:
if (skb)
kfree_skb(skb);
release_sock(sk);
return err;
}
static int
data_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s(%p) sk=%p\n", __func__, sock, sk);
if (!sk)
return 0;
switch (sk->sk_protocol) {
case ISDN_P_TE_S0:
case ISDN_P_NT_S0:
case ISDN_P_TE_E1:
case ISDN_P_NT_E1:
if (sk->sk_state == MISDN_BOUND)
delete_channel(&_pms(sk)->ch);
else
mISDN_sock_unlink(&data_sockets, sk);
break;
case ISDN_P_LAPD_TE:
case ISDN_P_LAPD_NT:
case ISDN_P_B_RAW:
case ISDN_P_B_HDLC:
case ISDN_P_B_X75SLP:
case ISDN_P_B_L2DTMF:
case ISDN_P_B_L2DSP:
case ISDN_P_B_L2DSPHDLC:
delete_channel(&_pms(sk)->ch);
mISDN_sock_unlink(&data_sockets, sk);
break;
}
lock_sock(sk);
sock_orphan(sk);
skb_queue_purge(&sk->sk_receive_queue);
release_sock(sk);
sock_put(sk);
return 0;
}
static int
data_sock_ioctl_bound(struct sock *sk, unsigned int cmd, void __user *p)
{
struct mISDN_ctrl_req cq;
int err = -EINVAL, val[2];
struct mISDNchannel *bchan, *next;
lock_sock(sk);
if (!_pms(sk)->dev) {
err = -ENODEV;
goto done;
}
switch (cmd) {
case IMCTRLREQ:
if (copy_from_user(&cq, p, sizeof(cq))) {
err = -EFAULT;
break;
}
if ((sk->sk_protocol & ~ISDN_P_B_MASK) == ISDN_P_B_START) {
list_for_each_entry_safe(bchan, next,
&_pms(sk)->dev->bchannels, list) {
if (bchan->nr == cq.channel) {
err = bchan->ctrl(bchan,
CONTROL_CHANNEL, &cq);
break;
}
}
} else
err = _pms(sk)->dev->D.ctrl(&_pms(sk)->dev->D,
CONTROL_CHANNEL, &cq);
if (err)
break;
if (copy_to_user(p, &cq, sizeof(cq)))
err = -EFAULT;
break;
case IMCLEAR_L2:
if (sk->sk_protocol != ISDN_P_LAPD_NT) {
err = -EINVAL;
break;
}
val[0] = cmd;
if (get_user(val[1], (int __user *)p)) {
err = -EFAULT;
break;
}
err = _pms(sk)->dev->teimgr->ctrl(_pms(sk)->dev->teimgr,
CONTROL_CHANNEL, val);
break;
case IMHOLD_L1:
if (sk->sk_protocol != ISDN_P_LAPD_NT
&& sk->sk_protocol != ISDN_P_LAPD_TE) {
err = -EINVAL;
break;
}
val[0] = cmd;
if (get_user(val[1], (int __user *)p)) {
err = -EFAULT;
break;
}
err = _pms(sk)->dev->teimgr->ctrl(_pms(sk)->dev->teimgr,
CONTROL_CHANNEL, val);
break;
default:
err = -EINVAL;
break;
}
done:
release_sock(sk);
return err;
}
static int
data_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
int err = 0, id;
struct sock *sk = sock->sk;
struct mISDNdevice *dev;
struct mISDNversion ver;
switch (cmd) {
case IMGETVERSION:
ver.major = MISDN_MAJOR_VERSION;
ver.minor = MISDN_MINOR_VERSION;
ver.release = MISDN_RELEASE;
if (copy_to_user((void __user *)arg, &ver, sizeof(ver)))
err = -EFAULT;
break;
case IMGETCOUNT:
id = get_mdevice_count();
if (put_user(id, (int __user *)arg))
err = -EFAULT;
break;
case IMGETDEVINFO:
if (get_user(id, (int __user *)arg)) {
err = -EFAULT;
break;
}
dev = get_mdevice(id);
if (dev) {
struct mISDN_devinfo di;
memset(&di, 0, sizeof(di));
di.id = dev->id;
di.Dprotocols = dev->Dprotocols;
di.Bprotocols = dev->Bprotocols | get_all_Bprotocols();
di.protocol = dev->D.protocol;
memcpy(di.channelmap, dev->channelmap,
sizeof(di.channelmap));
di.nrbchan = dev->nrbchan;
strcpy(di.name, dev_name(&dev->dev));
if (copy_to_user((void __user *)arg, &di, sizeof(di)))
err = -EFAULT;
} else
err = -ENODEV;
break;
default:
if (sk->sk_state == MISDN_BOUND)
err = data_sock_ioctl_bound(sk, cmd,
(void __user *)arg);
else
err = -ENOTCONN;
}
return err;
}
static int data_sock_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int len)
{
struct sock *sk = sock->sk;
int err = 0, opt = 0;
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s(%p, %d, %x, %p, %d)\n", __func__, sock,
level, optname, optval, len);
lock_sock(sk);
switch (optname) {
case MISDN_TIME_STAMP:
if (get_user(opt, (int __user *)optval)) {
err = -EFAULT;
break;
}
if (opt)
_pms(sk)->cmask |= MISDN_TIME_STAMP;
else
_pms(sk)->cmask &= ~MISDN_TIME_STAMP;
break;
default:
err = -ENOPROTOOPT;
break;
}
release_sock(sk);
return err;
}
static int data_sock_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
int len, opt;
if (get_user(len, optlen))
return -EFAULT;
if (len != sizeof(char))
return -EINVAL;
switch (optname) {
case MISDN_TIME_STAMP:
if (_pms(sk)->cmask & MISDN_TIME_STAMP)
opt = 1;
else
opt = 0;
if (put_user(opt, optval))
return -EFAULT;
break;
default:
return -ENOPROTOOPT;
}
return 0;
}
static int
data_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_mISDN *maddr = (struct sockaddr_mISDN *) addr;
struct sock *sk = sock->sk;
struct sock *csk;
int err = 0;
if (*debug & DEBUG_SOCKET)
printk(KERN_DEBUG "%s(%p) sk=%p\n", __func__, sock, sk);
if (addr_len != sizeof(struct sockaddr_mISDN))
return -EINVAL;
if (!maddr || maddr->family != AF_ISDN)
return -EINVAL;
lock_sock(sk);
if (_pms(sk)->dev) {
err = -EALREADY;
goto done;
}
_pms(sk)->dev = get_mdevice(maddr->dev);
if (!_pms(sk)->dev) {
err = -ENODEV;
goto done;
}
if (sk->sk_protocol < ISDN_P_B_START) {
read_lock_bh(&data_sockets.lock);
sk_for_each(csk, &data_sockets.head) {
if (sk == csk)
continue;
if (_pms(csk)->dev != _pms(sk)->dev)
continue;
if (csk->sk_protocol >= ISDN_P_B_START)
continue;
if (IS_ISDN_P_TE(csk->sk_protocol)
== IS_ISDN_P_TE(sk->sk_protocol))
continue;
read_unlock_bh(&data_sockets.lock);
err = -EBUSY;
goto done;
}
read_unlock_bh(&data_sockets.lock);
}
_pms(sk)->ch.send = mISDN_send;
_pms(sk)->ch.ctrl = mISDN_ctrl;
switch (sk->sk_protocol) {
case ISDN_P_TE_S0:
case ISDN_P_NT_S0:
case ISDN_P_TE_E1:
case ISDN_P_NT_E1:
mISDN_sock_unlink(&data_sockets, sk);
err = connect_layer1(_pms(sk)->dev, &_pms(sk)->ch,
sk->sk_protocol, maddr);
if (err)
mISDN_sock_link(&data_sockets, sk);
break;
case ISDN_P_LAPD_TE:
case ISDN_P_LAPD_NT:
err = create_l2entity(_pms(sk)->dev, &_pms(sk)->ch,
sk->sk_protocol, maddr);
break;
case ISDN_P_B_RAW:
case ISDN_P_B_HDLC:
case ISDN_P_B_X75SLP:
case ISDN_P_B_L2DTMF:
case ISDN_P_B_L2DSP:
case ISDN_P_B_L2DSPHDLC:
err = connect_Bstack(_pms(sk)->dev, &_pms(sk)->ch,
sk->sk_protocol, maddr);
break;
default:
err = -EPROTONOSUPPORT;
}
if (err)
goto done;
sk->sk_state = MISDN_BOUND;
_pms(sk)->ch.protocol = sk->sk_protocol;
done:
release_sock(sk);
return err;
}
static int
data_sock_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sockaddr_mISDN *maddr = (struct sockaddr_mISDN *) addr;
struct sock *sk = sock->sk;
if (!_pms(sk)->dev)
return -EBADFD;
lock_sock(sk);
*addr_len = sizeof(*maddr);
maddr->family = AF_ISDN;
maddr->dev = _pms(sk)->dev->id;
maddr->channel = _pms(sk)->ch.nr;
maddr->sapi = _pms(sk)->ch.addr & 0xff;
maddr->tei = (_pms(sk)->ch.addr >> 8) & 0xff;
release_sock(sk);
return 0;
}
static const struct proto_ops data_sock_ops = {
.family = PF_ISDN,
.owner = THIS_MODULE,
.release = data_sock_release,
.ioctl = data_sock_ioctl,
.bind = data_sock_bind,
.getname = data_sock_getname,
.sendmsg = mISDN_sock_sendmsg,
.recvmsg = mISDN_sock_recvmsg,
.poll = datagram_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = data_sock_setsockopt,
.getsockopt = data_sock_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static int
data_sock_create(struct net *net, struct socket *sock, int protocol)
{
struct sock *sk;
if (sock->type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->ops = &data_sock_ops;
sock->state = SS_UNCONNECTED;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sk->sk_state = MISDN_OPEN;
mISDN_sock_link(&data_sockets, sk);
return 0;
}
static int
base_sock_release(struct socket *sock)
{
struct sock *sk = sock->sk;
printk(KERN_DEBUG "%s(%p) sk=%p\n", __func__, sock, sk);
if (!sk)
return 0;
mISDN_sock_unlink(&base_sockets, sk);
sock_orphan(sk);
sock_put(sk);
return 0;
}
static int
base_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
int err = 0, id;
struct mISDNdevice *dev;
struct mISDNversion ver;
switch (cmd) {
case IMGETVERSION:
ver.major = MISDN_MAJOR_VERSION;
ver.minor = MISDN_MINOR_VERSION;
ver.release = MISDN_RELEASE;
if (copy_to_user((void __user *)arg, &ver, sizeof(ver)))
err = -EFAULT;
break;
case IMGETCOUNT:
id = get_mdevice_count();
if (put_user(id, (int __user *)arg))
err = -EFAULT;
break;
case IMGETDEVINFO:
if (get_user(id, (int __user *)arg)) {
err = -EFAULT;
break;
}
dev = get_mdevice(id);
if (dev) {
struct mISDN_devinfo di;
memset(&di, 0, sizeof(di));
di.id = dev->id;
di.Dprotocols = dev->Dprotocols;
di.Bprotocols = dev->Bprotocols | get_all_Bprotocols();
di.protocol = dev->D.protocol;
memcpy(di.channelmap, dev->channelmap,
sizeof(di.channelmap));
di.nrbchan = dev->nrbchan;
strcpy(di.name, dev_name(&dev->dev));
if (copy_to_user((void __user *)arg, &di, sizeof(di)))
err = -EFAULT;
} else
err = -ENODEV;
break;
case IMSETDEVNAME:
{
struct mISDN_devrename dn;
if (copy_from_user(&dn, (void __user *)arg,
sizeof(dn))) {
err = -EFAULT;
break;
}
dev = get_mdevice(dn.id);
if (dev)
err = device_rename(&dev->dev, dn.name);
else
err = -ENODEV;
}
break;
default:
err = -EINVAL;
}
return err;
}
static int
base_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_mISDN *maddr = (struct sockaddr_mISDN *) addr;
struct sock *sk = sock->sk;
int err = 0;
if (!maddr || maddr->family != AF_ISDN)
return -EINVAL;
lock_sock(sk);
if (_pms(sk)->dev) {
err = -EALREADY;
goto done;
}
_pms(sk)->dev = get_mdevice(maddr->dev);
if (!_pms(sk)->dev) {
err = -ENODEV;
goto done;
}
sk->sk_state = MISDN_BOUND;
done:
release_sock(sk);
return err;
}
static const struct proto_ops base_sock_ops = {
.family = PF_ISDN,
.owner = THIS_MODULE,
.release = base_sock_release,
.ioctl = base_sock_ioctl,
.bind = base_sock_bind,
.getname = sock_no_getname,
.sendmsg = sock_no_sendmsg,
.recvmsg = sock_no_recvmsg,
.poll = sock_no_poll,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.mmap = sock_no_mmap
};
static int
base_sock_create(struct net *net, struct socket *sock, int protocol)
{
struct sock *sk;
if (sock->type != SOCK_RAW)
return -ESOCKTNOSUPPORT;
sk = sk_alloc(net, PF_ISDN, GFP_KERNEL, &mISDN_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
sock->ops = &base_sock_ops;
sock->state = SS_UNCONNECTED;
sock_reset_flag(sk, SOCK_ZAPPED);
sk->sk_protocol = protocol;
sk->sk_state = MISDN_OPEN;
mISDN_sock_link(&base_sockets, sk);
return 0;
}
static int
mISDN_sock_create(struct net *net, struct socket *sock, int proto, int kern)
{
int err = -EPROTONOSUPPORT;
switch (proto) {
case ISDN_P_BASE:
err = base_sock_create(net, sock, proto);
break;
case ISDN_P_TE_S0:
case ISDN_P_NT_S0:
case ISDN_P_TE_E1:
case ISDN_P_NT_E1:
case ISDN_P_LAPD_TE:
case ISDN_P_LAPD_NT:
case ISDN_P_B_RAW:
case ISDN_P_B_HDLC:
case ISDN_P_B_X75SLP:
case ISDN_P_B_L2DTMF:
case ISDN_P_B_L2DSP:
case ISDN_P_B_L2DSPHDLC:
err = data_sock_create(net, sock, proto);
break;
default:
return err;
}
return err;
}
static const struct net_proto_family mISDN_sock_family_ops = {
.owner = THIS_MODULE,
.family = PF_ISDN,
.create = mISDN_sock_create,
};
int
misdn_sock_init(u_int *deb)
{
int err;
debug = deb;
err = sock_register(&mISDN_sock_family_ops);
if (err)
printk(KERN_ERR "%s: error(%d)\n", __func__, err);
return err;
}
void
misdn_sock_cleanup(void)
{
sock_unregister(PF_ISDN);
}
| ./CrossVul/dataset_final_sorted/CWE-20/c/bad_5845_2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.